diff --git a/.patch-version b/.patch-version index 1e8b3149..7f8f011e 100644 --- a/.patch-version +++ b/.patch-version @@ -1 +1 @@ -6 +7 diff --git a/dist/36ad5121226f8c2acd49.worker.js b/dist/0c4a4b990ada4f850f27.worker.js similarity index 98% rename from dist/36ad5121226f8c2acd49.worker.js rename to dist/0c4a4b990ada4f850f27.worker.js index 766a9348..a0502030 100644 --- a/dist/36ad5121226f8c2acd49.worker.js +++ b/dist/0c4a4b990ada4f850f27.worker.js @@ -1,2 +1,2 @@ !function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){"use strict";t.r(r);new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight;self.onerror=e=>{console.error(e),o({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),o({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const n=new Map;function o(e,r){r?postMessage(e,r):postMessage(e)}let s;self.importScripts("rlottie-wasm.js");const a=new Promise(e=>{Module.onRuntimeInitialized=()=>{s={init:Module.cwrap("lottie_init","",[]),destroy:Module.cwrap("lottie_destroy","",["number"]),resize:Module.cwrap("lottie_resize","",["number","number","number"]),buffer:Module.cwrap("lottie_buffer","number",["number"]),render:Module.cwrap("lottie_render","",["number","number"]),loadFromData:Module.cwrap("lottie_load_from_data","number",["number","number"])},e()}}),i=new Map;var c;c={init:async function(e,r,t,n,o,c){s||await a;const u=JSON.stringify(r),d=allocate(intArrayFromString(u),"i8",0),l=s.init(),f=s.loadFromData(l,d);s.resize(l,t,t),i.set(e,{imgSize:t,reduceFactor:o,handle:l}),c(Math.ceil(f/o))},renderFrames:async function(e,r,t,n){s||await a;const{imgSize:o,reduceFactor:c,handle:u}=i.get(e);for(let e=r;e<=t;e++){const r=e*c;s.render(u,r);const t=s.buffer(u),a=Module.HEAPU8.subarray(t,t+o*o*4);n(e,new Uint8ClampedArray(a).buffer)}},destroy:function(e){const r=i.get(e);s.destroy(r.handle),i.delete(e)}},onmessage=async e=>{const{data:r}=e;switch(r.type){case"callMethod":{const{messageId:e,name:t,args:s}=r;try{if(e){const r=(...r)=>{const t=r[r.length-1];o({type:"methodCallback",messageId:e,callbackArgs:r},t instanceof ArrayBuffer?[t]:void 0)};n.set(e,r),s.push(r)}const[r,a]=await c[t](...s)||[];e&&o({type:"methodResponse",messageId:e,response:r},a)}catch(r){e&&o({type:"methodResponse",messageId:e,error:{message:r.message}})}e&&n.delete(e);break}case"cancelProgress":{const e=n.get(r.messageId);e&&(e.isCanceled=!0);break}}}}]); -//# sourceMappingURL=36ad5121226f8c2acd49.worker.js.map \ No newline at end of file +//# sourceMappingURL=0c4a4b990ada4f850f27.worker.js.map \ No newline at end of file diff --git a/dist/36ad5121226f8c2acd49.worker.js.map b/dist/0c4a4b990ada4f850f27.worker.js.map similarity index 99% rename from dist/36ad5121226f8c2acd49.worker.js.map rename to dist/0c4a4b990ada4f850f27.worker.js.map index 63814c9c..3a42b573 100644 --- a/dist/36ad5121226f8c2acd49.worker.js.map +++ b/dist/0c4a4b990ada4f850f27.worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/config.ts","webpack:///./src/util/createWorkerInterface.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Set","window","innerHeight","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","Math","ceil","renderFrames","fromIndex","toIndex","onProgress","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,Q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,GAClC/B,EAAOQ,OAAOkC,OAAOC,SAASF,EAAeA,EAAiBpB,EAAUA,EAAU,GAExFkB,EAAWtF,EADS,IAAI2F,kBAAkB5C,GAAMc,UAgBlDF,QAXF,SAAiBpC,GACf,MAAMqE,EAAW5B,EAAUnD,IAAIU,GAE/B2B,EAAWS,QAAQiC,EAASd,QAE5Bd,EAAU6B,OAAOtE,KDzEjBuE,UAAY5B,UACV,MAAM,KAAEnB,GAASL,EAEjB,OAAQK,EAAKN,MACX,IAAK,aAAc,CACjB,MAAM,UAAEsD,EAAF,KAAaxF,EAAb,KAAmByF,GAASjD,EAClC,IACE,GAAIgD,EAAW,CACb,MAAME,EAAW,IAAIC,KACnB,MAAMC,EAAUD,EAAaA,EAAaE,OAAS,GAEnD5D,EAAa,CACXC,KAAM,iBACNsD,YACAG,gBACCC,aAAmBE,YAAc,CAACF,QAAWG,IAGlDzD,EAAcmC,IAAIe,EAAWE,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAUxD,SAAuBiB,EAAI1D,MAASyF,IAAU,GAE3DD,GACFvD,EACE,CACEC,KAAM,iBACNsD,YACAS,YAEFxD,GAGJ,MAAOT,GAMHwD,GACFvD,EAAa,CACXC,KAAM,iBACNsD,YACAxD,MAAO,CAAEG,QAASH,EAAMG,WAK1BqD,GACFlD,EAAcgD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAME,EAAWpD,EAAchC,IAAIkC,EAAKgD,WACpCE,IACFA,EAASQ,YAAa,GAGxB","file":"36ad5121226f8c2acd49.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 500;\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;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\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;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? [lastArg] : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const [response, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\n }\n };\n}\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/config.ts","webpack:///./src/util/createWorkerInterface.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Set","window","innerHeight","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","Math","ceil","renderFrames","fromIndex","toIndex","onProgress","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,KAQvDrB,EAAoBsB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQrB,EAAoBqB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFA1B,EAAoBkB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOrB,EAAoBU,EAAEe,EAAIE,EAAK,SA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AmBE,YAAc,CAACF,QAAWG,IAGlDzD,EAAcmC,IAAIe,EAAWE,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAUxD,SAAuBiB,EAAI1D,MAASyF,IAAU,GAE3DD,GACFvD,EACE,CACEC,KAAM,iBACNsD,YACAS,YAEFxD,GAGJ,MAAOT,GAMHwD,GACFvD,EAAa,CACXC,KAAM,iBACNsD,YACAxD,MAAO,CAAEG,QAASH,EAAMG,WAK1BqD,GACFlD,EAAcgD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAME,EAAWpD,EAAchC,IAAIkC,EAAKgD,WACpCE,IACFA,EAASQ,YAAa,GAGxB","file":"0c4a4b990ada4f850f27.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 0);\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 500;\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;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\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;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? [lastArg] : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const [response, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\n }\n };\n}\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/3.048f19f68ad10b65610e.js b/dist/3.048f19f68ad10b65610e.js deleted file mode 100644 index 3abb2cb2..00000000 --- a/dist/3.048f19f68ad10b65610e.js +++ /dev/null @@ -1,2 +0,0 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[3],Array(103).concat([function(e,t,a){"use strict";a.r(t),a.d(t,"MediaViewer",(function(){return de})),a.d(t,"ForwardPicker",(function(){return je})),a.d(t,"Errors",(function(){return ke})),a.d(t,"Notifications",(function(){return Ie})),a.d(t,"SafeLinkModal",(function(){return Pe})),a.d(t,"CalendarModal",(function(){return Ae})),a.d(t,"DeleteMessageModal",(function(){return Te})),a.d(t,"PinMessageModal",(function(){return Re})),a.d(t,"UnpinAllMessagesModal",(function(){return De})),a.d(t,"MessageSelectToolbar",(function(){return Ge})),a.d(t,"LeftSearch",(function(){return kt})),a.d(t,"Settings",(function(){return ln})),a.d(t,"ContactList",(function(){return dn})),a.d(t,"NewChat",(function(){return gn})),a.d(t,"NewChatStep1",(function(){return un})),a.d(t,"NewChatStep2",(function(){return hn})),a.d(t,"ArchivedChats",(function(){return vn})),a.d(t,"ContextMenuContainer",(function(){return Pn})),a.d(t,"StickerSetModal",(function(){return Mn})),a.d(t,"HeaderMenuContainer",(function(){return Ln})),a.d(t,"MobileSearch",(function(){return Rn})),a.d(t,"AttachmentModal",(function(){return Kn})),a.d(t,"PollModal",(function(){return Yn})),a.d(t,"SymbolMenu",(function(){return fc})),a.d(t,"AttachMenu",(function(){return jc})),a.d(t,"MentionTooltip",(function(){return _n})),a.d(t,"StickerTooltip",(function(){return Cc})),a.d(t,"BotKeyboardMenu",(function(){return yc})),a.d(t,"CustomSendMenu",(function(){return kc})),a.d(t,"DropArea",(function(){return Nc.b})),a.d(t,"TextFormatter",(function(){return Ic.a})),a.d(t,"EmojiTooltip",(function(){return wc})),a.d(t,"RightSearch",(function(){return Mc})),a.d(t,"StickerSearch",(function(){return Tc})),a.d(t,"GifSearch",(function(){return Rc})),a.d(t,"PollResults",(function(){return Bc})),a.d(t,"Management",(function(){return Xc})),a.d(t,"PaymentModal",(function(){return yr})),a.d(t,"ReceiptModal",(function(){return Ir}));var n=a(0),c=a(2),r=a(5),s=a(20),l=a(1),o=a(7),i=a(115),d=a(6),m=a(4),u=a(3),h=a(132),b=a(47),g=a(177),p=a(26),v=a(108),E=a(120),O=a(191),f=a(38),j=a(48),C=a(146),y=a(56);function k(e,t,a,n){const{mediaEl:c}=P(t,n);if(!c)return;const{width:r}=y.a.get();let o,d=!1;if(n){const{photo:e,video:t,webPage:a}=Object(m.v)(n);d=Boolean(t),o=t?Object(m.bb)(t):Object(m.S)(e||a.photo)}else o=i.a;const{width:u,height:h}=Object(i.j)(e,d),{width:b,height:g}=Object(i.e)(u,h,o.width,o.height),p=(r-b)/2,v=function(e){const t=window.matchMedia(i.b);let a=4.125;e&&(a+=t.matches?.875:3.375);return a*i.c}(e)+(h-g)/2;let{top:E,left:O,width:f,height:j}=c.getBoundingClientRect();if([s.h.SharedMedia,s.h.Album,s.h.ScheduledAlbum,s.h.SearchResult].includes(t)){const e=function(e,t,a,n,c,r){if(e===t){const s=Math.max(c,r)*(e/t);n-=(s-c)/2,a-=(s-r)/2,c=s,r=s}else if(e>t){const a=c;n-=((c=r*(e/t))-a)/2}else if(t>e){const n=r;a-=((r=c*(t/e))-n)/2}return{top:a,left:n,width:c,height:r}}(b,g,E,O,f,j);E=e.top,O=e.left,f=e.width,j=e.height}const C=O+f/2-(p+b/2),k=E+j/2-(v+g/2),N=f/b,S=j/g,F=I(a||c);w(F,{top:v+"px",left:p+"px",width:b+"px",height:g+"px",transform:`translate3d(${C}px, ${k}px, 0) scale(${N}, ${S})`}),M(F,t),document.body.classList.add("ghost-animating"),requestAnimationFrame(()=>{document.body.appendChild(F),requestAnimationFrame(()=>{F.style.transform="",function(e){e.firstChild.style.objectFit="default",e.classList.remove("rounded-corners","circle")}(F),setTimeout(()=>{requestAnimationFrame(()=>{document.body.contains(F)&&document.body.removeChild(F),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function N(e,t,a){const{container:n,mediaEl:c}=P(e,a);if(!c)return;const r=document.getElementById("MediaViewer").querySelector(".active .media-viewer-content img, .active .media-viewer-content video");if(!r||!c)return;const{top:o,left:i,width:d,height:m}=r.getBoundingClientRect(),{top:u,left:h,width:b,height:g}=c.getBoundingClientRect();let p=u;if(!function(e){if("none"===e.style.display)return!1;const t=e.getBoundingClientRect(),{height:a}=y.a.get();return t.top<=a&&t.top+t.height>=0}(n)){const{height:e}=y.a.get();p=uf?O=f:f>O&&(f=O));const C=document.getElementsByClassName("ghost")[0],k=C||I(t||c,e===s.h.ProfileAvatar);C||w(k,{top:p+"px",left:h+"px",width:b+"px",height:g+"px",transform:`translate3d(${v}px, ${E}px, 0) scale(${O}, ${f})`}),requestAnimationFrame(()=>{if(C){const{top:e,left:t,width:a,height:n}=C.getBoundingClientRect();w(k,{transition:"none",top:p+"px",left:h+"px",transformOrigin:"top left",transform:`translate3d(${t-h}px, ${e-p}px, 0) scale(${a/b}, ${n/g})`,width:b+"px",height:g+"px"})}document.body.classList.add("ghost-animating"),C||document.body.appendChild(k),requestAnimationFrame(()=>{C&&(C.style.transition=""),k.style.transform="",j&&(k.style.opacity="0"),M(k,e),setTimeout(()=>{requestAnimationFrame(()=>{document.body.contains(k)&&document.body.removeChild(k),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function I(e,t=!1){const a=document.createElement("div");a.classList.add("ghost");const n=new Image;if("string"==typeof e?n.src=e:e instanceof HTMLVideoElement?n.src=e.poster:n.src=e.src,a.appendChild(n),t){a.classList.add("ProfileInfo");const e=document.querySelector("#RightColumn .ProfileInfo .info");e&&a.appendChild(e.cloneNode(!0))}return a}function S(e,t){const a=document.querySelector(".active > .MessageList");let n=e.offsetTop+t.closest(".content-inner, .WebPage").offsetTop;return e.id.includes("album-media-")&&(n+=e.parentElement.offsetTop+e.closest(".Message").offsetTop),n>a.scrollTop&&n+t.offsetHeight{if(n&&t)return{sender:Object(m.lb)(t)?Object(d.Gb)(e,t):Object(d.f)(e,t)};if(!a||!t)return{};const c=Object(d.k)(e,t,a);return{message:c,sender:c&&Object(d.tb)(e,c)}},(e,t)=>Object(u.l)(t,["closeMediaViewer","focusMessage"]))(({chatId:e,messageId:t,sender:a,isAvatar:c,message:r,closeMediaViewer:s,focusMessage:l})=>{const o=Object(n.m)(()=>{s(),l({chatId:e,messageId:t})},[e,l,t,s]),i=Object(F.a)();if(!a||!r&&!c)return;const d=a.id<0,u=Object(m.V)(i,a);return n.a.createElement("div",{className:"SenderInfo",onClick:o},d?n.a.createElement(x.a,{key:a.id,size:"medium",chat:a}):n.a.createElement(x.a,{key:a.id,size:"medium",user:a}),n.a.createElement("div",{className:"meta"},n.a.createElement("div",{className:"title",dir:"auto"},u&&Object(B.a)(u)),n.a.createElement("div",{className:"date",dir:"auto"},c?i("lng_mediaview_profile_photo"):Object(D.d)(i,1e3*r.date))))}),G=a(178),q=a(62),z=a(42),$=a(121);a(253);var H=({mediaData:e,isVideo:t,isZoomed:a,message:c,fileName:r,isAvatar:s,onCloseMediaViewer:l,onForward:i,onZoomToggle:d})=>{const[u,h]=Object(n.r)(!1),b=t&&c?Object(m.D)(c,"download"):void 0,{mediaData:g,downloadProgress:p}=Object(E.a)(b,!u);Object(n.n)(()=>{u&&g&&(Object(G.a)(g,r),h(!1))},[r,g,u]),Object(n.n)(()=>{h(!1)},[b]);const v=Object(n.m)(e=>{e.stopPropagation(),h(e=>!e)},[]),O=Object(F.a)(),f=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",className:t?"active":void 0,onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]);return o.g?n.a.createElement("div",{className:"MediaViewerActions-mobile"},n.a.createElement(q.a,{trigger:f,positionX:"right"},!s&&n.a.createElement(z.a,{icon:"forward",onClick:i},O("Forward")),t?n.a.createElement(z.a,{icon:u?"close":"download",onClick:v},u?Math.round(100*p)+"% Downloading...":"Download"):n.a.createElement(z.a,{icon:"download",href:e,download:r},O("AccActionDownload"))),u&&n.a.createElement($.a,{progress:p,size:"s",noCross:!0})):n.a.createElement("div",{className:"MediaViewerActions"},!s&&n.a.createElement(n.a.Fragment,null,n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("Forward"),onClick:i},n.a.createElement("i",{className:"icon-forward"}))),t?n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("AccActionDownload"),onClick:v},u?n.a.createElement($.a,{progress:p,size:"s",onClick:v}):n.a.createElement("i",{className:"icon-download"})):n.a.createElement(R.a,{href:e,download:r,round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("AccActionDownload")},n.a.createElement("i",{className:"icon-download"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:a?"Zoom Out":"Zoom In",onClick:d},n.a.createElement("i",{className:a?"icon-zoom-out":"icon-zoom-in"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("Close"),onClick:l},n.a.createElement("i",{className:"icon-close"})))},_=a(9);a(254);var V=({text:e="",isHideable:t,onClick:a})=>{const[c,r]=Object(n.r)(!1);return Object(n.n)(()=>{const e=document.querySelector(".MediaViewerFooter .media-text"),t=()=>{const t=e?e.clientHeight:0;r(t>2*i.c)};t();const a=Object(_.g)(t,500,!0);return window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[]),n.a.createElement("div",{className:"MediaViewerFooter "+(t?"hideable":""),onClick:function(t){e&&t.stopPropagation()}},e&&n.a.createElement("div",{className:"media-viewer-footer-content",onClick:a},n.a.createElement("p",{className:"media-text custom-scroll "+(c?"multiline":""),dir:"auto"},e)))},K=a(35),W=a(137);const Y=function(){if(void 0!==document.fullscreenElement)return"fullscreenElement";if(void 0!==document.mozFullScreenElement)return"mozFullScreenElement";if(void 0!==document.webkitFullscreenElement)return"webkitFullscreenElement";return""}();var Z=a(147),Q=a(136);const X=["bytes","kB","MB","GB","TB","PB"];var J=e=>{const t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**Math.floor(t)).toFixed(1)} ${X[t]}`};a(255);const ee=e=>{e.stopPropagation()};var te=({bufferedProgress:e,currentTime:t,duration:a,fileSize:c,isForceVisible:r,isForceMobileVersion:s,isPlayed:l,isFullscreenSupported:i,isFullscreen:d,onChangeFullscreen:m,onPlayPause:u,onSeek:h})=>{const[b,g]=Object(n.r)(!0);Object(n.n)(()=>{r&&g(r)},[r]),Object(n.n)(()=>{let e;return r||(o.g?g(!1):e=window.setTimeout(()=>{g(!1)},800)),()=>{e&&window.clearTimeout(e)}},[r]),Object(n.n)(()=>((b||r)&&document.body.classList.add("video-controls-visible"),()=>{document.body.classList.remove("video-controls-visible")}),[r,b]);const p=Object(F.a)();var v,E;if(b||r)return n.a.createElement("div",{className:"VideoPlayerControls "+(s?"mobile":""),onClick:ee},function(e,t,a,c){const r=e/t*100,s=100*a;return n.a.createElement("div",{className:"player-seekline"},n.a.createElement("div",{className:"player-seekline-track"},n.a.createElement("div",{className:"player-seekline-buffered",style:`width: ${s||0}%`}),n.a.createElement("div",{className:"player-seekline-played",style:`width: ${r||0}%`}),n.a.createElement("input",{min:"0",max:"100",step:.01,type:"range",onInput:c,className:"player-seekline-input",value:r||0})))}(t,a,e,h),n.a.createElement(R.a,{ariaLabel:p("AccActionPlay"),size:"tiny",ripple:!o.g,color:"translucent-white",className:"play",onClick:u},n.a.createElement("i",{className:l?"icon-pause":"icon-play"})),function(e,t){return n.a.createElement("div",{className:"player-time"},`${Object(D.e)(e)} / ${Object(D.e)(t)}`)}(t,a),e<1&&(v=e,E=c,n.a.createElement("div",{className:"player-file-size"},`${J(E*v)} / ${J(E)}`)),i&&n.a.createElement(R.a,{ariaLabel:"Fullscreen",size:"tiny",color:"translucent-white",className:"fullscreen",onClick:m},n.a.createElement("i",{className:""+(d?"icon-smallscreen":"icon-fullscreen")})))};a(256);function ae(){return(ae=Object.assign||function(e){for(var t=1;t{const m=Object(n.q)(null),[u,h]=Object(n.r)(!o.l||!o.e),[b,g]=Object(n.r)(0),[p,v]=Object(n.r)(!0),[E,O,f]=function(e,t){const[a,c]=Object(n.r)(Boolean(Y&&document[Y]));return Object(n.o)(()=>{const a=()=>{c(Boolean(Y&&document[Y]))},n=()=>{c(!0)},r=()=>{c(!1),t(!1)},s=e.current;return document.addEventListener("fullscreenchange",a,!1),document.addEventListener("webkitfullscreenchange",a,!1),document.addEventListener("mozfullscreenchange",a,!1),s&&(s.addEventListener("webkitbeginfullscreen",n,!1),s.addEventListener("webkitendfullscreen",r,!1)),()=>{document.removeEventListener("fullscreenchange",a,!1),document.removeEventListener("webkitfullscreenchange",a,!1),document.removeEventListener("mozfullscreenchange",a,!1),s&&(s.removeEventListener("webkitbeginfullscreen",n,!1),s.removeEventListener("webkitendfullscreen",r,!1))}},[]),Y||"iOS"===o.o?[a,()=>{e.current&&(Y||"iOS"===o.o)&&(e.current.requestFullscreen?e.current.requestFullscreen():e.current.webkitRequestFullscreen?e.current.webkitRequestFullscreen():e.current.webkitEnterFullscreen?e.current.webkitEnterFullscreen():e.current.mozRequestFullScreen&&e.current.mozRequestFullScreen(),c(!0))},()=>{e.current&&(document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),c(!1))}]:[!1]}(m,h),{isBuffered:j,bufferedProgress:C,bufferingHandlers:y}=Object(W.a)(),{shouldRender:k,transitionClassNames:N}=Object(K.a)(!j,void 0,void 0,"slow");Object(n.n)(()=>{i||!l?m.current.pause():e&&!o.l&&Object(Q.a)(m.current)},[i,l,e]),Object(n.n)(()=>{m.current.currentTime===m.current.duration?(g(0),h(!1)):g(m.current.currentTime)},[b]);const I=Object(n.m)(e=>{e.stopPropagation(),u?(m.current.pause(),h(!1)):(m.current.play(),h(!0))},[u]);Object(Z.a)(m,[]);const S=Object(n.m)(()=>{v(!0)},[]),w=Object(n.m)(()=>{v(!1)},[]),P=Object(n.m)(e=>{g(e.currentTarget.currentTime)},[]),M=Object(n.m)(()=>{g(0),h(!1)},[]),F=Object(n.m)(()=>{E&&f?f():!E&&O&&O()},[f,E,O]),L=Object(n.m)(e=>{e.stopPropagation(),m.current.currentTime=Number(e.target.value)*m.current.duration/100},[]),A=Object(n.m)(e=>{e.stopPropagation(),v(!p)},[p]);Object(n.n)(()=>{const e=e=>{"Enter"!==e.key&&" "!==e.key||I(e)};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}},[I]);const T=c&&`width: ${c.width}px; height: ${c.height}px`,R=`background-image: url(${a})`;return n.a.createElement("div",{className:"VideoPlayer",onClick:!t&&o.g?A:void 0,onMouseOver:t?void 0:S,onMouseOut:t?void 0:w},n.a.createElement("div",{style:T},n.a.createElement("video",ae({ref:m,autoPlay:o.l,playsInline:!0,loop:t,muted:t,id:"media-viewer-video",style:R,onEnded:M},y,{onTimeUpdate:P}),e&&n.a.createElement("source",{src:e}))),k&&n.a.createElement("div",{className:["spinner-container",N].join(" ")},!j&&n.a.createElement("div",{className:"buffering"},"Buffering..."),n.a.createElement($.a,{size:"xl",progress:j?1:r,square:!0,onClick:d})),!t&&!k&&n.a.createElement(te,{isPlayed:u,bufferedProgress:C,currentTime:b,isFullscreenSupported:Boolean(O),isFullscreen:E,fileSize:s,duration:m.current?m.current.duration:0,isForceVisible:!u||p,isForceMobileVersion:c&&c.width<400,onSeek:L,onChangeFullscreen:F,onPlayPause:I}))}),ce=a(8);a(257);var re=Object(n.h)(({isShown:e,onChangeZoom:t})=>{const{transitionClassNames:a}=Object(K.a)(e),c=Object(f.a)(e),r=Object(n.q)(null),[s,l]=Object(n.r)(1),i=Object(n.q)(!1);Object(n.n)(()=>{e&&!c&&l(1.5)},[e,c]);const d=Object(n.m)(()=>{i.current=!0},[]),m=Object(n.m)(()=>{i.current=!1,1===s&&t(s,!i.current)},[t,s]);Object(n.n)(()=>{t(s,!i.current)},[s,t]);const u=Object(F.a)(),h=Object(ce.a)("ZoomControls",a);return n.a.createElement("div",{className:h},n.a.createElement(R.a,{disabled:1===s,size:"tiny",color:"translucent-white",ariaLabel:u("ZoomOut"),className:"zoom-out",ripple:!o.g,onClick:()=>{r.current&&l(Math.max(1,s-.5))}},n.a.createElement("i",{className:"icon-zoom-out"})),n.a.createElement(R.a,{disabled:3===s,size:"tiny",color:"translucent-white",ariaLabel:"Zoom In",className:"zoom-in",ripple:!o.g,onClick:()=>{r.current&&l(Math.min(3,s+.5))}},n.a.createElement("i",{className:"icon-zoom-in"})),n.a.createElement("div",{className:"seekline"},n.a.createElement("div",{className:"seekline-track"},n.a.createElement("div",{className:"seekline-played",style:`width: ${50*(s-1)}%`}),n.a.createElement("input",{ref:r,min:1,max:3,step:"0.5",value:s,type:"range",className:"seekline-input",onChange:e=>{l(Math.min(3,Math.max(Number(e.target.value),1)))},onMouseDown:d,onMouseUp:m}))))});a(258);const se=[1,0,0,1,0,0],le={1:1,1.5:1.5,2:2.2,2.5:3.3,3:5.5};var oe=Object(n.h)(({children:e,className:t,noWrap:a,canPan:c,zoomLevel:r,panDeltaX:s,panDeltaY:l,onPan:o})=>{const i=le[r]||r,[d,m]=Object(n.r)(!1),[h,b]=Object(n.r)({dx:s,dy:l,x:0,y:0}),[g,p]=Object(n.r)(se),v=Object(n.q)(null),E=Object(n.q)(null);Object(n.n)(()=>{const e=i||g[0],t=s||g[4],a=l||g[5],n=[...g];g[0]!==e&&(n[0]=e||n[0],n[3]=e||n[3]),g[4]!==t&&(n[4]=t),g[5]!==a&&(n[5]=a),Object(u.a)(g,n)||p(function(e,t,a){const n=a&&a.querySelector(".active img");if(!a||!n)return t;const c=a.getBoundingClientRect(),r=n.getBoundingClientRect(),s=r.width/e*t[0],l=r.height/e*t[3],o=(c.width-s)/2+t[4],i=(c.height-l)/2+t[5];return c.width&&c.width-150{c||p(se)},[c]),Object(n.n)(()=>{E.current&&(E.current.style.transform=`matrix(${g.toString()})`)},[a,g]);return a?e:n.a.createElement("div",{ref:v,className:"pan-wrapper "+(t||""),onMouseDown:e=>{if(!c)return;e.stopPropagation(),e.preventDefault();const t={dx:g[4],dy:g[5],x:e.pageX,y:e.pageY};b(t),m(!0),v.current&&v.current.classList.add("move")},onMouseUp:()=>{m(!1),v.current&&v.current.classList.remove("move"),o&&o(g[4],g[5])},onMouseMove:e=>{if(d){const t=function(e,t){const a=[...g],n=h.x-e,c=h.y-t;return a[4]=h.dx-n,a[5]=h.dy-c,a}(e.pageX,e.pageY);p(t),E.current&&(E.current.style.transform=`matrix(${g.toString()})`)}}},n.a.createElement("div",{ref:E,className:"pan-container"},e))});a(259);function ie(e,t,a){return e?n.a.createElement("img",{src:e,alt:"",style:t?`width: ${t.width}px`:"",draggable:Boolean(a)}):n.a.createElement("div",{className:"spinner-wrapper",style:t?`width: ${t.width}px`:""},n.a.createElement(L.a,{color:"white"}))}var de=Object(n.h)(Object(c.h)(e=>{const{chatId:t,threadId:a,messageId:n,avatarOwnerId:c,profilePhotoIndex:r,origin:l}=e.mediaViewer,{animationLevel:o}=e.settings.byKey;if(l===s.h.SearchResult){if(!t||!n)return{animationLevel:o};const a=Object(d.k)(e,t,n);return a?{chatId:t,messageId:n,senderId:a.senderId,origin:l,message:a,animationLevel:o}:{animationLevel:o}}if(c){return{messageId:-1,senderId:c,avatarOwner:Object(d.Gb)(e,c)||Object(d.f)(e,c),profilePhotoIndex:r||0,animationLevel:o,origin:l}}if(!(t&&a&&n))return{animationLevel:o};let i,m,u;if(i=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.pb)(e,t,n):Object(d.k)(e,t,n),!i)return{animationLevel:o};if(m=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.qb)(e,t):Object(d.m)(e,t),l===s.h.Inline||l===s.h.Album)u=Object(d.gb)(e,t,a)||Object(d.Y)(e,t,a);else if(l===s.h.SharedMedia){const t=Object(d.v)(e),{foundIds:a}=t&&t.resultsByType&&t.resultsByType.media||{};u=a}return{chatId:t,threadId:a,messageId:n,senderId:i.senderId,origin:l,message:i,chatMessages:m,collectionIds:u,animationLevel:o}},(e,t)=>Object(u.l)(t,["openMediaViewer","closeMediaViewer","openForwardMenu","focusMessage"]))(({chatId:e,threadId:t,messageId:a,senderId:c,origin:d,avatarOwner:u,profilePhotoIndex:y,message:I,chatMessages:S,collectionIds:w,openMediaViewer:P,closeMediaViewer:M,openForwardMenu:L,focusMessage:D,animationLevel:B})=>{const x=Object(n.q)(null),G=Boolean(u||a),q=I?Object(m.R)(I):void 0,z=I?Object(m.G)(I):void 0,$=I?Object(m.P)(I):void 0,_=Boolean(q),K=Boolean(z||q),W=Boolean($),Y=$?$.isGif:void 0,Z=d===s.h.SharedMedia,Q=d===s.h.SearchResult,X=B>=1?"mv-slide":"none",J=2===B?"slide-fade":"none",ee=2===B,te=u?`avatar${u.id}-${y}.jpg`:I&&Object(m.B)(I),ae=Object(f.a)(c),[ce,se]=Object(n.r)(!1),[le,de]=Object(n.r)(!1),[me,ue]=Object(n.r)(1),[he,be]=Object(n.r)({x:0,y:0}),ge=Object(n.p)(()=>_&&a?[a]:Object(m.i)(S||{},w||[],Z),[_,a,S,w,Z]),pe=a?ge.indexOf(a):-1,ve=0===pe||-1===pe,Ee=pe===ge.length-1||-1===pe;function Oe(e){if(u&&void 0!==y){const{photos:t}=u;return t&&t[y]?`photo${t[y].id}?size=c`:Object(m.f)(u,e?"big":"normal")}return I&&Object(m.D)(I,e?"viewerFull":"viewerPreview")}!G||ae&&ae===c&&x.current||(x.current=pe);const fe=Object(v.a)(I&&(Z||Q)&&Object(m.D)(I,"pictogram"),void 0,r.ApiMediaFormat.BlobUrl,void 0,ee&&350),je=Oe(),Ce=Object(v.a)(je,void 0,u&&je&&je.startsWith("profilePhoto")?r.ApiMediaFormat.DataUri:r.ApiMediaFormat.BlobUrl,void 0,ee&&350),{mediaData:ye,downloadProgress:ke}=Object(E.a)(Oe(!0),void 0,I&&Object(m.C)(I,"viewerFull"),void 0,ee&&350),Ne=z||$?(z||$).blobUrl:void 0;let Ie=!W&&(Ne||ye)||Ce||fe;const Se=Object(O.a)(!Ie&&I&&Object(m.E)(I));Ie||d===s.h.SearchResult||(Ie=Se);const we=K?Object(m.S)(_?Object(m.R)(I):Object(m.G)(I)):void 0,Pe=W?Object(m.bb)(Object(m.P)(I)):void 0;Object(n.n)(()=>{o.g&&document.body.classList.toggle("is-media-viewer-open",G)},[G]);const Me=Object(p.a)();Object(n.n)(()=>{const e=window.matchMedia(i.b);return"function"==typeof e.addEventListener?e.addEventListener("change",Me):"function"==typeof e.addListener&&e.addListener(Me),()=>{"function"==typeof e.removeEventListener?e.removeEventListener("change",Me):"function"==typeof e.removeListener&&e.removeListener(Me)}},[Me]);const Fe=Object(f.a)(I),Le=Object(f.a)(d),Ae=Object(f.a)(u),Te=Object(f.a)(Ie);Object(n.n)(()=>{if(ee&&G&&!Fe&&!Ae){Object(j.b)(350+l.c);const e=I?Object(C.a)(I):void 0;k(Boolean(e),d,Ie,I)}ee&&!G&&(Fe||Ae)&&(Object(j.b)(350+l.c),N(Le,Te,Fe||void 0))},[ee,G,d,Le,I,Fe,Ae,Ie,Te]),Object(n.n)(()=>{let e;return le?se(!0):e=window.setTimeout(()=>{se(!1)},350),()=>{e&&window.clearTimeout(e)}},[le]);const Re=()=>{de(!1),ue(1),be({x:0,y:0})},De=Object(n.m)(()=>{de(!le),ue(le?1:1.5),le&&be({x:0,y:0})},[le]),Be=Object(n.m)((e,t=!1)=>{ue(e),1===e&&t&&Re()},[]),xe=Object(n.m)(()=>{M(),Re()},[M]),Ue=Object(n.m)(()=>{xe(),D({chatId:e,threadId:t,messageId:a})},[xe,e,t,D,a]),Ge=Object(n.m)(()=>{L({fromChatId:e,messageIds:[a]}),Re()},[L,e,a]);Object(n.n)(()=>G?Object(b.a)(()=>{le?Re():xe()}):void 0,[xe,G,le]),Object(n.n)(()=>{W&&!Y&&Object(g.b)()},[Y,W]);const qe=Object(n.m)((e,t)=>{let a=ge.indexOf(e);return(-1===t&&a>0||1===t&&a{ve||P({chatId:e,threadId:t,messageId:a?qe(a,-1):void 0,origin:d})},[e,t,qe,ve,a,P,d]),$e=Object(n.m)(()=>{Ee||P({chatId:e,threadId:t,messageId:a?qe(a,1):void 0,origin:d})},[e,t,qe,Ee,a,P,d]);Object(n.n)(()=>{const e=e=>{switch(e.key){case"Left":case"ArrowLeft":ze();break;case"Right":case"ArrowRight":$e()}};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}}),Object(n.n)(()=>{const e=document.querySelector(".slide-container > .active, .slide-container > .to");if(!e)return;const t=Y&&!o.e;return Object(h.b)(e,{excludedClosestSelector:".backdrop, .navigation, .media-viewer-head, .media-viewer-footer"+(t?"":", .VideoPlayer"),onClick:()=>{le||xe()},onSwipe:o.l?(e,t)=>{t===h.a.Right?ze():t===h.a.Left?$e():xe()}:void 0})},[xe,Y,le,$e,ze,ce]);const He=Object(n.m)((e,t)=>{be({x:e,y:t})},[]),_e=Object(F.a)();function Ve(t){if(u)return n.a.createElement("div",{key:e,className:"media-viewer-content"},ie(ye||Ce,Object(i.g)(i.a,!1),!o.g&&!le));if(I){const e=Object(C.a)(I),c=Boolean(e);return n.a.createElement("div",{key:a,className:"media-viewer-content "+(c?"has-footer":"")},K&&ie(Ne||ye||Ce||fe,I&&Object(i.g)(we,c),!o.g&&!le),W&&n.a.createElement(ne,{key:a,url:Ne||ye,isGif:Y,posterData:Ie,posterSize:I&&Object(i.g)(Pe,c,!0),downloadProgress:ke,fileSize:$.size,isMediaViewerOpen:G,noPlay:!t,onClose:xe}),e&&n.a.createElement(V,{text:e,onClick:Ue,isHideable:W}))}}function Ke(){return n.a.createElement(U,{key:u?u.id:a,chatId:u?u.id:e,messageId:a,isAvatar:Boolean(u)})}return n.a.createElement(A.a,{id:"MediaViewer",className:le?"zoomed":"",isOpen:G},()=>n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"media-viewer-head",dir:_e.isRtl?"rtl":void 0},o.g&&n.a.createElement(R.a,{className:"media-viewer-close",round:!0,size:"smaller",color:"translucent-white",ariaLabel:_e("Close"),onClick:xe},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(T.a,{activeKey:x.current,name:J},Ke),n.a.createElement(H,{mediaData:ye||Ce,isVideo:W,isZoomed:le,message:I,fileName:te,onCloseMediaViewer:xe,onForward:Ge,onZoomToggle:De,isAvatar:Boolean(u)})),n.a.createElement(oe,{noWrap:!ce,canPan:le,panDeltaX:he.x,panDeltaY:he.y,zoomLevel:me,onPan:He},n.a.createElement(T.a,{className:"slide-container",activeKey:pe,name:X},Ve)),!ve&&n.a.createElement("button",{type:"button",className:"navigation prev "+(W&&!Y&&"inline"),"aria-label":_e("AccDescrPrevious"),dir:_e.isRtl?"rtl":void 0,onClick:ze}),!Ee&&n.a.createElement("button",{type:"button",className:"navigation next "+(W&&!Y&&"inline"),"aria-label":_e("Next"),dir:_e.isRtl?"rtl":void 0,onClick:$e}),n.a.createElement(re,{isShown:le,onChangeZoom:Be})))})),me=a(52),ue=a(127),he=a(63),be=a(16),ge=a(110),pe=a(45),ve=a(113),Ee=a(106),Oe=a(109),fe=a(123);a(260);var je=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a},currentUserId:n}=e;return{chatsById:t,activeListIds:a.active,archivedListIds:a.archived,currentUserId:n}},(e,t)=>Object(u.l)(t,["setForwardChatId","exitForwardMode","loadMoreChats"]))(({chatsById:e,activeListIds:t,archivedListIds:a,currentUserId:c,isOpen:s,setForwardChatId:l,exitForwardMode:i,loadMoreChats:d})=>{const[u,h]=Object(n.r)(""),b=Object(n.q)(null),g=Object(F.a)();Object(n.n)(()=>{s?o.g||setTimeout(()=>{requestAnimationFrame(()=>{b.current&&b.current.focus()})},500):(b.current&&b.current.blur(),setTimeout(()=>{h("")},300))},[s]);const p=Object(n.p)(()=>{const n=[...t||[],...a||[]];return Object(m.Db)([...n.filter(t=>{const a=e[t];return!a||!!Object(m.e)(a,r.MAIN_THREAD_ID)&&(!u||Object(me.a)(Object(m.l)(g,e[t],void 0,t===c),u))})],e,void 0,c?[c]:void 0)},[t,a,e,c,u,g]),[v,E]=Object(ue.a)(d,p,Boolean(u)),O=Object(n.m)(e=>{h(e.currentTarget.value)},[]),f=Object(n.q)(null),j=Object(he.a)(f,s,e=>{v&&l({id:v[e]})},".ListItem-button",!0),C=n.a.createElement("div",{className:"modal-header",dir:g.isRtl?"rtl":void 0},n.a.createElement(R.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:g("Close"),onClick:i},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(pe.a,{ref:b,value:u,onChange:O,onKeyDown:j,placeholder:g("ForwardTo")}));return n.a.createElement(ge.a,{isOpen:s,onClose:i,className:"ForwardPicker",header:C},v&&v.length?n.a.createElement(ve.a,{className:"picker-list custom-scroll",items:v,onLoadMore:E,noScrollRestore:Boolean(u),ref:f,onKeyDown:j},v.map(e=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable force-rounded-corners",onClick:()=>l({id:e})},Object(m.lb)(e)?n.a.createElement(Oe.a,{status:e===c?g("SavedMessagesInfo"):void 0,userId:e}):n.a.createElement(fe.a,{chatId:e})))):v&&!v.length?n.a.createElement("p",{className:"no-results"},"Sorry, nothing found."):n.a.createElement(be.a,null))})),Ce=a(169);a(261);function ye(e){return e.isSlowMode?"Slowmode enabled":"Something went wrong"}var ke=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["errors"]),(e,t)=>Object(u.l)(t,["dismissError"]))(({errors:e,dismissError:t})=>{const a=Object(F.a)();if(e.length)return n.a.createElement("div",{id:"Errors"},e.map(e=>n.a.createElement(ge.a,{isOpen:!0,onClose:t,className:"error",title:ye(e)},n.a.createElement("p",null,Object(Ce.a)(e)),n.a.createElement(R.a,{isText:!0,onClick:t},a("OK")))))})),Ne=a(180);var Ie=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["notifications"]),(e,t)=>Object(u.l)(t,["dismissNotification"]))(({notifications:e,dismissNotification:t})=>{if(e.length)return n.a.createElement("div",{id:"Notifications"},e.map(({message:e})=>n.a.createElement(Ne.a,{message:Object(B.a)(e,["emoji","br","links"]),onDismiss:t})))})),Se=a(135),we=a(117);var Pe=Object(n.h)(Object(c.h)(void 0,(e,t)=>Object(u.l)(t,["toggleSafeLinkModal"]))(({url:e,toggleSafeLinkModal:t})=>{const a=Object(F.a)(),c=Object(n.m)(()=>{window.open(e),t({url:void 0})},[t,e]),r=Object(n.m)(()=>{t({url:void 0})},[t]),s=Object(Se.a)(e);return n.a.createElement(we.a,{isOpen:Boolean(e),onClose:r,title:a("OpenUrlTitle"),textParts:Object(B.a)(a("OpenUrlAlert2",s),["links"]),confirmLabel:a("OpenUrlTitle"),confirmHandler:c})}));a(262);const Me=["M","T","W","T","F","S","S"];function Fe(e,t,a,n,c){const r=new Date(e,t,a,0,0,0,0),s=n&&new Date(n.getFullYear(),n.getMonth(),n.getDate(),0,0,0,0),l=c&&new Date(c.getFullYear(),c.getMonth(),c.getDate(),0,0,0,0);return!!(l&&r>l)||!!(s&&r{const h=Object(F.a)(),b=new Date,g=Object(n.p)(()=>e?new Date(e):new Date,[e]),p=t?new Date(t):void 0,[v,E]=Object(n.r)(g),[O,f]=Object(n.r)(Le(g.getHours())),[j,C]=Object(n.r)(Le(g.getMinutes())),y=v.getFullYear(),k=v.getMonth(),N=v.getDate();Object(n.n)(()=>{r&&E(g)},[r,g]);const I=c&&y>=b.getFullYear()&&k>=b.getMonth()||p&&y>=p.getFullYear()&&k>=p.getMonth(),S=a&&y<=b.getFullYear()&&k<=b.getMonth(),w=Object(n.p)(()=>function(e,t){const a=[],n=new Date;n.setFullYear(e),n.setMonth(t),n.setDate(1);const c=n.getDay();for(let e=1;e{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return f(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),23)),n=new Date(v.getTime());n.setHours(a),E(n);const c=Le(a);f(c),e.target.value=c},[v]),M=Object(n.m)(e=>{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return C(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),59)),n=new Date(v.getTime());n.setMinutes(a),E(n);const c=Le(a);C(c),e.target.value=c},[v]);return n.a.createElement(ge.a,{isOpen:r,onClose:d,className:"CalendarModal"},n.a.createElement("div",{className:"container"},n.a.createElement("div",{className:"month-selector"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:d},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h4",null,Object(D.f)(h,v,o.g)),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",disabled:S,onClick:S?void 0:function(){E(e=>{const t=new Date(e);return t.setMonth(t.getMonth()-1),t})}},n.a.createElement("i",{className:"icon-previous"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",disabled:I,onClick:I?void 0:function(){E(e=>{const t=new Date(e);return t.setMonth(t.getMonth()+1),t})}},n.a.createElement("i",{className:"icon-next"})))),n.a.createElement("div",{className:"calendar-wrapper"},n.a.createElement("div",{className:"calendar-grid"},Me.map(e=>n.a.createElement("div",{className:"day-button faded weekday"},n.a.createElement("span",null,e))),w.map(e=>n.a.createElement("div",{role:"button",tabIndex:0,onClick:()=>{return t=e,void E(e=>{const a=new Date(e);return a.setDate(t),a});var t},className:Object(ce.a)("day-button",Fe(y,k,e,a?b:void 0,c?b:p)?"disabled":""+(e?"clickable":""),e===N&&"selected")},!!e&&n.a.createElement("span",null,e))))),s&&n.a.createElement("div",{className:"timepicker"},n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:O,onChange:P}),":",n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:j,onChange:M})),n.a.createElement("div",{className:"footer"},n.a.createElement(R.a,{onClick:function(){m(v)}},s?function(e,t){const a=Object(D.c)(e,t,!0);if("Today"===a)return e("Conversation.ScheduleMessage.SendToday",Object(D.h)(t));return e("Conversation.ScheduleMessage.SendOn",a).replace("%@",Object(D.h)(t))}(h,v):l),i&&n.a.createElement(R.a,{onClick:u,isText:!0},i)))});var Te=Object(n.h)(Object(c.h)((e,{message:t,isSchedule:a})=>{const{threadId:n}=Object(d.y)(e)||{},{canDeleteForAll:c}=n&&Object(d.b)(e,t,n)||{},r=Object(d.f)(e,t.chatId);return{canDeleteForAll:!a&&c,contactName:r&&Object(m.lb)(r.id)?Object(m.Y)(Object(d.Gb)(e,Object(m.U)(r))):void 0,willDeleteForCurrentUserOnly:r&&Object(m.ib)(r)&&!c,willDeleteForAll:r&&Object(m.nb)(r)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages"]))(({isOpen:e,isSchedule:t,message:a,album:c,canDeleteForAll:r,contactName:s,willDeleteForCurrentUserOnly:l,willDeleteForAll:o,onClose:i,deleteMessages:d,deleteScheduledMessages:m})=>{const u=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];d({messageIds:e,shouldDeleteForAll:!0}),i()},[d,a.id,i,c]),h=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];t?m({messageIds:e}):d({messageIds:e,shouldDeleteForAll:!1}),i()},[c,a.id,t,i,m,d]),b=Object(F.a)();return n.a.createElement(ge.a,{isOpen:e,onClose:i,onEnter:e&&!r?h:void 0,className:"delete",title:b("DeleteSingleMessagesTitle")},n.a.createElement("p",null,b("AreYouSureDeleteSingleMessage")),l&&n.a.createElement("p",null,b("lng_delete_for_me_chat_hint")),o&&n.a.createElement("p",null,b("lng_delete_for_everyone_hint",1,"i")),r&&n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},s&&b("Conversation.DeleteMessagesFor",Object(B.a)(s)),!s&&b("Conversation.DeleteMessagesForEveryone")),n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},b(r?"ChatList.DeleteForCurrentUser":"Delete")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:i},b("Cancel")))}));var Re=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(m.lb)(t),n=Object(d.P)(e,t),c=Object(d.f)(e,t),r=!!c&&Object(m.jb)(c),s=!!c&&Object(m.ib)(c),l=!!c&&Object(m.nb)(c);return{isPrivateChat:a,isChatWithSelf:n,isChannel:r,isGroup:s,isSuperGroup:l,canPinForAll:a&&!n||l||s,contactName:c&&Object(m.lb)(c.id)?Object(m.Y)(Object(d.Gb)(e,Object(m.U)(c))):void 0}},(e,t)=>Object(u.l)(t,["pinMessage"]))(({isOpen:e,messageId:t,chatId:a,isChannel:c,isGroup:r,isSuperGroup:s,canPinForAll:l,contactName:o,onClose:i,pinMessage:d})=>{const m=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1}),i()},[d,a,t,i]),u=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1,isOneSide:!0,isSilent:!0}),i()},[a,t,i,d]),h=Object(F.a)();return n.a.createElement(ge.a,{isOpen:e,onClose:i,className:"pin",title:h("PinMessageAlertTitle")},n.a.createElement("p",null,h(c?"PinMessageAlertChannel":r||s?"PinMessageAlert":"PinMessageAlertChat")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:u},h("DialogPin")),l&&n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:m},o?h("Conversation.PinMessagesFor",o):h("Conversation.PinMessageAlert.PinAndNotifyMembers")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:i},h("Cancel")))}));var De=Object(n.h)(({isOpen:e,pinnedMessagesCount:t=0,onClose:a,onUnpin:c})=>{const r=Object(F.a)();return n.a.createElement(ge.a,{isOpen:e,onClose:a,className:"unpin-all",title:r("Chat.PanelUnpinAllMessages")},n.a.createElement("p",null,r("Chat.UnpinAllMessagesConfirmation",t,"i")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:c},r("DialogUnpin")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:a},r("Cancel")))}),Be=a(34),xe=a(55);var Ue=Object(n.h)(Object(c.h)((e,{isSchedule:t})=>{const{messageIds:a}=e.selectedMessages||{},{canDeleteForAll:n}=Object(d.e)(e),c=Object(d.r)(e);return{selectedMessageIds:a,canDeleteForAll:!t&&n,contactName:c&&Object(m.lb)(c.id)?Object(m.Y)(Object(d.Gb)(e,Object(m.U)(c))):void 0,willDeleteForCurrentUserOnly:c&&Object(m.ib)(c)&&!n,willDeleteForAll:c&&Object(m.nb)(c)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages","exitMessageSelectMode"]))(({isOpen:e,isSchedule:t,selectedMessageIds:a,canDeleteForAll:c,contactName:r,willDeleteForCurrentUserOnly:s,willDeleteForAll:l,onClose:o,deleteMessages:i,deleteScheduledMessages:d,exitMessageSelectMode:m})=>{const u=Object(n.m)(()=>{i({messageIds:a,shouldDeleteForAll:!0}),m(),o()},[i,m,a,o]),h=Object(n.m)(()=>{t?d({messageIds:a}):i({messageIds:a,shouldDeleteForAll:!1}),m(),o()},[t,m,o,d,a,i]),b=Object(F.a)();if(a)return n.a.createElement(ge.a,{isOpen:e,onClose:o,onEnter:c?void 0:h,className:"delete",title:b("Conversation.DeleteManyMessages")},n.a.createElement("p",null,b("AreYouSureDeleteFewMessages")),s&&n.a.createElement("p",null,"This will delete them just for you, not for other participants in the chat."),l&&n.a.createElement("p",null,"This will delete them for everyone in this chat."),c&&n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},r?b("ChatList.DeleteForEveryone",Object(B.a)(r)):b("Conversation.DeleteMessagesForEveryone")),n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},b(c?"ChatList.DeleteForCurrentUser":"Delete")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:o},b("Cancel")))}));a(263);var Ge=Object(n.h)(Object(c.h)(e=>{const{type:t}=Object(d.y)(e)||{},{canDelete:a}=Object(d.e)(e);return{isSchedule:"scheduled"===t,selectedMessagesCount:Object(d.sb)(e),canDeleteMessages:a}},(e,t)=>Object(u.l)(t,["exitMessageSelectMode","openForwardMenuForSelectedMessages"]))(({canPost:e,isActive:t,messageListType:a,isSchedule:c,selectedMessagesCount:r,canDeleteMessages:s,exitMessageSelectMode:l,openForwardMenuForSelectedMessages:o})=>{const[i,d,m]=Object(Be.a)();Object(n.n)(()=>t&&!i?Object(xe.a)({onBackspace:d,onDelete:d,onEsc:l}):void 0,[t,i,d,l]);const u=Object(f.a)(r||void 0,!0),h=t?r:u,b=Object(F.a)(),g=b("VoiceOver.Chat.MessagesSelected",h),p=Object(ce.a)("MessageSelectToolbar",e&&"with-composer",t&&"shown");return n.a.createElement("div",{className:p},n.a.createElement("div",{className:"MessageSelectToolbar-inner"},n.a.createElement(R.a,{color:"translucent",round:!0,onClick:l,ariaLabel:"Exit select mode"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("span",{className:"MessageSelectToolbar-count",title:g},g),!!r&&n.a.createElement("div",{className:"MessageSelectToolbar-actions"},"scheduled"!==a&&n.a.createElement(z.a,{icon:"forward",ariaLabel:"Forward Messages",onClick:o},n.a.createElement("span",{className:"item-text"},b("Forward"))),n.a.createElement(z.a,{destructive:!0,icon:"delete",onClick:d,disabled:!s,ariaLabel:b("EditAdminGroupDeleteMessages")},n.a.createElement("span",{className:"item-text"},b("Delete"))))),n.a.createElement(Ue,{isOpen:i,isSchedule:c,onClose:m}))})),qe=a(168),ze=a(50),$e=a(170),He=e=>{const t=Object(n.q)(null),a=Object(n.m)(a=>{if("Enter"!==a.key)return;t.current===document.activeElement&&e()},[e]);return Object(n.n)(()=>(window.addEventListener("keydown",a,!1),()=>window.removeEventListener("keydown",a)),[a]),t},_e=a(157);var Ve=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(m.U)(a);return{chat:a,privateChatUser:n?Object(d.Gb)(e,n):void 0,isPinned:Object(d.N)(e,t)}})(({chatId:e,chat:t,privateChatUser:a,isPinned:c,withUsername:r,onClick:s})=>{const[l,o,i]=Object(Be.a)(),d=Object($e.a)({chat:t,privateChatUser:a,isPinned:c,handleDelete:o}),u=()=>{s(e)},h=He(u);if(t)return n.a.createElement(Ee.a,{className:"chat-item-clickable search-result",onClick:u,contextActions:d,buttonRef:h},Object(m.lb)(e)?n.a.createElement(Oe.a,{userId:e,withUsername:r,avatarSize:"large"}):n.a.createElement(fe.a,{chatId:e,withUsername:r,avatarSize:"large"}),n.a.createElement(_e.a,{isOpen:l,onClose:i,chat:t}))})),Ke=a(143);a(264);const We=Object(_.g)(e=>e(),6e4,!0);var Ye=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.topPeers,a=e.users.byId,{recentlyFoundChatIds:n}=e.globalSearch;return{topUserIds:t,usersById:a,recentlyFoundChatIds:n}},(e,t)=>Object(u.l)(t,["loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats"]))(({topUserIds:e,usersById:t,recentlyFoundChatIds:a,onReset:c,loadTopUsers:r,loadContactList:s,openChat:l,addRecentlyFoundChatId:o,clearRecentlyFoundChats:i})=>{const d=Object(n.q)(null);Object(n.n)(()=>{We(()=>{r(),s()})},[r,s]),Object(Ke.a)(d,!e);const u=Object(n.m)(e=>{l({id:e}),c(),setTimeout(()=>{o({id:e})},250)},[l,o,c]),h=Object(F.a)();return n.a.createElement("div",{className:"RecentContacts custom-scroll"},e&&n.a.createElement("div",{className:"top-peers-section",dir:h.isRtl?"rtl":void 0},n.a.createElement("div",{ref:d,className:"top-peers no-selection"},e.map(e=>n.a.createElement("div",{className:"top-peer-item",onClick:()=>u(e),dir:h.isRtl?"rtl":void 0},n.a.createElement(x.a,{user:t[e]}),n.a.createElement("div",{className:"top-peer-name"},Object(B.a)(Object(m.Y)(t[e])||" ")))))),a&&n.a.createElement("div",{className:"search-section pt-1"},n.a.createElement("h3",{className:"section-heading mt-0 recent-chats-header",dir:h.isRtl?"rtl":void 0},h("Recent"),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:"Clear recent chats",onClick:i,isRtl:h.isRtl},n.a.createElement("i",{className:"icon-close"}))),a.map(e=>n.a.createElement(Ve,{chatId:e,onClick:u}))))})),Ze=a(133),Qe=a(27);a(265);var Xe=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);if(!a)return{};const n=Object(m.U)(a);return{chat:a,...n&&{privateChatUser:Object(d.Gb)(e,n)},lastSyncTime:e.lastSyncTime}},(e,t)=>Object(u.l)(t,["focusMessage"]))(({message:e,searchQuery:t,chatId:a,chat:c,privateChatUser:r,focusMessage:s,lastSyncTime:l})=>{const i=Object(m.E)(e),d=Object(v.a)(Object(m.D)(e,"micro")),u=Boolean(Object(m.I)(e)),h=Object(n.m)(()=>{s({chatId:a,messageId:e.id})},[a,s,e.id]),b=Object(F.a)(),g=He(h);if(c)return n.a.createElement(Ee.a,{className:"ChatMessage chat-item-clickable",ripple:!o.g,onClick:h,buttonRef:g},n.a.createElement(x.a,{chat:c,user:r,withOnlineStatus:!0,isSavedMessages:r&&r.isSelf,lastSyncTime:l}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"info-row"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",{dir:"auto"},Object(B.a)(Object(m.l)(b,c,r))),c.isVerified&&n.a.createElement(Ze.a,null)),n.a.createElement("div",{className:"message-date"},n.a.createElement(Qe.a,{className:"date"},Object(D.g)(b,1e3*e.date)))),n.a.createElement("div",{className:"subtitle"},n.a.createElement("div",{className:"message",dir:"auto"},function(e,t,a,c,r){if(!a)return Object(B.a)(Object(m.N)(e,t));return n.a.createElement("span",{className:"media-preview"},n.a.createElement("img",{src:a,alt:"",className:r?"round":void 0}),Object(m.P)(t)&&n.a.createElement("i",{className:"icon-play"}),Object(B.a)(Object(m.N)(e,t,!0),["emoji","highlight"],{highlight:c}))}(b,e,d||i,t,u)))))}));a(266);var Je=Object(n.h)(({searchDate:e,onSelect:t})=>{const a=Object(n.p)(()=>function(e){if(e.match(/^\d{2,4}-\d{2}-\d{2}$/g)){const t=new Date(e);return[{date:t,text:Object(D.a)(t)}]}const t=[],a=new Date,n=a.getFullYear(),c=a.getTime()>new Date(`${n}-${e}`).getTime()?n:n-1;for(let a=0;a<8;a++){const n=new Date(`${c-a}-${e}`);t.push({date:n,text:Object(D.a)(n)})}return t}(e),[e]);return n.a.createElement("section",{className:"DateSuggest custom-scroll custom-scroll-x"},a.map(({date:e,text:a})=>n.a.createElement("div",{onClick:()=>t(e),className:"date-item",key:a},n.a.createElement("i",{className:"icon-calendar"}),n.a.createElement("span",null,a))))}),et=a(118),tt=a(141);const at=Object(_.g)(e=>e(),500,!0);var nt=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{byId:a}=e.users,{userIds:n}=e.contactList||{};if(!n)return{chatsById:t,usersById:a};const{currentUserId:c,messages:r,lastSyncTime:s}=e,{fetchingStatus:l,globalResults:o,localResults:i,resultsByType:d}=e.globalSearch,{chatIds:m,userIds:u}=o||{},{chatIds:h,userIds:b}=i||{},{byChatId:g}=r,{foundIds:p}=d&&d.text||{};return{currentUserId:c,localContactIds:n,localChatIds:h,localUserIds:b,globalChatIds:m,globalUserIds:u,foundIds:p,globalMessagesByChatId:g,chatsById:t,usersById:a,fetchingStatus:l,lastSyncTime:s}},(e,t)=>Object(u.l)(t,["openChat","addRecentlyFoundChatId","searchMessagesGlobal","setGlobalSearchChatId"]))(({searchQuery:e,searchDate:t,dateSearchQuery:a,currentUserId:c,localContactIds:r,localChatIds:l,localUserIds:i,globalChatIds:d,globalUserIds:h,foundIds:b,globalMessagesByChatId:g,chatsById:p,usersById:v,fetchingStatus:E,lastSyncTime:O,onReset:f,onSearchDateSelect:j,openChat:C,addRecentlyFoundChatId:y,searchMessagesGlobal:k,setGlobalSearchChatId:N})=>{const I=Object(F.a)(),[S,w]=Object(n.r)(!1),[P,M]=Object(n.r)(!1),L=Object(n.m)(({direction:t})=>{O&&t===s.e.Backwards&&at(()=>{k({type:"text",query:e})})},[O,k,e]),A=Object(n.m)(e=>{C({id:e}),e!==c&&y({id:e}),o.g||f()},[c,C,y,f]),T=Object(n.m)(e=>{N({id:e})},[N]),R=Object(n.p)(()=>{if(!e||e.startsWith("@")&&e.length<2)return ze.a;const t=r?r.filter(t=>{const a=v[t];if(!a)return!1;const n=Object(m.Z)(a);return n&&Object(me.a)(n,e)||Object(me.a)(a.username,e)}):[];return[...c&&Object(me.a)(I("SavedMessages"),e)?[c]:[],...Object(m.Db)(Object(u.o)([...t,...l||[],...i||[]]),p)]},[e,r,c,I,l,i,p,v]),D=Object(n.p)(()=>!e||e.length<4||!d||!h?ze.a:Object(m.Db)(Object(u.o)([...d,...h]),p,!0),[p,d,h,e]),B=Object(n.p)(()=>(e||t)&&b&&0!==b.length?b.map(e=>{const[t,a]=e.split("_").map(Number);return g&&g[t]&&g[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):ze.a,[b,g,e,t]),x=Object(n.m)(()=>{w(!S)},[S]),U=Object(n.m)(()=>{M(!P)},[P]);const G=E&&!E.chats&&!E.messages&&!R.length&&!D.length&&!B.length;return e||t?n.a.createElement(ve.a,{className:"LeftSearch custom-scroll",items:B,onLoadMore:L,noScrollRestoreOnTop:!0,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(Je,{searchDate:a,onSelect:j})),G&&n.a.createElement(et.a,{text:I("ChatList.Search.NoResults"),description:I("ChatList.Search.NoResultsDescription")}),!!R.length&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar",dir:I.isRtl?"rtl":void 0},R.map(e=>n.a.createElement(tt.a,{chatOrUserId:e,onClick:T,clickArg:e}))),!!R.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading",dir:I.isRtl?"auto":void 0},R.length>3&&n.a.createElement(Qe.a,{onClick:x},I(S?"ChatList.Search.ShowLess":"ChatList.Search.ShowMore")),I("DialogList.SearchSectionDialogs")),R.map((e,t)=>{if(S||!(t>=3))return n.a.createElement(Ve,{chatId:e,onClick:A})})),!!D.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading",dir:I.isRtl?"auto":void 0},D.length>3&&n.a.createElement(Qe.a,{onClick:U},I(P?"ChatList.Search.ShowLess":"ChatList.Search.ShowMore")),I("DialogList.SearchSectionGlobal")),D.map((e,t)=>{if(P||!(t>=3))return n.a.createElement(Ve,{chatId:e,withUsername:!0,onClick:A})})),!!B.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading",dir:I.isRtl?"auto":void 0},I("SearchMessages")),B.map((function(t){const a=Object(m.N)(I,t),c=p[t.chatId];if(a&&c)return n.a.createElement(Xe,{chatId:t.chatId,message:t,searchQuery:e})})))):n.a.createElement(Ye,{onReset:f})}));const ct=Object(_.g)(e=>e(),500,!0);var rt=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{currentUserId:a,messages:{byChatId:n},lastSyncTime:c}=e,{fetchingStatus:r,resultsByType:s}=e.globalSearch,{foundIds:l}=s&&s.text||{};return{currentUserId:a,foundIds:l,globalMessagesByChatId:n,chatsById:t,fetchingStatus:r,lastSyncTime:c}},(e,t)=>Object(u.l)(t,["searchMessagesGlobal"]))(({searchQuery:e,currentUserId:t,dateSearchQuery:a,foundIds:c,globalMessagesByChatId:r,chatsById:l,fetchingStatus:o,lastSyncTime:i,searchMessagesGlobal:d,onSearchDateSelect:u})=>{const h=Object(F.a)(),b=Object(n.m)(({direction:a})=>{i&&a===s.e.Backwards&&ct(()=>{d({type:"text",query:e,chatId:t})})},[t,i,d,e]),g=Object(n.p)(()=>c&&0!==c.length?c.map(e=>{const[t,a]=e.split("_").map(Number);return r&&r[t]&&r[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):ze.a,[c,r]);const p=o&&!o.chats&&!o.messages&&!g.length;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content custom-scroll chat-list",items:g,onLoadMore:b,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(Je,{searchDate:a,onSelect:u})),p&&n.a.createElement(et.a,{text:h("ChatList.Search.NoResults"),description:h("ChatList.Search.NoResultsDescription")}),!!g.length&&g.map((function(t){const a=Object(m.N)(h,t),c=l[t.chatId];if(a&&c)return n.a.createElement(Xe,{chatId:t.chatId,message:t,searchQuery:e})}))))}));function st(e){return(t,a)=>{const{byId:n}=t.chats,{byId:c}=t.users,{fetchingStatus:r,resultsByType:s,chatId:l}=t.globalSearch,o="audio"!==e?e:a&&a.isVoice?"voice":"audio",{byChatId:i}=t.messages,{foundIds:d}=s&&s[o]||{};return{isLoading:void 0===d||!!r&&Boolean(r.chats||r.messages),chatsById:n,usersById:c,globalMessagesByChatId:i,foundIds:d,searchChatId:l,lastSyncTime:t.lastSyncTime}}}var lt=a(119),ot=a(165);const it=Object(_.g)(e=>e(),500,!0);var dt=Object(n.h)(Object(c.h)(st("media"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","openMediaViewer"]))(({searchQuery:e,searchChatId:t,isLoading:a,globalMessagesByChatId:c,foundIds:r,lastSyncTime:o,searchMessagesGlobal:i,openMediaViewer:d})=>{const m=Object(F.a)(),u=Object(n.m)(({direction:a})=>{o&&a===s.e.Backwards&&it(()=>{i({type:"media",query:e,chatId:t})})},[o,i,e,t]),h=Object(n.p)(()=>r&&c?r.map(e=>{const[t,a]=e.split("_").map(Number);return c[t]&&c[t].byId[a]}).filter(Boolean):ze.a,[c,r]),b=Object(n.m)((e,t)=>{d({chatId:t,messageId:e,origin:s.h.SearchResult})},[d]);const g=Object(lt.a)([e],l.pb)&&!a,p=g&&r&&r.length>0&&!e,v=g&&r&&r.length>0&&e,E=Object(ce.a)("search-content custom-scroll",v&&"chat-list");return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:E,items:h,itemSelector:e?".ListItem":".Media",onLoadMore:u,noFastList:!0},!g&&n.a.createElement(be.a,null),g&&(!r||0===r.length)&&n.a.createElement(et.a,{text:m("ChatList.Search.NoResults"),description:m("ChatList.Search.NoResultsDescription")}),p&&n.a.createElement("div",{className:"media-list",dir:m.isRtl?"rtl":void 0},h.map(e=>n.a.createElement(ot.a,{key:e.id,idPrefix:"search-media",message:e,onClick:b}))),v&&h.map(e=>n.a.createElement(Xe,{key:e.id,chatId:e.chatId,message:e}))))}));function mt(e,t,a,n){const{senderId:c}=t;if(!c)return;const r=Object(m.lb)(c)?n[c]:a[c];let s=Object(m.V)(e,r);const l=a[t.chatId];return l&&(Object(m.lb)(c)&&r.isSelf?s=`${e("FromYou")} → ${Object(m.l)(e,l)}`:Object(m.kb)(l)&&(s+=" → "+Object(m.l)(e,l))),s}var ut=a(185);const ht=Object(_.g)(e=>e(),500,!0);var bt=Object(n.h)(Object(c.h)(st("links"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:m,focusMessage:u})=>{const h=Object(F.a)(),b=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&ht(()=>{m({type:"links",query:e,chatId:t})})},[d,m,e,t]),g=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number);return o[t]&&o[t].byId[a]}).filter(Boolean):ze.a,[o,i]),p=Object(n.m)((e,t)=>{u({chatId:t,messageId:e})},[u]);const v=Object(lt.a)([e],l.pb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content documents-list custom-scroll",items:g,onLoadMore:b,noFastList:!0},!v&&n.a.createElement(be.a,null),v&&(!i||0===i.length)&&n.a.createElement(et.a,{text:h("ChatList.Search.NoResults"),description:h("ChatList.Search.NoResultsDescription")}),v&&i&&i.length>0&&g.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(g[t-1].date);return n.a.createElement("div",{className:"ListItem",dir:h.isRtl?"rtl":void 0,key:e.id},a&&n.a.createElement("p",{className:"section-heading",dir:h.isRtl?"rtl":void 0},Object(D.f)(h,new Date(1e3*e.date))),n.a.createElement(ut.a,{key:e.id,message:e,senderTitle:mt(h,e,c,r),onMessageClick:p}))})))})),gt=a(160);const pt=Object(_.g)(e=>e(),500,!0);var vt=Object(n.h)(Object(c.h)(st("documents"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:u,focusMessage:h})=>{const b=Object(F.a)(),g=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&pt(()=>{u({type:"documents",query:e,chatId:t})})},[d,u,e,t]),p=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number),n=o[t]&&o[t].byId[a];return n&&Object(m.y)(n)?n:void 0}).filter(Boolean):ze.a,[o,i]),v=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]);const E=Object(lt.a)([e],l.pb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content documents-list custom-scroll",items:p,onLoadMore:g,noFastList:!0},!E&&n.a.createElement(be.a,null),E&&(!i||0===i.length)&&n.a.createElement(et.a,{text:b("ChatList.Search.NoResults"),description:b("ChatList.Search.NoResultsDescription")}),E&&i&&i.length>0&&p.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(p[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(b,new Date(1e3*e.date))),n.a.createElement(gt.a,{message:e,withDate:!0,datetime:e.date,smaller:!0,sender:mt(b,e,c,r),className:"scroll-item",onDateClick:v}))})))})),Et=a(167);const Ot=Object(_.g)(e=>e(),500,!0);var ft=Object(n.h)(Object(c.h)(st("audio"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage","openAudioPlayer"]))(({isVoice:e,searchQuery:t,searchChatId:a,isLoading:c,chatsById:r,usersById:o,globalMessagesByChatId:i,foundIds:d,lastSyncTime:m,searchMessagesGlobal:u,focusMessage:h,openAudioPlayer:b})=>{const g=Object(F.a)(),p=e?"voice":"audio",v=Object(n.m)(({direction:e})=>{m&&e===s.e.Backwards&&Ot(()=>{u({type:p,query:t,chatId:a})})},[p,m,u,t,a]),E=Object(n.p)(()=>d&&i?d.map(e=>{const[t,a]=e.split("_").map(Number);return i[t]&&i[t].byId[a]}).filter(Boolean):ze.a,[i,d]),O=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]),f=Object(n.m)((e,t)=>{b({chatId:t,messageId:e})},[b]);const j=Object(lt.a)([t],l.pb)&&!c;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content documents-list custom-scroll",items:E,onLoadMore:v,noFastList:!0},!j&&n.a.createElement(be.a,null),j&&(!d||0===d.length)&&n.a.createElement(et.a,{text:g("ChatList.Search.NoResults"),description:g("ChatList.Search.NoResultsDescription")}),j&&d&&d.length>0&&E.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(E[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading",dir:g.isRtl?"rtl":void 0},Object(D.f)(g,new Date(1e3*e.date))),n.a.createElement(Et.a,{key:e.id,message:e,renderingFor:"searchResult",senderTitle:mt(g,e,r,o),date:e.date,lastSyncTime:m,className:"scroll-item",onPlay:f,onDateClick:O}))})))}));a(267);const jt=[{type:s.c.ChatList,title:"SearchAllChatsShort"},{type:s.c.Media,title:"SharedMediaTab2"},{type:s.c.Links,title:"SharedLinksTab2"},{type:s.c.Files,title:"SharedFilesTab2"},{type:s.c.Music,title:"SharedMusicTab2"},{type:s.c.Voice,title:"SharedVoiceTab2"}],Ct=[{type:s.c.ChatList,title:"All Messages"},...jt.slice(1)],yt=Object.keys(s.c).length/2;var kt=Object(n.h)(Object(c.h)(e=>{const{currentContent:t,chatId:a}=e.globalSearch;return{currentContent:t,chatId:a}},(e,t)=>Object(u.l)(t,["setGlobalSearchContent","setGlobalSearchDate"]))(({searchQuery:e,searchDate:t,isActive:a,currentContent:c=s.c.ChatList,chatId:r,setGlobalSearchContent:l,setGlobalSearchDate:o,onReset:i})=>{const d=Object(F.a)(),[m,u]=Object(n.r)(0),h=Object(n.p)(()=>Object(D.l)(e),[e]),b=Object(n.m)(e=>{const t=jt[e];l({content:t.type}),u(e)},[l]),g=Object(n.m)(e=>{o({date:e.getTime()/1e3})},[o]),p=Object(n.q)(null),v=Object(he.a)(p,a,void 0,".ListItem-button",!0);return n.a.createElement("div",{className:"LeftSearch",ref:p,onKeyDown:v},n.a.createElement(qe.a,{activeTab:m,tabs:r?Ct:jt,onSwitchTab:b}),n.a.createElement(T.a,{name:d.isRtl?"slide-reversed":"slide",renderCount:yt,activeKey:c},()=>{switch(c){case s.c.ChatList:return r?n.a.createElement(rt,{searchQuery:e,dateSearchQuery:h,onReset:i,onSearchDateSelect:g}):n.a.createElement(nt,{searchQuery:e,searchDate:t,dateSearchQuery:h,onReset:i,onSearchDateSelect:g});case s.c.Media:return n.a.createElement(dt,{searchQuery:e});case s.c.Links:return n.a.createElement(bt,{searchQuery:e});case s.c.Files:return n.a.createElement(vt,{searchQuery:e});case s.c.Music:return n.a.createElement(ft,{key:"audio",searchQuery:e});case s.c.Voice:return n.a.createElement(ft,{key:"voice",isVoice:!0,searchQuery:e});default:return}}))}));function Nt(e,t){const a=Object(n.q)(e),[c,r]=Object(n.r)(t);return[c,Object(n.m)(e=>{r(t=>a.current(t,e))},[])]}const It=[{icon:"user",title:"FilterContacts",key:"contacts"},{icon:"non-contacts",title:"FilterNonContacts",key:"nonContacts"},{icon:"group",title:"FilterGroups",key:"groups"},{icon:"channel",title:"FilterChannels",key:"channels"},{icon:"bots",title:"FilterBots",key:"bots"}],St=[{icon:"mute",title:"FilterMuted",key:"excludeMuted"},{icon:"archive",title:"FilterArchived",key:"excludeArchived"},{icon:"readchats",title:"FilterRead",key:"excludeRead"}],wt=["includedChatIds","bots","channels","groups","contacts","nonContacts"],Pt=["excludedChatIds","excludeArchived","excludeMuted","excludeRead"];function Mt(e,t,a){let n=[],c=[];if("included"===t){const{includedChatIds:t,...r}=a?e.includeFilters||{}:Object(u.l)(e.folder,wt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}else{const{excludedChatIds:t,...r}=a?e.excludeFilters||{}:Object(u.l)(e.folder,Pt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}return{selectedChatIds:n,selectedChatTypes:c}}function Ft(e){if(e){const{includedChatIds:t,...a}=e;if(Object.values(a).filter(Boolean).length>1||t&&t.length)return"";if(a.bots)return"Bots";if(a.groups)return"Groups";if(a.channels)return"Channels";if(a.contacts)return"Contacts";if(a.nonContacts)return"Non-Contacts"}return""}const Lt={mode:"create",chatFilter:"",folder:{title:"",includedChatIds:[],excludedChatIds:[]}},At=(e,t)=>{switch(t.type){case"setTitle":return{...e,folder:{...e.folder,title:t.payload},isTouched:!0};case"editIncludeFilters":return{...e,includeFilters:Object(u.l)(e.folder,wt)};case"editExcludeFilters":return{...e,excludeFilters:Object(u.l)(e.folder,Pt)};case"setIncludeFilters":return{...e,includeFilters:t.payload,chatFilter:""};case"setExcludeFilters":return{...e,excludeFilters:t.payload,chatFilter:""};case"saveFilters":return e.includeFilters?{...e,folder:{...Object(u.j)(e.folder,wt),title:e.folder.title?e.folder.title:Ft(e.includeFilters),...e.includeFilters},includeFilters:void 0,chatFilter:"",isTouched:!0}:e.excludeFilters?{...e,folder:{...Object(u.j)(e.folder,Pt),...e.excludeFilters},excludeFilters:void 0,chatFilter:"",isTouched:!0}:e;case"editFolder":{const{id:e,description:a,...n}=t.payload;return{mode:"edit",folderId:e,folder:n,chatFilter:""}}case"setChatFilter":return{...e,chatFilter:t.payload};case"setIsLoading":return{...e,isLoading:t.payload};case"setError":return{...e,error:t.payload};case"reset":return Lt;default:return e}};const Tt={currentPassword:"",password:"",hint:"",email:""},Rt=(e,t)=>{switch(t.type){case"setCurrentPassword":return{...e,currentPassword:t.payload};case"setPassword":return{...e,password:t.payload};case"setHint":return{...e,hint:t.payload};case"setEmail":return{...e,email:t.payload};case"reset":return Tt;default:return e}};var Dt=Object(n.h)(Object(c.h)(void 0,(e,t)=>Object(u.l)(t,["signOut","deleteChatFolder"]))(({currentScreen:e,editedFolderId:t,onReset:a,onSaveFilter:c,signOut:r,deleteChatFolder:l})=>{const[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(n.m)(()=>{d(!0)},[]),b=Object(n.m)(()=>{d(!1)},[]),g=Object(n.m)(()=>{u(!0)},[]),p=Object(n.m)(()=>{u(!1)},[]),v=Object(n.m)(()=>{b(),r()},[b,r]),E=Object(n.m)(()=>{p(),l({id:t}),a()},[t,p,l,a]),O=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(R.a,{round:!0,ripple:!o.g,size:"smaller",color:"translucent",className:t?"active":"",onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]),f=Object(F.a)();return n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:a,ariaLabel:f("AccDescrGoBack")},n.a.createElement("i",{className:"icon-arrow-left"})),function(){switch(e){case s.m.EditProfile:return n.a.createElement("h3",null,f("lng_settings_information"));case s.m.General:return n.a.createElement("h3",null,f("General"));case s.m.Notifications:return n.a.createElement("h3",null,f("Notifications"));case s.m.Privacy:return n.a.createElement("h3",null,f("PrivacySettings"));case s.m.Language:return n.a.createElement("h3",null,f("Language"));case s.m.GeneralChatBackground:return n.a.createElement("h3",null,f("ChatBackground"));case s.m.GeneralChatBackgroundColor:return n.a.createElement("h3",null,f("SetColor"));case s.m.PrivacyPhoneNumber:return n.a.createElement("h3",null,f("PrivacyPhone"));case s.m.PrivacyLastSeen:return n.a.createElement("h3",null,f("PrivacyLastSeen"));case s.m.PrivacyProfilePhoto:return n.a.createElement("h3",null,f("Privacy.ProfilePhoto"));case s.m.PrivacyForwarding:return n.a.createElement("h3",null,f("PrivacyForwards"));case s.m.PrivacyGroupChats:return n.a.createElement("h3",null,f("AutodownloadGroupChats"));case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement("h3",null,f("AlwaysShareWith"));case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement("h3",null,f("NeverShareWith"));case s.m.PrivacyActiveSessions:return n.a.createElement("h3",null,f("SessionsTitle"));case s.m.PrivacyBlockedUsers:return n.a.createElement("h3",null,f("BlockedUsers"));case s.m.TwoFaDisabled:case s.m.TwoFaEnabled:return n.a.createElement("h3",null,f("TwoStepVerification"));case s.m.TwoFaNewPassword:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:return n.a.createElement("h3",null,f("EnterPassword"));case s.m.TwoFaNewPasswordConfirm:return n.a.createElement("h3",null,f("PleaseReEnterPassword"));case s.m.TwoFaNewPasswordHint:case s.m.TwoFaChangePasswordHint:return n.a.createElement("h3",null,f("PasswordHint"));case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaRecoveryEmail:return n.a.createElement("h3",null,f("RecoveryEmailTitle"));case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement("h3",null,"Recovery Email Code");case s.m.TwoFaCongratulations:return n.a.createElement("h3",null,f("TwoStepVerificationPasswordSet"));case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement("h3",null,f("PleaseEnterCurrentPassword"));case s.m.Folders:return n.a.createElement("h3",null,f("Filters"));case s.m.FoldersCreateFolder:return n.a.createElement("h3",null,f("FilterNew"));case s.m.FoldersEditFolder:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,f("FilterEdit")),t&&n.a.createElement(q.a,{className:"settings-more-menu",trigger:O,positionX:"right"},n.a.createElement(z.a,{icon:"delete",destructive:!0,onClick:g},"Delete Folder")));case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement("div",{className:"settings-main-header"},e===s.m.FoldersIncludedChats?n.a.createElement("h3",null,f("FilterInclude")):n.a.createElement("h3",null,f("FilterExclude")),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",className:"color-primary",onClick:c,ariaLabel:f("AutoDeleteConfirm")},n.a.createElement("i",{className:"icon-check"})));default:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,f("SETTINGS")),n.a.createElement(q.a,{className:"settings-more-menu",trigger:O,positionX:"right"},n.a.createElement(z.a,{icon:"logout",onClick:h},f("LogOutTitle"))))}}(),n.a.createElement(we.a,{isOpen:i,onClose:b,text:"Are you sure you want to log out?",confirmLabel:"Log Out",confirmHandler:v,confirmIsDestructive:!0}),n.a.createElement(we.a,{isOpen:m,onClose:p,text:"Are you sure you want to delete this folder?",confirmLabel:"Delete",confirmHandler:E,confirmIsDestructive:!0}))})),Bt=a(18);var xt=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e;return{currentUser:t?Object(d.Gb)(e,t):void 0}})(({onScreenSelect:e,currentUser:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-main-menu"},t&&n.a.createElement("div",{className:"settings-current-user"},n.a.createElement(x.a,{user:t,size:"jumbo"}),n.a.createElement("p",{className:"name"},Object(m.Z)(t)),n.a.createElement("p",{className:"phone"},Object(Bt.c)(t.phoneNumber))),n.a.createElement(Ee.a,{icon:"edit",onClick:()=>e(s.m.EditProfile)},a("lng_settings_information")),n.a.createElement(Ee.a,{icon:"folder",onClick:()=>e(s.m.Folders)},a("Filters")),n.a.createElement(Ee.a,{icon:"settings",onClick:()=>e(s.m.General)},a("Telegram.GeneralSettingsViewController")),n.a.createElement(Ee.a,{icon:"unmute",onClick:()=>e(s.m.Notifications)},a("Notifications")),n.a.createElement(Ee.a,{icon:"lock",onClick:()=>e(s.m.Privacy)},a("PrivacySettings")),n.a.createElement(Ee.a,{icon:"language",onClick:()=>e(s.m.Language)},a("Language"))))})),Ut=a(130);a(268);var Gt=({isShown:e,className:t,color:a="primary",ariaLabel:c,disabled:r,onClick:s,children:l})=>{const o=Object(ce.a)("FloatingActionButton",e&&"revealed",t);return n.a.createElement(R.a,{className:o,color:a,round:!0,disabled:r,onClick:e&&!r?s:void 0,ariaLabel:c,tabIndex:-1},l)};const qt=/https:\/\/t\.me\/?/i,zt=/^([a-zA-Z0-9_]+)$/,$t=Object(_.a)(e=>e(),250,!1);var Ht=Object(n.h)(({currentUsername:e,asLink:t,isLoading:a,isUsernameAvailable:c,checkUsername:r,onChange:s})=>{const[l,o]=Object(n.r)(e||""),i=Object(F.a)(),d=t?"SetUrl":"Username",m=i(t?"SetUrlPlaceholder":"Username"),[u,h]=Object(n.p)(()=>l.length?l.length<5?[void 0,m+" is too short"]:l.length>32?[void 0,m+" is too long"]:zt.test(l)?void 0===c?[]:[c?i(d+"Available","Username"):void 0,!1===c?i(d+"InUse"):void 0]:[void 0,m+" contains invalid characters"]:[],[l,c,i,d,m]);Object(n.n)(()=>{o(e||"")},[t,e]);const b=Object(n.m)(e=>{const a=e.target.value.trim().replace(qt,"");o(a),e.target.value=`${t?"https://t.me/":""}${a}`;const n=function(e){return e.length>=5&&e.length<=32&&zt.test(e)}(a);n&&$t(()=>{r({username:a})}),s&&s(!!n&&a)},[t,r,s]);return n.a.createElement(pe.a,{value:`${t?"https://t.me/":""}${l}`,onChange:b,label:m,error:h,success:u,readOnly:a})});const _t=Object(_.g)(e=>e(),6e4,!0);var Vt=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e,{progress:a,isUsernameAvailable:n}=e.profileEdit||{},c=t?Object(d.Gb)(e,t):void 0;if(!c)return{progress:a,isUsernameAvailable:n};const{firstName:r,lastName:s,username:l,fullInfo:o}=c,{bio:i}=o||{};return{currentAvatarHash:Object(m.f)(c),currentFirstName:r,currentLastName:s,currentBio:i,currentUsername:l,progress:a,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["loadCurrentUser","updateProfile","checkUsername"]))(({currentAvatarHash:e,currentFirstName:t,currentLastName:a,currentBio:c,currentUsername:l,progress:o,isUsernameAvailable:i,loadCurrentUser:d,updateProfile:m,checkUsername:u})=>{const[h,b]=Object(n.r)(!1),[g,p]=Object(n.r)(!1),[E,O]=Object(n.r)(),[f,j]=Object(n.r)(),[C,y]=Object(n.r)(t||""),[k,N]=Object(n.r)(a||""),[I,S]=Object(n.r)(c||""),[w,P]=Object(n.r)(l||""),M=Object(v.a)(e,!1,r.ApiMediaFormat.BlobUrl),A=o===s.j.InProgress,T=!1===w,R=Object(n.p)(()=>!T&&(Boolean(f)||g||!0===i),[f,g,T,i]);Object(n.n)(()=>{_t(()=>{d()})},[d]),Object(n.n)(()=>{j(void 0)},[M]),Object(n.n)(()=>{y(t||""),N(a||""),S(c||"")},[t,a,c]),Object(n.n)(()=>{P(l||"")},[l]),Object(n.n)(()=>{o===s.j.Complete&&(p(!1),b(!1),O(void 0))},[o]);const D=Object(n.m)(e=>{j(e)},[]),x=Object(n.m)(e=>{y(e.target.value),p(!0)},[]),U=Object(n.m)(e=>{N(e.target.value),p(!0)},[]),G=Object(n.m)(e=>{S(e.target.value),p(!0)},[]),q=Object(n.m)(e=>{P(e),b(!0)},[]),z=Object(n.m)(()=>{const e=C.trim(),t=k.trim(),a=I.trim();e.length?a.length>70?O("Bio can' be longer than 70 characters"):m({photo:f,...g&&{firstName:e,lastName:t,bio:a},...h&&{username:w}}):O("Please provide your first name")},[f,C,k,I,g,w,h,m]),$=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-edit-profile"},n.a.createElement(Ut.a,{currentAvatarBlobUrl:M,onChange:D,title:"Edit your profile photo",disabled:A}),n.a.createElement(pe.a,{value:C,onChange:x,label:$("FirstName"),disabled:A,error:"Please provide your first name"===E?E:void 0}),n.a.createElement(pe.a,{value:k,onChange:U,label:$("LastName"),disabled:A}),n.a.createElement(pe.a,{value:I,onChange:G,label:$("UserBio"),disabled:A,error:"Bio can' be longer than 70 characters"===E?E:void 0}),n.a.createElement("p",{className:"settings-item-description",dir:$.isRtl?"rtl":void 0},Object(B.a)($("lng_settings_about_bio"),["br","simple_markdown"]))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:$.isRtl?"rtl":void 0},$("Username")),n.a.createElement(Ht,{currentUsername:w||"",isLoading:A,isUsernameAvailable:i,checkUsername:u,onChange:q}),n.a.createElement("p",{className:"settings-item-description",dir:$.isRtl?"rtl":void 0},Object(B.a)($("UsernameHelp"),["br","simple_markdown"])),w&&n.a.createElement("p",{className:"settings-item-description",dir:$.isRtl?"rtl":void 0},$("lng_username_link"),n.a.createElement("br",null),n.a.createElement("span",{className:"username-link"},"https://t.me/",w)))),n.a.createElement(Gt,{isShown:R,onClick:z,disabled:A,ariaLabel:"Save changes"},A?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),Kt=a(125),Wt=a(116);const Yt=Object(_.g)(e=>e(),6e4,!0);var Zt=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a}}=e,{orderedIds:n,byId:c,recommended:r}=e.chatFolders;return{chatsById:t,usersById:a,orderedFolderIds:n,foldersById:c,recommendedChatFolders:r,notifySettings:Object(d.eb)(e),notifyExceptions:Object(d.db)(e)}},(e,t)=>Object(u.l)(t,["loadRecommendedChatFolders","addChatFolder","showError"]))(({onCreateFolder:e,onEditFolder:t,chatsById:a,usersById:c,orderedFolderIds:r,foldersById:s,recommendedChatFolders:o,notifySettings:i,notifyExceptions:d,loadRecommendedChatFolders:u,addChatFolder:h,showError:b})=>{const[g,p]=Object(n.r)(),[v,E]=Object(n.r)(!1),O=Object(n.m)(()=>E(!0),[]);Object(n.n)(()=>{g||Object(Kt.a)("FoldersAll").then(p)},[g]),Object(n.n)(()=>{Yt(()=>{u()})},[u]);const f=Object(n.m)(()=>{Object.keys(s).length>=10?b({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):e()},[s,b,e]),j=Object(F.a)(),C=Object(n.p)(()=>{if(!r)return;const e=Object.keys(a).map(Number);return r.map(t=>{const n=s[t];return{id:n.id,title:n.title,subtitle:Object(m.o)(j,a,c,n,e,i,d)}})},[r,a,s,c,i,d,j]),y=Object(n.m)(e=>{Object.keys(s).length>=10?b({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):h({folder:e})},[s,h,b]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},g&&n.a.createElement(Wt.a,{id:"settingsFoldersMain",size:l.tb,animationData:g,play:v,noLoop:!0,onLoad:O})),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},j("CreateNewFilterInfo")),n.a.createElement(R.a,{className:"with-icon mb-2",color:"primary",size:"smaller",pill:!0,fluid:!0,onClick:f,isRtl:j.isRtl},n.a.createElement("i",{className:"icon-add"}),j("CreateNewFilter"))),n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3",dir:j.isRtl?"rtl":void 0},j("Filters")),C&&C.length?C.map(e=>n.a.createElement(Ee.a,{className:"mb-2",narrow:!0,multiline:!0,onClick:()=>t(s[e.id])},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.subtitle))):C&&!C.length?n.a.createElement("p",{className:"settings-item-description my-4",dir:"auto"},"You have no folders yet."):n.a.createElement(be.a,null)),o&&!!o.length&&n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3",dir:j.isRtl?"rtl":void 0},j("FilterRecommended")),o.map(e=>n.a.createElement(Ee.a,{className:"mb-2",narrow:!0,onClick:()=>y(e)},n.a.createElement("div",{className:"settings-folders-recommended-item"},n.a.createElement("div",{className:"multiline-item"},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.description)),n.a.createElement(R.a,{className:"px-3",color:"primary",size:"tiny",pill:!0,fluid:!0,isRtl:j.isRtl},j("Add")))))))}));a(269);var Qt=({count:e,itemName:t,itemPluralName:a,isLoading:c,onClick:r})=>{const s=Object(F.a)();return n.a.createElement(R.a,{className:"ShowMoreButton",color:"translucent",size:"smaller",isText:!0,isLoading:c,isRtl:s.isRtl,onClick:r},n.a.createElement("i",{className:"icon-down"}),"Show ",e," more ",e>1?a||t+"s":t)};const Xt="Please provide a title for this folder.",Jt="Please select at least one chat for this folder.";var ea=Object(n.h)(Object(c.h)(e=>{const{listIds:t}=e.chats;return{loadedActiveChatIds:t.active,loadedArchivedChatIds:t.archived}},(e,t)=>Object(u.l)(t,["editChatFolder","addChatFolder","loadMoreChats"]))(({state:e,dispatch:t,onAddIncludedChats:a,onAddExcludedChats:c,onReset:r,loadedActiveChatIds:s,loadedArchivedChatIds:o,editChatFolder:i,addChatFolder:d,loadMoreChats:h})=>{const[b,g]=Object(n.r)(),[p,v]=Object(n.r)(!1),E=Object(n.m)(()=>v(!0),[]),[O,f]=Object(n.r)(!1),[j,C]=Object(n.r)(!1),{selectedChatIds:y,selectedChatTypes:k}=Mt(e,"included"),{selectedChatIds:N,selectedChatTypes:I}=Mt(e,"excluded");Object(n.n)(()=>{b||Object(Kt.a)("FoldersNew").then(g)},[b]),Object(n.n)(()=>{f(!1),C(!1)},[e.folderId]);const[S,w]=Object(n.p)(()=>{const e=new Set([...s||[],...o||[]]),t=Object(u.f)(y,e),a=Object(u.f)(N,e);return[O?t:t.slice(0,5-k.length),j?a:a.slice(0,5-I.length)]},[N,y,k,I,j,O,s,o]);Object(n.n)(()=>{(S.lengthf(!0):()=>C(!0);return n.a.createElement(n.a.Fragment,null,t.map(t=>function(e,t){const a="included"===t?It.find(({key:t})=>t===e):St.find(({key:t})=>t===e);if(a)return n.a.createElement(Ee.a,{key:a.key,className:"settings-folders-list-item mb-1",icon:a.icon,narrow:!0,inactive:!0},P(a.title))}(t,e)),a.map(e=>n.a.createElement(Ee.a,{className:"settings-folders-list-item mb-1",narrow:!0,inactive:!0},Object(m.lb)(e)?n.a.createElement(Oe.a,{avatarSize:"small",userId:e}):n.a.createElement(fe.a,{avatarSize:"small",chatId:e}))),!c&&r>0&&n.a.createElement(Qt,{count:r,itemName:"chat",onClick:s}))}return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},b&&n.a.createElement(Wt.a,{id:"settingsFoldersEdit",size:l.tb,animationData:b,play:p&&String(e.folderId),noLoop:!0,onLoad:E})),"create"===e.mode&&n.a.createElement("p",{className:"settings-item-description mb-3",dir:P.isRtl?"rtl":void 0},P("FilterIncludeInfo")),n.a.createElement(pe.a,{className:"mb-0",label:P("FilterNameHint"),value:e.folder.title,onChange:function(e){const{currentTarget:a}=e;t({type:"setTitle",payload:a.value.trim()})},error:e.error&&e.error===Xt?Xt:void 0})),n.a.createElement("div",{className:"settings-item no-border pt-3"},e.error&&e.error===Jt&&n.a.createElement("p",{className:"settings-item-description color-danger mb-2",dir:P.isRtl?"rtl":void 0},e.error),n.a.createElement("h4",{className:"settings-item-header mb-3",dir:P.isRtl?"rtl":void 0},P("FilterInclude")),n.a.createElement(Ee.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:a},P("FilterAddChats")),M("included")),n.a.createElement("div",{className:"settings-item no-border pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3",dir:P.isRtl?"rtl":void 0},P("FilterExclude")),n.a.createElement(Ee.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:c},P("FilterAddChats")),M("excluded"))),n.a.createElement(Gt,{isShown:!!e.isTouched,disabled:e.isLoading,onClick:function(){const{title:a}=e.folder;a?y.length||Object.keys(k).length?(t({type:"setIsLoading",payload:!0}),"edit"===e.mode?i({id:e.folderId,folderUpdate:e.folder}):d({folder:e.folder}),setTimeout(()=>{r()},500)):t({type:"setError",payload:Jt}):t({type:"setError",payload:Xt})},ariaLabel:"edit"===e.mode?"Save changes":"Create folder"},e.isLoading?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),ta=a(46);a(186),a(270);var aa=Object(n.h)(({mode:e,chatIds:t,selectedIds:a,selectedChatTypes:c,filterValue:r,onSelectedIdsChange:s,onSelectedChatTypesChange:l,onFilterChange:o,onLoadMore:i})=>{const d=Object(n.q)(null),u="included"===e?It:St,h=a.length+c.length>10,b=a.length>=100;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{d.current.focus()})},500)},[]);const g=Object(n.m)(e=>{const t=[...a];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),s(t)},[a,s]),p=Object(n.m)(e=>{const t=[...c];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),l(t)},[c,l]),v=Object(n.m)(e=>{const{value:t}=e.currentTarget;o(t)},[o]),E=Object(F.a)();const[O,f]=Object(ue.a)(i,t,Boolean(r));return n.a.createElement("div",{className:"Picker SettingsFoldersChatsPicker"},n.a.createElement("div",{className:"picker-header custom-scroll"},c.map((function(e){const t=u.find(({key:t})=>e===t);if(t)return n.a.createElement(tt.a,{icon:t.icon,title:E(t.title),isMinimized:h,canClose:!0,onClick:p,clickArg:t.key})})),a.map((e,t)=>n.a.createElement(tt.a,{chatOrUserId:e,isMinimized:h&&tp(e.key),ripple:!0},n.a.createElement("i",{className:"icon-"+e.icon}),n.a.createElement("h3",{className:"chat-type",dir:"auto"},E(e.title)),n.a.createElement(ta.a,{label:"",checked:c.includes(e.key),round:!0}))})),n.a.createElement("div",{key:"divider",className:"picker-list-divider"}),n.a.createElement("h4",{key:"header2",className:"settings-item-header",dir:E.isRtl?"rtl":void 0},E("FilterChats"))),O&&O.length?O.map((function(e){const t=a.includes(e);return n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable picker-list-item chat-item",onClick:()=>g(e),ripple:!0,disabled:!t&&b},Object(m.lb)(e)?n.a.createElement(Oe.a,{userId:e}):n.a.createElement(fe.a,{chatId:e,withChatType:!0}),n.a.createElement(ta.a,{label:"",checked:t,round:!0}))})):O&&!O.length?n.a.createElement("p",{className:"no-results",key:"no-results"},"Sorry, nothing found."):n.a.createElement(be.a,{key:"loading"})))});var na=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a,orderedPinnedIds:n}}=e;return{chatsById:t,listIds:a.active,orderedPinnedIds:n.active,archivedPinnedIds:n.archived,archivedListIds:a.archived}},(e,t)=>Object(u.l)(t,["loadMoreChats"]))(({mode:e,state:t,dispatch:a,chatsById:c,listIds:r,orderedPinnedIds:s,archivedListIds:l,archivedPinnedIds:o,loadMoreChats:i})=>{const{chatFilter:d}=t,{selectedChatIds:u,selectedChatTypes:h}=Mt(t,e,!0),b=Object(F.a)(),g=Object(n.p)(()=>{const e=r?Object(m.Ab)(c,r,s,"all"):void 0,t=l?Object(m.Ab)(c,l,o,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[c,r,s,l,o]),p=Object(n.p)(()=>{if(g)return g.filter(e=>!d||Object(me.a)(Object(m.l)(b,e),d)||u.includes(e.id)).map(({id:e})=>e)},[g,d,b,u]),v=Object(n.m)(e=>{a({type:"setChatFilter",payload:e})},[a]),E=Object(n.m)(n=>{a("included"===e?{type:"setIncludeFilters",payload:{...t.includeFilters,includedChatIds:n}}:{type:"setExcludeFilters",payload:{...t.excludeFilters,excludedChatIds:n}})},[e,t,a]),O=Object(n.m)(t=>{const n={};t.forEach(e=>{n[e]=!0}),a("included"===e?{type:"setIncludeFilters",payload:{includedChatIds:u,...n}}:{type:"setExcludeFilters",payload:{excludedChatIds:u,...n}})},[e,u,a]);return p?n.a.createElement(aa,{mode:e,chatIds:p,selectedIds:u,selectedChatTypes:h,filterValue:d,onSelectedIdsChange:E,onSelectedChatTypesChange:O,onFilterChange:v,onLoadMore:i}):n.a.createElement(be.a,null)}));a(271);var ca=Object(n.h)(({currentScreen:e,state:t,dispatch:a,onScreenSelect:c,onReset:r})=>{const l=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{a({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?r():"create"===t.mode?c(s.m.FoldersCreateFolder):c(s.m.FoldersEditFolder)},[t.mode,a,e,r,c]),o=Object(n.m)(()=>{a({type:"reset"}),c(s.m.FoldersCreateFolder)},[c,a]),i=Object(n.m)(e=>{a({type:"editFolder",payload:e}),c(s.m.FoldersEditFolder)},[a,c]),d=Object(n.m)(()=>{a({type:"editIncludeFilters"}),c(s.m.FoldersIncludedChats)},[a,c]),m=Object(n.m)(()=>{a({type:"editExcludeFilters"}),c(s.m.FoldersExcludedChats)},[a,c]);switch(e){case s.m.Folders:return n.a.createElement(Zt,{onCreateFolder:o,onEditFolder:i});case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:return n.a.createElement(ea,{state:t,dispatch:a,onAddIncludedChats:d,onAddExcludedChats:m,onReset:l});case s.m.FoldersIncludedChats:return n.a.createElement(na,{mode:"included",state:t,dispatch:a});case s.m.FoldersExcludedChats:return n.a.createElement(na,{mode:"excluded",state:t,dispatch:a});default:return}}),ra=a(107);a(272);var sa=Object(n.h)(({options:e,range:t,label:a,value:c,disabled:r,onChange:s})=>{const l=Object(F.a)(),o=Object(n.m)(e=>{s(Number(e.currentTarget.value))},[s]),i=Object(ce.a)("RangeSlider",r&&"disabled"),d=Object(n.p)(()=>{if(e)return c/(e.length-1)*100;if(t){const e=(t.max-t.min)/(t.step||1);return(c-t.min)/e*100}return 0},[c,e,t]),[m,u,h]=Object(n.p)(()=>e?[0,e.length-1,1]:t?[t.min,t.max,t.step||1]:[0,0,0],[t,e]);return n.a.createElement("div",{className:i},a&&n.a.createElement("div",{className:"slider-top-row",dir:l.isRtl?"rtl":void 0},n.a.createElement("span",{className:"label",dir:"auto"},a),t&&n.a.createElement("span",{className:"value",dir:"auto"},c)),n.a.createElement("div",{className:"slider-main"},n.a.createElement("div",{className:"slider-fill-track",style:`width: ${d}%`}),n.a.createElement("input",{min:m,max:u,value:c,step:h,type:"range",onChange:o}),e&&n.a.createElement("div",{className:"slider-options"},e.map((e,t)=>n.a.createElement("div",{className:Object(ce.a)("slider-option no-selection",t===c&&"active"),onClick:()=>s(t)},e)))))}),la=a(126),oa=a(114),ia=a(49);var da=Object(n.h)(({size:e=l.zb,stickerSet:t,observeIntersection:a})=>{const c=Object(n.q)(null),s=Object(ra.b)(c,a),o="stickerSet"+t.id,i=Object(v.a)(o,!s,r.ApiMediaFormat.Lottie),{shouldRenderFullMedia:d,transitionClassNames:m}=Object(oa.a)(i,"slow");return n.a.createElement("div",{ref:c,className:"sticker-set-cover"},!d&&Object(ia.c)(t.title,2),d&&i&&n.a.createElement(Wt.a,{id:o,size:e,animationData:i,className:m}))});var ma=Object(n.h)(({stickerSet:e,observeIntersection:t})=>{const a=Object(n.q)(null),c=Object(ra.b)(a,t),r=Object(v.a)(e.hasThumbnail&&"stickerSet"+e.id,!c),{shouldRenderFullMedia:s,transitionClassNames:l}=Object(oa.a)(r,"slow");return n.a.createElement("div",{ref:a,className:"sticker-set-cover"},!s&&Object(ia.c)(e.title,2),s&&n.a.createElement("img",{src:r,className:l,alt:""}))});a(273);var ua=Object(n.h)(({sticker:e,size:t,observeIntersection:a,noAnimate:c,title:s,className:l,onClick:o,clickArg:i,onUnfaveClick:d})=>{const m=Object(n.q)(null),u="sticker"+e.id,h="sticker-button-"+e.id,b=Object(ra.b)(m,a),g=e.thumbnail?e.thumbnail.dataUri:void 0,p=Object(v.a)(u+"?size=m",!b,r.ApiMediaFormat.BlobUrl),E=b&&!c,O=Object(v.a)(e.isAnimated&&u,!E,r.ApiMediaFormat.Lottie),[f,j,C]=Object(Be.a)(Boolean(O)),y=f&&E,{shouldRenderThumb:k,shouldRenderFullMedia:N,transitionClassNames:I}=Object(oa.a)(p||y,"slow");Object(n.n)(()=>{E||C()},[C,E]);const S=Object(ce.a)("StickerButton",e.isAnimated&&"animated",h,l),w=k&&g?`background-image: url('${g}');`:"";return n.a.createElement("div",{ref:m,className:S,title:s||e&&e.emoji,style:w,"data-sticker-id":e.id,onClick:function(){o&&o(i)}},N&&!y&&n.a.createElement("img",{src:p,className:I}),E&&O&&n.a.createElement(Wt.a,{id:u,animationData:O,play:!0,size:t,isLowPriority:!0,onLoad:j}),d&&n.a.createElement(R.a,{className:"sticker-unfave-button",color:"dark",round:!0,onClick:function(t){t.stopPropagation(),t.preventDefault(),d(e)}},n.a.createElement("i",{className:"icon-close"})))});a(274);var ha=Object(n.h)(({stickerSet:e,observeIntersection:t,onClick:a})=>{const c=Object(F.a)();if(!e||!e.stickers)return;const r=e.stickers&&e.stickers[0];return e.hasThumbnail||!r?n.a.createElement(Ee.a,{narrow:!0,className:"SettingsStickerSet",inactive:!r,onClick:()=>r&&a(r)},n.a.createElement(R.a,{ariaLabel:e.title,color:"translucent",isRtl:c.isRtl},e.isAnimated?n.a.createElement(da,{size:l.ub,stickerSet:e,observeIntersection:t}):n.a.createElement(ma,{stickerSet:e,observeIntersection:t})),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i")))):n.a.createElement(Ee.a,{narrow:!0,className:"SettingsStickerSet",onClick:()=>a(r)},n.a.createElement(ua,{sticker:r,size:l.ub,title:e.title,observeIntersection:t}),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i"))))}),ba=a(161);const ga=["Solid and Steady","Nice and Fast","Lots of Stuff"];var pa=Object(n.h)(Object(c.h)(e=>({...Object(u.l)(e.settings.byKey,["messageTextSize","animationLevel","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers"]),stickerSetIds:e.stickers.added.setIds,stickerSetsById:e.stickers.setsById}),(e,t)=>Object(u.l)(t,["setSettingOption","loadStickerSets","loadAddedStickers"]))(({onScreenSelect:e,stickerSetIds:t,stickerSetsById:a,messageTextSize:c,animationLevel:r,messageSendKeyCombo:l,shouldAutoDownloadMediaFromContacts:i,shouldAutoDownloadMediaInPrivateChats:d,shouldAutoDownloadMediaInGroups:m,shouldAutoDownloadMediaInChannels:u,shouldAutoPlayGifs:h,shouldAutoPlayVideos:b,shouldSuggestStickers:g,shouldLoopStickers:p,setSettingOption:v,loadStickerSets:E,loadAddedStickers:O})=>{const f=Object(n.q)(null),{observe:j}=Object(ra.a)({rootRef:f}),[C,y,k]=Object(Be.a)(),[N,I]=Object(n.r)(),S=Object(F.a)(),w=o.l?void 0:[{value:"enter",label:S("lng_settings_send_enter"),subLabel:"New line by Shift + Enter"},{value:"ctrl-enter",label:S(o.f?"lng_settings_send_cmdenter":"lng_settings_send_ctrlenter"),subLabel:"New line by Enter"}];Object(n.n)(()=>{E()},[E]),Object(n.n)(()=>{t&&t.length&&O()},[t,O]);const P=Object(n.m)(e=>{ga.forEach((t,a)=>{document.body.classList.toggle("animation-level-"+a,e===a)}),v({animationLevel:e})},[v]),M=Object(n.m)(e=>{document.documentElement.style.setProperty("--message-text-size",e+"px"),v({messageTextSize:e})},[v]),L=Object(n.m)(e=>{I(e),y()},[y]),A=t&&t.map(e=>!!(a&&a[e]&&a[e].installedDate)&&a[e]).filter(Boolean);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("SETTINGS")),n.a.createElement(sa,{label:S("TextSize"),range:{min:12,max:20},value:c,onChange:M}),n.a.createElement(Ee.a,{icon:"photo",onClick:()=>e(s.m.GeneralChatBackground)},S("ChatBackground"))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},"Animation Level"),n.a.createElement("p",{className:"settings-item-description",dir:S.isRtl?"rtl":void 0},"Choose the desired animations amount."),n.a.createElement(sa,{options:ga,value:r,onChange:P})),w&&n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("Keyboard")),n.a.createElement(la.a,{name:"keyboard-send-settings",options:w,onChange:e=>v({messageSendKeyCombo:e}),selected:l})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("AutoDownloadMedia")),n.a.createElement(ta.a,{label:S("Contacts"),checked:i,onCheck:e=>v({shouldAutoDownloadMediaFromContacts:e})}),n.a.createElement(ta.a,{label:S("AutodownloadPrivateChats"),checked:d,onCheck:e=>v({shouldAutoDownloadMediaInPrivateChats:e})}),n.a.createElement(ta.a,{label:S("AutodownloadGroupChats"),checked:m,onCheck:e=>v({shouldAutoDownloadMediaInGroups:e})}),n.a.createElement(ta.a,{label:S("FilterChannels"),checked:u,onCheck:e=>v({shouldAutoDownloadMediaInChannels:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("AutoplayMedia")),n.a.createElement(ta.a,{label:S("GifsTab2"),checked:h,onCheck:e=>v({shouldAutoPlayGifs:e})}),n.a.createElement(ta.a,{label:S("VideosTitle"),checked:b,onCheck:e=>v({shouldAutoPlayVideos:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("AccDescrStickers")),n.a.createElement(ta.a,{label:S("SuggestStickers"),checked:g,onCheck:e=>v({shouldSuggestStickers:e})}),n.a.createElement(ta.a,{label:S("LoopAnimatedStickers"),checked:p,onCheck:e=>v({shouldLoopStickers:e})}),n.a.createElement("div",{className:"mt-4",ref:f},A&&A.map(e=>n.a.createElement(ha,{key:e.id,stickerSet:e,observeIntersection:j,onClick:L}))),N&&n.a.createElement(ba.a,{isOpen:C,fromSticker:N,onClose:k})))}));let va;function Ea(e="*",t,a=!1){va||(va=document.createElement("input"),va.setAttribute("type","file")),va.setAttribute("accept",e),a?va.removeAttribute("multiple"):va.setAttribute("multiple","multiple"),va.onchange=null,va.value="",va.onchange=t,va.click()}var Oa=a(13);function fa(e){return[parseInt(e.substring(0,2),16),parseInt(e.substring(2,4),16),parseInt(e.substring(4,6),16)]}function ja(e){const t=e[0].toString(16),a=e[1].toString(16),n=e[2].toString(16);return(1==t.length?"0"+t:t)+(1==a.length?"0"+a:a)+(1==n.length?"0"+n:n)}function Ca([e,t,a]){e/=255,t/=255,a/=255;let n,c,r=Math.max(e,t,a),s=Math.min(e,t,a),l=r,o=r-s;if(c=0==r?0:o/r,r==s)n=0;else{switch(r){case e:n=(t-a)/o+(t.5?Math.max(0,.65*n):Math.max(0,Math.min(1,1-.65*n)),`hsla(${360*t}, ${100*a}%, ${100*n}%, .4)`}var Na=a(12),Ia=a(162);a(275);var Sa=Object(n.h)(({wallpaper:e,theme:t,isSelected:a,onClick:c})=>{const{slug:r,document:o}=e,i="wallpaper"+o.id,d=o.previewBlobUrl,m=Object(v.a)(i+"?size=m"),u=Object(Ia.a)(o.thumbnail&&o.thumbnail.dataUri,Boolean(m),!0),{shouldRenderThumb:h,shouldRenderFullMedia:b,transitionClassNames:g}=Object(oa.a)(m||d,"slow"),[p,O]=Object(n.r)(!1),{mediaData:j,downloadProgress:C}=Object(E.a)(i,!p),y=!1===Object(f.a)(p),{shouldRender:k,transitionClassNames:N}=Object(K.a)(p&&!j||r===s.n,void 0,y,"slow"),I=Object(n.q)();I.current=t;const S=Object(n.m)(()=>{(async()=>{const e=await Object(Oa.e)(j);await Na.d(l.m,I.current,e),c(r)})()},[j,c,r]);Object(n.n)(()=>{j&&S()},[j,S]);const w=Object(n.m)(()=>{j?S():O(e=>!e)},[j,S]),P=Object(ce.a)("WallpaperTile",a&&"selected");return n.a.createElement("div",{className:P,onClick:w},n.a.createElement("div",{className:"media-inner"},h&&n.a.createElement("canvas",{ref:u,className:"thumbnail"}),b&&n.a.createElement("img",{src:m||d,className:"full-media "+g,alt:""}),k&&n.a.createElement("div",{className:Object(ce.a)("spinner-container",N)},n.a.createElement($.a,{progress:C,onClick:w}))))});a(276);const wa=Object(_.g)(e=>e(),6e4,!0);var Pa=Object(n.h)(Object(c.h)(e=>{const{theme:t}=e.settings.byKey,{background:a,isBlurred:n}=e.settings.themes[t]||{},{loadedWallpapers:c}=e.settings;return{background:a,isBlurred:n,loadedWallpapers:c,theme:t}},(e,t)=>Object(u.l)(t,["loadWallpapers","uploadWallpaper","setThemeSettings"]))(({onScreenSelect:e,background:t,isBlurred:a,loadedWallpapers:c,theme:r,loadWallpapers:o,uploadWallpaper:i,setThemeSettings:d})=>{const m=Object(n.q)();m.current=r,Object(n.n)(()=>{wa(()=>{o()})},[o]);const u=Object(n.m)(e=>{const{files:t}=e.target;t&&t.length>0&&i(t[0])},[i]),h=Object(n.m)(()=>{Ea("image/jpeg",u,!0)},[u]),b=Object(n.m)(()=>{e(s.m.GeneralChatBackgroundColor)},[e]),g=Object(n.m)(()=>{d({theme:r,background:void 0,backgroundColor:void 0,isBlurred:!0,patternColor:"dark"===r?l.o:l.t})},[d,r]),p=Object(n.m)(e=>{d({theme:m.current,background:e});const t=c&&c.find(t=>t.slug===e);t&&t.document.thumbnail&&async function(e){const t=[0,0,0];let a,n,c,r,s=-4,l=[0,0,0],o=0;const i=document.createElement("canvas"),d=i.getContext&&i.getContext("2d");if(!d)return t;const m=await Object(Oa.g)(e);c=m.naturalHeight||m.offsetHeight||m.height,n=m.naturalWidth||m.offsetWidth||m.width,i.height=c,i.width=n,d.drawImage(m,0,0);try{a=d.getImageData(0,0,n,c)}catch(e){return t}for(r=a.data.length;(s+=20){const t=ka(e),a="#"+ja(e);d({theme:m.current,backgroundColor:a,patternColor:t})})},[c,d]),v=Object(n.m)(e=>{d({theme:m.current,isBlurred:e.target.checked})},[d]),E=Object(F.a)(),O=c&&c[0]&&c[0].slug===s.n;return n.a.createElement("div",{className:"SettingsGeneralBackground settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(Ee.a,{icon:"camera-add",className:"mb-0",disabled:O,onClick:h},E("UploadImage")),n.a.createElement(Ee.a,{icon:"colorize",className:"mb-0",onClick:b},E("SetColor")),n.a.createElement(Ee.a,{icon:"favorite",onClick:g},E("ThemeResetToDefaults")),n.a.createElement(ta.a,{label:E("BackgroundBlurred"),checked:Boolean(a),onChange:v})),c?n.a.createElement("div",{className:"settings-wallpapers"},c.map(e=>n.a.createElement(Sa,{wallpaper:e,theme:r,isSelected:t===e.slug,onClick:p}))):n.a.createElement(be.a,null))}));a(277);const Ma=Ca(fa("e6ebee")),Fa=["#e6ebee","#b2cee1","#008dd0","#c6e7cb","#c4e1a6","#60b16e","#ccd0af","#a6a997","#7a7072","#fdd7af","#fdb76e","#dd8851"];function La(e,t){return{colorPosition:[Math.round(e[1]*(t.colorRect.width-1)),Math.round((1-e[2])*(t.colorRect.height-1))],huePosition:Math.round(e[0]*(t.hueRect.width-1))}}function Aa({colorPosition:e,huePosition:t},a){return[t/(a.hueRect.width-1),e[0]/(a.colorRect.width-1),1-e[1]/(a.colorRect.height-1)]}var Ta=Object(n.h)(Object(c.h)(e=>{const{theme:t}=e.settings.byKey,{backgroundColor:a}=e.settings.themes[t]||{};return{backgroundColor:a,theme:t}},(e,t)=>Object(u.l)(t,["setThemeSettings"]))(({theme:e,backgroundColor:t,setThemeSettings:a})=>{const c=Object(n.q)();c.current=e;const r=Object(n.q)(null),s=Object(n.q)(null),l=Object(n.q)(null),o=Object(n.q)(!0),[i,d]=Object(n.r)(function(e){return e&&e.startsWith("#")?Ca(fa(e.replace("#",""))):Ma}(t)),m=Object(n.q)(i);Object(n.n)(()=>{m.current=i},[i]);const[b,g,p]=Object(Be.a)(),[v,E]=Object(n.r)(""),[O,f]=Object(n.r)(""),j=Object(n.q)(),C=Object(n.q)();Object(n.n)(()=>{const e={offsetLeft:s.current.offsetLeft,...Object(u.l)(s.current.getBoundingClientRect(),["top","width","height"])},t={offsetLeft:l.current.offsetLeft,...Object(u.l)(l.current.getBoundingClientRect(),["width"])};function a(t){const a=[Math.min(Math.max(0,t.pageX-e.offsetLeft),e.width-1),Math.min(Math.max(0,t.pageY-e.top+r.current.scrollTop),e.height-1)],{huePosition:n}=La(m.current,j.current);d(Aa({colorPosition:a,huePosition:n},j.current)),g()}function n(e){const{colorPosition:a}=La(m.current,j.current),n=Math.min(Math.max(0,e.pageX-t.offsetLeft),t.width-1);d(Aa({colorPosition:a,huePosition:n},j.current)),g()}j.current={colorRect:e,hueRect:t},Object(h.b)(s.current,{onCapture:a,onDrag:a,onRelease:p,onClick:p,withCursor:!0}),Object(h.b)(l.current,{onCapture:n,onDrag:n,onRelease:p,onClick:p,withCursor:!0})},[g,p]);const{colorPosition:y=[0,0],huePosition:k=0}=j.current?La(i,j.current):{},N=ja(ya(i)),I=i[0],S=ja(ya([I,1,1]));Object(n.n)(()=>{const e=ya(i),t="#"+ja(e);if(E(e.join(", ")),f(t),!o.current){const n=ka(e);a({theme:c.current,background:void 0,backgroundColor:t,patternColor:n})}o.current=!1},[i,a]),Object(n.n)(()=>{!function(e,t,a,n){let c,r,s;a.current&&n.current?(c=n.current.colorRect.width,r=n.current.colorRect.height,s=a.current):(c=e.offsetWidth,r=e.offsetHeight,s=e.getContext("2d"),e.width=c,e.height=r,a.current=s);const l=s.createImageData(c,r),o=l.data,i=ya([t,1,1]);let d=0;for(let e=0;e{!function(e){const t=e.offsetWidth;e.width=t,e.height=1;const a=e.getContext("2d"),n=a.createImageData(t,1),c=n.data;let r=0;for(let e=0;e{const t=e.currentTarget.value.replace(/[^\d, ]/g,"").slice(0,13);if(t.match(/^\d{1,3},\s?\d{1,3},\s?\d{1,3}$/)){const e=t.split(",").map(e=>Number(e.trim()));d(Ca(e))}e.currentTarget.value=t},[]),P=Object(n.m)(e=>{const t=e.currentTarget.value.replace(/[^0-9a-fA-F]/g,"").slice(0,6);t.match(/^#?[0-9a-fA-F]{6}$/)&&d(Ca(fa(t.replace("#","")))),e.currentTarget.value=t},[]),M=Object(n.m)(e=>{d(Ca(fa(e.currentTarget.dataset.color.replace("#",""))))},[]),F=Object(ce.a)("SettingsGeneralBackgroundColor settings-content custom-scroll",b&&"is-dragging");return n.a.createElement("div",{ref:r,className:F},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("div",{ref:s,className:"color-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translate(${y[0]}px, ${y[1]}px); background-color: #${N};`})),n.a.createElement("div",{ref:l,className:"hue-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translateX(${k}px); background-color: #${S};`})),n.a.createElement("div",{className:"tools"},n.a.createElement(pe.a,{value:O,label:"HEX",onChange:P}),n.a.createElement(pe.a,{value:v,label:"RGB",onChange:w}))),n.a.createElement("div",{className:"predefined-colors"},Fa.map(e=>n.a.createElement("div",{className:e==="#"+N?"active":void 0,"data-color":e,style:`background-color: ${e};`,onClick:M}))))}));var Ra=Object(n.h)(Object(c.h)(e=>({hasPrivateChatsNotifications:Boolean(e.settings.byKey.hasPrivateChatsNotifications),hasPrivateChatsMessagePreview:Boolean(e.settings.byKey.hasPrivateChatsMessagePreview),hasGroupNotifications:Boolean(e.settings.byKey.hasGroupNotifications),hasGroupMessagePreview:Boolean(e.settings.byKey.hasGroupMessagePreview),hasBroadcastNotifications:Boolean(e.settings.byKey.hasBroadcastNotifications),hasBroadcastMessagePreview:Boolean(e.settings.byKey.hasBroadcastMessagePreview),hasContactJoinedNotifications:Boolean(e.settings.byKey.hasContactJoinedNotifications)}),(e,t)=>Object(u.l)(t,["loadNotificationSettings","updateContactSignUpNotification","updateNotificationSettings"]))(({hasPrivateChatsNotifications:e,hasPrivateChatsMessagePreview:t,hasGroupNotifications:a,hasGroupMessagePreview:c,hasBroadcastNotifications:r,hasBroadcastMessagePreview:s,hasContactJoinedNotifications:l,loadNotificationSettings:o,updateContactSignUpNotification:i,updateNotificationSettings:d})=>{Object(n.n)(()=>{o()},[o]);const m=Object(n.m)((n,l,o)=>{const i="contact"===l?!e:!("group"===l?a:r),m="contact"===l?t:"group"===l?c:s;d({peerType:l,..."silent"===o&&{isSilent:!n.target.checked,shouldShowPreviews:m},..."showPreviews"===o&&{shouldShowPreviews:n.target.checked,isSilent:i}})},[s,r,c,a,t,e,d]),u=Object(n.m)(e=>{i({isSilent:!e.target.checked})},[i]),h=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("AutodownloadPrivateChats")),n.a.createElement(ta.a,{label:h("NotificationsForPrivateChats"),subLabel:h(e?"NotificationsEnabled":"NotificationsDisabled"),checked:e,onChange:e=>{m(e,"contact","silent")}}),n.a.createElement(ta.a,{label:h("MessagePreview"),subLabel:h(t?"PreviewEnabled":"PreviewDisabled"),checked:t,onChange:e=>{m(e,"contact","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("FilterGroups")),n.a.createElement(ta.a,{label:h("NotificationsForGroups"),subLabel:h(a?"NotificationsEnabled":"NotificationsDisabled"),checked:a,onChange:e=>{m(e,"group","silent")}}),n.a.createElement(ta.a,{label:h("MessagePreview"),subLabel:h(c?"PreviewEnabled":"PreviewDisabled"),checked:c,onChange:e=>{m(e,"group","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("FilterChannels")),n.a.createElement(ta.a,{label:h("NotificationsForChannels"),subLabel:h(r?"NotificationsEnabled":"NotificationsDisabled"),checked:r,onChange:e=>{m(e,"broadcast","silent")}}),n.a.createElement(ta.a,{label:h("MessagePreview"),subLabel:h(s?"PreviewEnabled":"PreviewDisabled"),checked:s,onChange:e=>{m(e,"broadcast","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("PhoneOther")),n.a.createElement(ta.a,{label:h("ContactJoined"),checked:l,onChange:u})))}));var Da=Object(n.h)(Object(c.h)(e=>{const{settings:{byKey:{hasPassword:t},privacy:a},blocked:n,activeSessions:c}=e;return{hasPassword:t,blockedCount:n.totalCount,sessionsCount:c.length,visibilityPrivacyPhoneNumber:a.phoneNumber&&a.phoneNumber.visibility,visibilityPrivacyLastSeen:a.lastSeen&&a.lastSeen.visibility,visibilityPrivacyProfilePhoto:a.profilePhoto&&a.profilePhoto.visibility,visibilityPrivacyForwarding:a.forwards&&a.forwards.visibility,visibilityPrivacyGroupChats:a.chatInvite&&a.chatInvite.visibility}},(e,t)=>Object(u.l)(t,["loadBlockedContacts","loadAuthorizations","loadPrivacySettings"]))(({onScreenSelect:e,hasPassword:t,blockedCount:a,sessionsCount:c,visibilityPrivacyPhoneNumber:r,visibilityPrivacyLastSeen:l,visibilityPrivacyProfilePhoto:o,visibilityPrivacyForwarding:i,visibilityPrivacyGroupChats:d,loadPrivacySettings:m,loadBlockedContacts:u,loadAuthorizations:h})=>{Object(n.n)(()=>{u(),h(),m()},[u,h,m]);const b=Object(F.a)();function g(e){switch(e){case"everybody":return b("P2PEverybody");case"contacts":return b("P2PContacts");case"nobody":return b("P2PNobody")}}return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(Ee.a,{icon:"delete-user",narrow:!0,onClick:()=>e(s.m.PrivacyBlockedUsers)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("BlockedUsers")),a>0&&n.a.createElement("span",{className:"subtitle",dir:"auto"},b("Users",a)))),n.a.createElement(Ee.a,{icon:"lock",narrow:!0,onClick:()=>e(t?s.m.TwoFaEnabled:s.m.TwoFaDisabled)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("TwoStepVerification")),n.a.createElement("span",{className:"subtitle",dir:"auto"},b(t?"PasswordOn":"PasswordOff")))),n.a.createElement(Ee.a,{icon:"active-sessions",narrow:!0,onClick:()=>e(s.m.PrivacyActiveSessions)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("SessionsTitle")),c>0&&n.a.createElement("span",{className:"subtitle",dir:"auto"},1===c?"1 session":c+" sessions")))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:b.isRtl?"rtl":void 0},b("PrivacyTitle")),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyPhoneNumber)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyPhoneTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(r)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyLastSeen)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("LastSeenTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(l)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyProfilePhoto)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyProfilePhotoTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(o)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyForwarding)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyForwardsTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(i)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyGroupChats)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("WhoCanAddMe")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(d))))))})),Ba=a(14);var xa=Object(n.h)(Object(c.h)(e=>({languages:e.settings.byKey.languages,language:e.settings.byKey.language}),(e,t)=>Object(u.l)(t,["loadLanguages","setSettingOption"]))(({languages:e,language:t,loadLanguages:a,setSettingOption:c})=>{const[r,s]=Object(n.r)(t),[l,o,i]=Object(Be.a)();Object(n.n)(()=>{a()},[a]);const d=Object(n.m)(e=>{s(e),o(),Object(Ba.c)(e,()=>{i(),c({language:e})})},[o,i,c]),m=Object(n.p)(()=>e?function(e){const t=(window.navigator.language||"en").toLowerCase(),a=t.substr(0,2);return e.map(({langCode:e,nativeName:t,name:a})=>({value:e,label:t,subLabel:a})).sort(e=>!t||e.value!==t&&e.value!==a?0:-1)}(e):void 0,[e]);return n.a.createElement("div",{className:"settings-content settings-item settings-language custom-scroll"},m?n.a.createElement(la.a,{name:"keyboard-send-settings",options:m,selected:r,loadingOption:l?r:void 0,onChange:d}):n.a.createElement(be.a,null))}));function Ua(e){switch(e){case s.m.PrivacyPhoneNumber:case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return"phoneNumber";case s.m.PrivacyLastSeen:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return"lastSeen";case s.m.PrivacyProfilePhoto:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return"profilePhoto";case s.m.PrivacyForwarding:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return"forwards";case s.m.PrivacyGroupChats:case s.m.PrivacyGroupChatsAllowedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return"chatInvite"}}var Ga=Object(n.h)(Object(c.h)((e,{screen:t})=>{let a;const{chats:{byId:n},settings:{privacy:c}}=e;switch(t){case s.m.PrivacyPhoneNumber:a=c.phoneNumber;break;case s.m.PrivacyLastSeen:a=c.lastSeen;break;case s.m.PrivacyProfilePhoto:a=c.profilePhoto;break;case s.m.PrivacyForwarding:a=c.forwards;break;case s.m.PrivacyGroupChats:a=c.chatInvite}return a?{...a,chatsById:n}:{}},(e,t)=>Object(u.l)(t,["setPrivacyVisibility"]))(({screen:e,onScreenSelect:t,visibility:a,allowUserIds:c,allowChatIds:r,blockUserIds:l,blockChatIds:o,chatsById:i,setPrivacyVisibility:d})=>{const m=Object(F.a)(),u=Object(n.p)(()=>{switch(e){case s.m.PrivacyProfilePhoto:case s.m.PrivacyGroupChats:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")}];default:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")},{value:"nobody",label:m("P2PNobody")}]}},[m,e]),h={shouldShowDenied:"nobody"!==a,shouldShowAllowed:"everybody"!==a},b=Ua(e),g=Object(n.p)(()=>{switch(e){case s.m.PrivacyPhoneNumber:return m("PrivacyPhoneTitle");case s.m.PrivacyLastSeen:return m("LastSeenTitle");case s.m.PrivacyProfilePhoto:return m("PrivacyProfilePhotoTitle");case s.m.PrivacyForwarding:return m("PrivacyForwardsTitle");case s.m.PrivacyGroupChats:return m("WhoCanAddMe");default:return}},[m,e]),p=Object(n.p)(()=>{switch(e){case s.m.PrivacyLastSeen:return m("CustomHelp");default:return}},[m,e]),v=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberAllowedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenAllowedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoAllowedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingAllowedContacts;default:return s.m.PrivacyGroupChatsAllowedContacts}})(),E=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberDeniedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenDeniedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoDeniedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingDeniedContacts;default:return s.m.PrivacyGroupChatsDeniedContacts}})(),O=Object(n.p)(()=>c&&r&&i?r.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),c.length):0,[r,c,i]),f=Object(n.p)(()=>l&&o&&i?o.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),l.length):0,[o,l,i]),j=Object(n.m)(e=>{d({privacyKey:b,visibility:e})},[b,d]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:m.isRtl?"rtl":void 0},g),n.a.createElement(la.a,{name:"visibility-"+b,options:u,onChange:j,selected:a}),p&&n.a.createElement("p",{className:"settings-item-description-larger",dir:m.isRtl?"rtl":void 0},p)),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:m.isRtl?"rtl":void 0},m("PrivacyExceptions")),h.shouldShowAllowed&&n.a.createElement(Ee.a,{narrow:!0,icon:"add-user",onClick:()=>{t(v)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},O>0&&n.a.createElement("span",{className:"date",dir:"auto"},"+",O),n.a.createElement("span",{className:"title"},m("AlwaysShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers")))),h.shouldShowDenied&&n.a.createElement(Ee.a,{narrow:!0,icon:"delete-user",onClick:()=>{t(E)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},f>0&&n.a.createElement("span",{className:"date",dir:"auto"},"−",f),n.a.createElement("span",{className:"title"},m("NeverShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers"))))))}));function qa(e){return[e.region,e.country].filter(Boolean).join(", ")}function za(e){return`${e.deviceModel}${e.deviceModel?", ":""} ${e.platform} ${e.systemVersion}`}var $a=Object(n.h)(Object(c.h)(e=>({activeSessions:e.activeSessions}),(e,t)=>Object(u.l)(t,["loadAuthorizations","terminateAuthorization","terminateAllAuthorizations"]))(({activeSessions:e,loadAuthorizations:t,terminateAuthorization:a,terminateAllAuthorizations:c})=>{const[r,s,l]=Object(Be.a)();Object(n.n)(()=>{t()},[t]);const o=Object(n.m)(e=>{a({hash:e})},[a]),i=Object(n.m)(()=>{l(),c()},[l,c]),d=Object(n.p)(()=>e.find(e=>e.isCurrent),[e]),m=Object(n.p)(()=>e.filter(e=>!e.isCurrent),[e]),u=Object(F.a)();function h(e){return n.a.createElement(Ee.a,{key:e.hash,ripple:!0,narrow:!0,contextActions:[{title:"Terminate",icon:"stop",handler:()=>{o(e.hash)}}]},n.a.createElement("div",{className:"multiline-menu-item full-size",dir:"auto"},n.a.createElement("span",{className:"date"},Object(D.g)(u,1e3*e.dateActive)),n.a.createElement("span",{className:"title"},e.appName),n.a.createElement("span",{className:"subtitle black tight"},za(e)),n.a.createElement("span",{className:"subtitle"},e.ip," - ",qa(e))))}return n.a.createElement("div",{className:"settings-content custom-scroll"},d&&(g=d,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:u.isRtl?"rtl":void 0},u("AuthSessions.CurrentSession")),n.a.createElement(Ee.a,{narrow:!0,inactive:!0},n.a.createElement("div",{className:"multiline-menu-item",dir:"auto"},n.a.createElement("span",{className:"title",dir:"auto"},g.appName),n.a.createElement("span",{className:"subtitle black tight"},za(g)),n.a.createElement("span",{className:"subtitle"},g.ip," - ",qa(g)))),n.a.createElement(Ee.a,{className:"destructive mb-0",icon:"stop",ripple:!0,narrow:!0,onClick:s},u("TerminateAllSessions")))),m&&(b=m,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:u.isRtl?"rtl":void 0},"Other Sessions"),b.map(h))),m&&n.a.createElement(we.a,{isOpen:r,onClose:l,text:"Are you sure you want to terminate all other sessions?",confirmLabel:"Terminate All Other Sessions",confirmHandler:i,confirmIsDestructive:!0}),";");var b,g}));var Ha=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a},blocked:{ids:n}}=e;return{chatsByIds:t,usersByIds:a,blockedIds:n}},(e,t)=>Object(u.l)(t,["unblockContact"]))(({chatsByIds:e,usersByIds:t,blockedIds:a,unblockContact:c})=>{const r=Object(n.m)(e=>{c({contactId:e})},[c]),s=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content infinite-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("p",{className:"settings-item-description-larger mt-0 mb-2",dir:s.isRtl?"rtl":void 0},s("BlockedUsersInfo"))),n.a.createElement("div",{className:"chat-list custom-scroll"},a&&a.length?n.a.createElement("div",{className:"scroll-container"},a.map((a,c)=>function(a,c,o){const i=Object(m.lb)(a),d=i?t[a]:void 0,u=i?void 0:e[a],h=Object(ce.a)("Chat chat-item-clickable blocked-list-item",i?"private":"group");return n.a.createElement(Ee.a,{key:a,className:h,ripple:!0,narrow:!0,contextActions:[{title:"Unblock",icon:"unlock",handler:()=>{r(a)}}],style:`top: ${(o+c)*l.i}px;`},n.a.createElement(x.a,{size:"medium",user:d,chat:u}),n.a.createElement("div",{className:"contact-info",dir:"auto"},n.a.createElement("h3",{dir:"auto"},Object(B.a)((i?Object(m.Z)(d):Object(m.l)(s,u))||"")),d&&d.phoneNumber&&n.a.createElement("div",{className:"contact-phone",dir:"auto"},Object(Bt.c)(d.phoneNumber)),d&&!d.phoneNumber&&d.username&&n.a.createElement("div",{className:"contact-username",dir:"auto"},"@",d.username)))}(a,c,0))):a&&!a.length?n.a.createElement("div",{className:"no-results",dir:"auto"},"List is empty"):n.a.createElement(be.a,{key:"loading"}))),n.a.createElement(Gt,{isShown:!0,onClick:()=>{},className:"not-implemented",ariaLabel:"Add a blocked user"},n.a.createElement("i",{className:"icon-add"})))})),_a=a(128);var Va=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(_a.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},Object(B.a)(a("EnabledPasswordText"),["br"]))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(Ee.a,{icon:"edit",onClick:()=>t(s.m.TwoFaChangePasswordCurrent)},a("ChangePassword")),n.a.createElement(Ee.a,{icon:"password-off",onClick:()=>t(s.m.TwoFaTurnOff)},a("TurnPasswordOff")),n.a.createElement(Ee.a,{icon:"email",onClick:()=>t(s.m.TwoFaRecoveryEmailCurrentPassword)},a("SetRecoveryEmail"))))})),Ka=a(148),Wa=a(149);var Ya=Object(n.h)(({error:e,isLoading:t,expectedPassword:a,placeholder:c="Current Password",hint:r,submitLabel:s,clearError:l,onSubmit:o})=>{const[i,d]=Object(n.r)(""),[m,u]=Object(n.r)(!1),h=Object(n.m)(e=>{a&&e!==a?d("Passwords Should Be Equal"):o(e)},[o,a]),b=Object(n.m)(()=>{l&&l(),d("")},[l]),g=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Ka.a,{isBig:!0,isPasswordVisible:m})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(Wa.a,{error:i||e,hint:r,placeholder:c,submitLabel:s||g("Next"),clearError:b,isLoading:t,isPasswordVisible:m,onChangePasswordVisibility:u,onSubmit:h})))});var Za=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onStart:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(_a.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},a("SetAdditionalPasswordInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(R.a,{onClick:t},a("EditAdminTransferSetPassword"))))}));const Qa=o.g?550:400;var Xa=Object(n.h)(Object(c.h)((e,{icon:t})=>({animatedEmoji:Object(d.c)(e,"email"===t?"💌":"💡")}))(({animatedEmoji:e,type:t="text",isLoading:a,error:c,placeholder:r,shouldConfirm:s,clearError:l,onSubmit:i})=>{const d=Object(n.q)(null),[m,u]=Object(n.r)(""),[h,b,g]=Object(Be.a)(!1);Object(n.n)(()=>{o.l||setTimeout(()=>{d.current.focus()},Qa)},[]);const p=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(_a.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement("form",{action:"",onSubmit:e=>{e.preventDefault(),d.current&&i(m)}},n.a.createElement(pe.a,{ref:d,value:m,inputMode:t,label:r,error:c,onChange:e=>{c&&l&&l(),u(e.target.value)}}),m?n.a.createElement(R.a,{type:"submit",isLoading:a,ripple:!0},p("Continue")):n.a.createElement(R.a,{isText:!0,isLoading:a,ripple:!0,onClick:s?b:()=>{i()}},p("YourEmailSkip"))),s&&n.a.createElement(ge.a,{className:"narrow",isOpen:h,title:p("YourEmailSkipWarning"),onClose:g},Object(B.a)(p("YourEmailSkipWarningText"),["br","simple_markdown"]),n.a.createElement("div",{className:"dialog-buttons"},n.a.createElement(R.a,{color:"danger",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:()=>{g(),i()}},p("YourEmailSkip")),n.a.createElement(R.a,{color:"primary",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:g},p("Cancel"))))))}));var Ja=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🥳")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(_a.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},a("TwoStepVerificationPasswordSetInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(R.a,{onClick:()=>{t(s.m.Privacy)}},a("TwoStepVerificationPasswordReturnSettings"))))}));const en=o.g?550:400;var tn=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"💌"),codeLength:e.twoFaSettings.waitingEmailCodeLength}))(({animatedEmoji:e,codeLength:t,isLoading:a,error:c,clearError:r,onSubmit:s})=>{const l=Object(n.q)(null),[i,d]=Object(n.r)("");Object(n.n)(()=>{o.l||setTimeout(()=>{l.current.focus()},en)},[]);const m=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(_a.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(pe.a,{value:i,ref:l,inputMode:"decimal",label:m("YourEmailCode"),error:c,onChange:e=>{c&&r&&r();const a=e.target.value.slice(0,t);a.length===t&&s(a),d(a),e.target.value=a}}),a&&n.a.createElement(be.a,null)))}));var an=Object(n.h)(Object(c.h)(e=>({...e.twoFaSettings}),(e,t)=>Object(u.l)(t,["updatePassword","updateRecoveryEmail","clearPassword","provideTwoFaEmailCode","checkPassword","clearTwoFaError"]))(({currentScreen:e,state:t,hint:a,isLoading:c,error:r,waitingEmailCodeLength:l,dispatch:o,onScreenSelect:i,updatePassword:d,checkPassword:m,clearTwoFaError:u,updateRecoveryEmail:h,provideTwoFaEmailCode:b,clearPassword:g})=>{Object(n.n)(()=>{l&&(e===s.m.TwoFaNewPasswordEmail?i(s.m.TwoFaNewPasswordEmailCode):e===s.m.TwoFaRecoveryEmail&&i(s.m.TwoFaRecoveryEmailCode))},[e,i,l]);const p=Object(n.m)(()=>{o({type:"reset"}),i(s.m.TwoFaNewPassword)},[o,i]),v=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaNewPasswordConfirm)},[o,i]),E=Object(n.m)(()=>{i(s.m.TwoFaNewPasswordHint)},[i]),O=Object(n.m)(e=>{o({type:"setHint",payload:e}),i(s.m.TwoFaNewPasswordEmail)},[o,i]),f=Object(n.m)(e=>{o({type:"setEmail",payload:e}),d({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),j=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaChangePasswordNew)}})},[m,o,i]),C=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaChangePasswordConfirm)},[o,i]),y=Object(n.m)(()=>{i(s.m.TwoFaChangePasswordHint)},[i]),k=Object(n.m)(e=>{o({type:"setHint",payload:e}),d({...t,hint:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),N=Object(n.m)(e=>{g({currentPassword:e,onSuccess:()=>{i(s.m.Privacy)}})},[g,i]),I=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaRecoveryEmail)}})},[m,o,i]),S=Object(n.m)(e=>{o({type:"setEmail",payload:e}),h({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,h]),w=Object(n.m)(e=>{b({code:e})},[b]),P=Object(F.a)();switch(e){case s.m.TwoFaDisabled:return n.a.createElement(Za,{onStart:p});case s.m.TwoFaNewPassword:return n.a.createElement(Ya,{placeholder:P("EnterPassword"),submitLabel:P("Continue"),onSubmit:v});case s.m.TwoFaNewPasswordConfirm:return n.a.createElement(Ya,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),submitLabel:P("Continue"),onSubmit:E});case s.m.TwoFaNewPasswordHint:return n.a.createElement(Xa,{icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:O});case s.m.TwoFaNewPasswordEmail:return n.a.createElement(Xa,{icon:"email",type:"email",isLoading:c,error:r,clearError:u,placeholder:P("RecoveryEmailTitle"),shouldConfirm:!0,onSubmit:f});case s.m.TwoFaNewPasswordEmailCode:return n.a.createElement(tn,{isLoading:c,error:r,clearError:u,onSubmit:w});case s.m.TwoFaCongratulations:return n.a.createElement(Ja,{onScreenSelect:i});case s.m.TwoFaEnabled:return n.a.createElement(Va,{onScreenSelect:i});case s.m.TwoFaChangePasswordCurrent:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:j});case s.m.TwoFaChangePasswordNew:return n.a.createElement(Ya,{placeholder:P("PleaseEnterNewFirstPassword"),onSubmit:C});case s.m.TwoFaChangePasswordConfirm:return n.a.createElement(Ya,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),onSubmit:y});case s.m.TwoFaChangePasswordHint:return n.a.createElement(Xa,{isLoading:c,error:r,clearError:u,icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:k});case s.m.TwoFaTurnOff:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:N});case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement(Ya,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:I});case s.m.TwoFaRecoveryEmail:return n.a.createElement(Xa,{icon:"email",type:"email",placeholder:P("RecoveryEmailTitle"),onSubmit:S});case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(tn,{isLoading:c,error:r,clearError:u,onSubmit:w});default:return}}));var nn=Object(n.h)(({itemIds:e,selectedIds:t,filterValue:a,filterPlaceholder:c,notFoundText:r,searchInputId:s,isLoading:l,onSelectedIdsChange:o,onFilterChange:i,onLoadMore:d})=>{const u=Object(n.q)(null),h=t.length>10;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{u.current.focus()})},500)},[]);const b=Object(n.m)(e=>{const a=[...t];a.includes(e)?a.splice(a.indexOf(e),1):a.push(e),o(a),i("")},[t,o,i]),g=Object(n.m)(e=>{const{value:t}=e.currentTarget;i(t)},[i]),[p,v]=Object(ue.a)(d,e,Boolean(a)),E=Object(F.a)();return n.a.createElement("div",{className:"Picker"},n.a.createElement("div",{className:"picker-header custom-scroll",dir:E.isRtl?"rtl":void 0},t.map((e,a)=>n.a.createElement(tt.a,{chatOrUserId:e,isMinimized:h&&an.a.createElement(Ee.a,{key:e,className:"chat-item-clickable picker-list-item",onClick:()=>b(e),ripple:!0},n.a.createElement(ta.a,{label:"",checked:t.includes(e)}),Object(m.lb)(e)?n.a.createElement(Oe.a,{userId:e}):n.a.createElement(fe.a,{chatId:e})))):l||!p||p.length?n.a.createElement(be.a,null):n.a.createElement("p",{className:"no-results"},r||"Sorry, nothing found."))});function cn(e,t){const{privacy:a}=e.settings;switch(t){case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return a.phoneNumber;case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return a.lastSeen;case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return a.profilePhoto;case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return a.forwards;case s.m.PrivacyGroupChatsDeniedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return a.chatInvite}}var rn=Object(n.h)(Object(c.h)((e,{screen:t})=>{const{chats:{byId:a,listIds:n,orderedPinnedIds:c},currentUserId:r}=e;return{currentUserId:r,chatsById:a,listIds:n.active,orderedPinnedIds:c.active,archivedPinnedIds:c.archived,archivedListIds:n.archived,settings:cn(e,t)}},(e,t)=>Object(u.l)(t,["setPrivacySettings"]))(({currentUserId:e,isAllowList:t,screen:a,settings:c,chatsById:r,listIds:l,orderedPinnedIds:o,archivedListIds:i,archivedPinnedIds:d,setPrivacySettings:u,onScreenSelect:h})=>{const b=Object(F.a)(),g=Object(n.p)(()=>c?t?[...c.allowUserIds,...c.allowChatIds]:[...c.blockUserIds,...c.blockChatIds]:[],[t,c]),[p,v]=Object(n.r)(""),[E,O]=Object(n.r)(!1),[f,j]=Object(n.r)(g),C=Object(n.p)(()=>{const e=l?Object(m.Ab)(r,l,o,"all"):void 0,t=i?Object(m.Ab)(r,i,d,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[r,l,o,i,d]),y=Object(n.p)(()=>{if(C)return C.filter(t=>(Object(m.lb)(t.id)&&t.id!==e||Object(m.kb)(t))&&(!p||Object(me.a)(Object(m.l)(b,t),p)||g.includes(t.id))).map(({id:e})=>e)},[C,e,b,p,g]),k=Object(n.m)(e=>{j(e),O(!0)},[]),N=Object(n.m)(()=>{u({privacyKey:Ua(a),isAllowList:Boolean(t),contactsIds:f}),h(s.m.Privacy)},[t,f,h,a,u]);return n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(nn,{itemIds:y||[],selectedIds:f,filterValue:p,filterPlaceholder:b(t?"AlwaysShareWithPlaceholder":"NeverShareWithPlaceholder"),searchInputId:"new-group-picker-search",onSelectedIdsChange:k,onFilterChange:v}),n.a.createElement(Gt,{isShown:E,onClick:N,ariaLabel:b(t?"AlwaysShareWithTitle":"NeverShareWithTitle")},n.a.createElement("i",{className:"icon-arrow-right"})))}));a(278);const sn=Object.keys(s.m).length/2;var ln=Object(n.h)(({currentScreen:e,onScreenSelect:t,onReset:a})=>{const[c,r]=Nt(At,Lt),[l,i]=Nt(Rt,Tt),d=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{r({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?a():"create"===c.mode?t(s.m.FoldersCreateFolder):t(s.m.FoldersEditFolder)},[c.mode,r,e,a,t]),m=Object(n.m)(()=>{r({type:"saveFilters"}),d()},[r,d]);function u(){return n.a.createElement(n.a.Fragment,null,n.a.createElement(Dt,{currentScreen:e,onReset:d,onSaveFilter:m,editedFolderId:c.folderId}),function(){switch(e){case s.m.Main:return n.a.createElement(xt,{onScreenSelect:t});case s.m.EditProfile:return n.a.createElement(Vt,null);case s.m.General:return n.a.createElement(pa,{onScreenSelect:t});case s.m.Notifications:return n.a.createElement(Ra,null);case s.m.Privacy:return n.a.createElement(Da,{onScreenSelect:t});case s.m.Language:return n.a.createElement(xa,null);case s.m.GeneralChatBackground:return n.a.createElement(Pa,{onScreenSelect:t});case s.m.GeneralChatBackgroundColor:return n.a.createElement(Ta,{onScreenSelect:t});case s.m.PrivacyActiveSessions:return n.a.createElement($a,null);case s.m.PrivacyBlockedUsers:return n.a.createElement(Ha,null);case s.m.PrivacyPhoneNumber:case s.m.PrivacyLastSeen:case s.m.PrivacyProfilePhoto:case s.m.PrivacyForwarding:case s.m.PrivacyGroupChats:return n.a.createElement(Ga,{screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement(rn,{isAllowList:!0,screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement(rn,{screen:e,onScreenSelect:t});case s.m.Folders:case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement(ca,{currentScreen:e,state:c,dispatch:r,onScreenSelect:t,onReset:d});case s.m.TwoFaDisabled:case s.m.TwoFaNewPassword:case s.m.TwoFaNewPasswordConfirm:case s.m.TwoFaNewPasswordHint:case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaCongratulations:case s.m.TwoFaEnabled:case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:case s.m.TwoFaChangePasswordHint:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:case s.m.TwoFaRecoveryEmail:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(an,{currentScreen:e,state:l,dispatch:i,onScreenSelect:t});default:return}}())}return n.a.createElement(T.a,{id:"Settings",name:o.g?"slide-layers":"push-slide",activeKey:e,renderCount:sn},u)});const on=Object(_.g)(e=>e(),6e4,!0);var dn=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users;return{usersById:a,contactIds:t}},(e,t)=>Object(u.l)(t,["loadContactList","openChat"]))(({filter:e,usersById:t,contactIds:a,loadContactList:c,openChat:r})=>{Object(n.n)(()=>{on(()=>{c()})});const s=Object(n.m)(e=>{r({id:e})},[r]),l=Object(n.p)(()=>{if(!a)return;const n=e?a.filter(a=>{const n=t[a];if(!n)return!1;const c=Object(m.Z)(n);return c&&Object(me.a)(c,e)}):a;return Object(m.Eb)(n,t)},[e,t,a]),[i,d]=Object(ue.a)(void 0,l,Boolean(e));return n.a.createElement(ve.a,{items:i,onLoadMore:d,className:"chat-list custom-scroll"},i&&i.length?i.map(e=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable",onClick:()=>s(e),ripple:!o.g},n.a.createElement(Oe.a,{userId:e,forceShowSelf:!0,avatarSize:"large"}))):i&&!i.length?n.a.createElement("p",{className:"no-results",key:"no-results",dir:"auto"},e.length?"No contacts matched your search.":"Contact list is empty."):n.a.createElement(be.a,{key:"loading"}))}));const mn=Object(_.g)(e=>e(),6e4,!0);var un=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users,{byId:n}=e.chats,{currentUserId:c}=e,{query:r,fetchingStatus:s,globalResults:l,localResults:o}=e.globalSearch,{userIds:i}=l||{},{userIds:d}=o||{};return{currentUserId:c,usersById:a,chatsById:n,localContactIds:t,searchQuery:r,isSearching:s&&s.chats,globalUserIds:i,localUserIds:d}},(e,t)=>Object(u.l)(t,["loadContactList","setGlobalSearchQuery"]))(({isChannel:e,selectedMemberIds:t,onSelectedMemberIdsChange:a,onNextStep:c,onReset:r,currentUserId:s,usersById:l,chatsById:o,localContactIds:i,searchQuery:d,isSearching:h,localUserIds:b,globalUserIds:g,loadContactList:p,setGlobalSearchQuery:v})=>{Object(n.n)(()=>{mn(()=>{p()})});const E=Object(n.m)(e=>{v({query:e})},[v]),O=Object(n.p)(()=>{const e=i?Object(m.Db)(i.filter(e=>e!==s),o):[];if(!d)return e;const a=e.filter(e=>{const t=l[e];if(!t)return!1;const a=Object(m.Z)(t);return a&&Object(me.a)(a,d)});return Object(m.Db)(Object(u.o)([...a,...b||[],...g||[]]),o,!1,t)},[i,d,b,g,l,o,t,s]),f=Object(n.m)(()=>{(t.length||e)&&(v({query:""}),c())},[t.length,e,v,c]),j=Object(F.a)();return n.a.createElement("div",{className:"NewChat step-1"},n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:r,ariaLabel:"Return to Chat List"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,j("GroupAddMembers"))),n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(nn,{itemIds:O,selectedIds:t,filterValue:d,filterPlaceholder:j("SendMessageTo"),searchInputId:"new-group-picker-search",isLoading:h,onSelectedIdsChange:a,onFilterChange:E}),n.a.createElement(Gt,{isShown:Boolean(t.length||e),onClick:f,ariaLabel:e?"Continue To Channel Info":"Continue To Group Info"},n.a.createElement("i",{className:"icon-arrow-right"}))))}));var hn=Object(n.h)(Object(c.h)(e=>{const{progress:t,error:a}=e.chatCreation||{};return{creationProgress:t,creationError:a}},(e,t)=>Object(u.l)(t,["createGroupChat","createChannel"]))(({isChannel:e,memberIds:t,onReset:a,creationProgress:c,creationError:r,createGroupChat:l,createChannel:o})=>{const i=Object(F.a)(),[d,m]=Object(n.r)(""),[u,h]=Object(n.r)(""),[b,g]=Object(n.r)(),[p,v]=Object(n.r)(),E=c===s.a.InProgress,O=Object(n.m)(e=>{const{value:t}=e.currentTarget,a=t.replace(/^\s+/,"");m(a),a!==t&&(e.currentTarget.value=a)},[]),f=Object(n.m)(e=>{h(e.currentTarget.value)},[]),j=Object(n.m)(()=>{d.length?t.length>199?v("Sorry, creating supergroups is not yet supported"):l({title:d,photo:b,memberIds:t}):v("Chat title can't be empty")},[d,t,l,b,"Chat title can't be empty","Sorry, creating supergroups is not yet supported"]),C=Object(n.m)(()=>{d.length?o({title:d,about:u,photo:b,memberIds:t}):v("Channel title can't be empty")},[d,o,u,b,t,"Channel title can't be empty"]);Object(n.n)(()=>{c===s.a.Complete&&a(!0)},[c,a]);const y=r||("Chat title can't be empty"!==p&&"Channel title can't be empty"!==p?p:void 0);return n.a.createElement("div",{className:"NewChat"},n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:()=>a(),ariaLabel:"Return to member selection"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,i(e?"NewChannel":"NewGroup"))),n.a.createElement("div",{className:"NewChat-inner step-2"},n.a.createElement(Ut.a,{onChange:g,title:i("AddPhoto")}),n.a.createElement(pe.a,{value:d,onChange:O,label:i(e?"EnterChannelName":"GroupName"),error:"Chat title can't be empty"===p||"Channel title can't be empty"===p?p:void 0}),e&&n.a.createElement(n.a.Fragment,null,n.a.createElement(pe.a,{value:u,onChange:f,label:i("DescriptionOptionalPlaceholder")}),n.a.createElement("p",{className:"note"},i("DescriptionInfo"))),y&&n.a.createElement("p",{className:"error"},y),t.length>0&&n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",{className:"chat-members-heading"},i("GroupInfo.ParticipantCount",t.length,"i")),n.a.createElement("div",{className:"chat-members-list custom-scroll"},t.map(e=>n.a.createElement(Ee.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Oe.a,{userId:e})))))),n.a.createElement(Gt,{isShown:0!==d.length,onClick:e?C:j,disabled:E,ariaLabel:e?i("ChannelIntro.CreateChannel"):"Create Group"},E?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-arrow-right"})))}));a(279);const bn=Object.keys(s.d).length/2;var gn=Object(n.h)(({isChannel:e=!1,content:t,onContentChange:a,onReset:c})=>{const[r,l]=Object(n.r)([]),i=Object(n.m)(()=>{a(e?s.d.NewChannelStep2:s.d.NewGroupStep2)},[e,a]);return n.a.createElement(T.a,{id:"NewChat",name:o.g?"slide-layers":"push-slide",renderCount:bn,activeKey:t},()=>{switch(t){case s.d.NewChannelStep1:case s.d.NewGroupStep1:return n.a.createElement(un,{isChannel:e,selectedMemberIds:r,onSelectedMemberIdsChange:l,onNextStep:i,onReset:c});case s.d.NewChannelStep2:case s.d.NewGroupStep2:return n.a.createElement(hn,{isChannel:e,memberIds:r,onReset:c});default:return}})}),pn=a(189);a(280);var vn=Object(n.h)(({isActive:e,onReset:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"ArchivedChats"},n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:t,ariaLabel:"Return to chat list"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,a("ArchivedChats"))),n.a.createElement(pn.a,{folderType:"archived",noChatsText:"Archive is empty.",isActive:e}))});const En={Down:!0,ArrowDown:!0,Up:!0,ArrowUp:!0,Left:!0,ArrowLeft:!0,Right:!0,ArrowRight:!0," ":!0,PageUp:!0,PageDown:!0,End:!0,Home:!0,Tab:!0},On=e=>{e.preventDefault()};function fn(e){En[e.key]&&On(e)}function jn(){document.addEventListener("wheel",On,{passive:!1}),window.ontouchmove=On,document.onkeydown=fn}function Cn(){document.removeEventListener("wheel",On),window.ontouchmove=null,document.onkeydown=null}var yn=a(54),kn=a(153);function Nn(e,t){return e?"lng_context_copy_selected":t?"lng_context_copy_text":"Copy"}var In=a(173),Sn=a(53);a(281);var wn=({isOpen:e,message:t,anchor:a,canSendNow:c,canReschedule:s,canReply:l,canEdit:o,canPin:i,canUnpin:d,canDelete:u,canForward:h,canFaveSticker:b,canUnfaveSticker:g,canCopy:p,canCopyLink:v,canSelect:E,onReply:O,onEdit:f,onPin:C,onUnpin:y,onForward:k,onDelete:N,onFaveSticker:I,onUnfaveSticker:S,onSelect:w,onSend:P,onReschedule:M,onClose:L,onCloseAnimationEnd:A,onCopyLink:T})=>{Object(n.n)(()=>{Object(j.b)(200)},[e]);const R=function(e,t,a){const n=[],c=Object(m.O)(e),s=Object(m.G)(e),l=Object(m.D)(e,"inline"),o=s&&l&&kn.a,i=window.getSelection();if(o&&n.push({label:"lng_context_copy_image",handler:()=>{yn.b(l,r.ApiMediaFormat.BlobUrl).then(kn.b),t&&t()}}),c){const e=Boolean(i&&i.anchorNode&&i.anchorNode.parentNode&&i.anchorNode.parentNode.closest(".Message .content-inner")&&""!==i.toString().replace(/(?:\r\n|\r|\n)/g,""));n.push({label:Nn(e,o),handler:()=>{const a=e&&i?i.toString():c;Object(kn.c)(a),t&&t()}})}return a&&n.push({label:"lng_context_copy_message_link",handler:()=>{a(),t&&t()}}),n}(t,L,v?T:void 0),D=Object(n.m)(()=>document.querySelector(`.active > .MessageList div[data-message-id="${t.id}"]`),[t.id]),B=Object(n.m)(()=>document.querySelector(".active > .MessageList"),[]),x=Object(n.m)(()=>document.querySelector(".MessageContextMenu .bubble"),[]),{positionX:U,positionY:G,style:q}=Object(In.a)(a,D,B,x,10,document.querySelector(".MiddleHeader").offsetHeight),$=Object(F.a)();return n.a.createElement(Sn.a,{isOpen:e,positionX:U,positionY:G,style:q,className:"MessageContextMenu fluid",onClose:L,onCloseAnimationEnd:A},c&&n.a.createElement(z.a,{icon:"send-outline",onClick:P},$("MessageScheduleSend")),s&&n.a.createElement(z.a,{icon:"schedule",onClick:M},$("MessageScheduleEditTime")),l&&n.a.createElement(z.a,{icon:"reply",onClick:O},$("Reply")),o&&n.a.createElement(z.a,{icon:"edit",onClick:f},$("Edit")),b&&n.a.createElement(z.a,{icon:"favorite",onClick:I},$("AddToFavorites")),g&&n.a.createElement(z.a,{icon:"favorite",onClick:S},$("Stickers.RemoveFromFavorites")),p&&R.map(e=>n.a.createElement(z.a,{key:e.label,icon:"copy",onClick:e.handler},$(e.label))),i&&n.a.createElement(z.a,{icon:"pin",onClick:C},$("DialogPin")),d&&n.a.createElement(z.a,{icon:"unpin",onClick:y},$("DialogUnpin")),h&&n.a.createElement(z.a,{icon:"forward",onClick:k},$("Forward")),E&&n.a.createElement(z.a,{icon:"select",onClick:w},$("Common.Select")),u&&n.a.createElement(z.a,{destructive:!0,icon:"delete",onClick:N},$("Delete")))};var Pn=Object(n.h)(Object(c.h)((e,{message:t,messageListType:a})=>{const{threadId:n}=Object(d.y)(e)||{},{noOptions:c,canReply:r,canPin:s,canUnpin:l,canDelete:o,canEdit:i,canForward:m,canFaveSticker:u,canUnfaveSticker:h,canCopy:b,canCopyLink:g,canSelect:p}=n&&Object(d.b)(e,t,n)||{},v="pinned"===a,E="scheduled"===a;return{noOptions:c,canSendNow:E,canReschedule:E,canReply:!v&&!E&&r,canPin:!E&&s,canUnpin:!E&&l,canDelete:o,canEdit:!v&&i,canForward:!E&&m,canFaveSticker:!E&&u,canUnfaveSticker:!E&&h,canCopy:b,canCopyLink:!E&&g,canSelect:p}},(e,t)=>Object(u.l)(t,["setReplyingToId","setEditingId","pinMessage","openForwardMenu","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink"]))(({isOpen:e,messageListType:t,message:a,album:c,anchor:r,onClose:s,onCloseAnimationEnd:l,noOptions:o,canSendNow:i,canReschedule:d,canReply:m,canPin:u,canUnpin:h,canDelete:b,canEdit:g,canForward:p,canFaveSticker:v,canUnfaveSticker:E,canCopy:O,canCopyLink:f,canSelect:j,setReplyingToId:C,setEditingId:y,pinMessage:k,openForwardMenu:N,faveSticker:I,unfaveSticker:S,toggleMessageSelection:w,sendScheduledMessages:P,rescheduleMessage:M,loadMessageLink:F})=>{const{transitionClassNames:L}=Object(K.a)(e,l,void 0,!1),[A,T]=Object(n.r)(!0),[R,B]=Object(n.r)(!1),[x,U]=Object(n.r)(!1),[G,q,z]=Object(Be.a)(),$=Object(n.m)(()=>{T(!1),B(!0)},[]),H=Object(n.m)(()=>{T(!1),s()},[s]),_=Object(n.m)(()=>{B(!1),s()},[s]),V=Object(n.m)(()=>{U(!1),s()},[s]),W=Object(n.m)(()=>{z(),s()},[z,s]),Y=Object(n.m)(()=>{C({messageId:a.id}),H()},[C,a.id,H]),Z=Object(n.m)(()=>{y({messageId:a.id}),H()},[y,a.id,H]),Q=Object(n.m)(()=>{T(!1),U(!0)},[]),X=Object(n.m)(()=>{k({messageId:a.id,isUnpin:!0}),H()},[k,a.id,H]),J=Object(n.m)(()=>{if(H(),c&&c.messages){const e=c.messages.map(({id:e})=>e);N({fromChatId:a.chatId,messageIds:e})}else N({fromChatId:a.chatId,messageIds:[a.id]})},[N,a,H,c]),ee=Object(n.m)(()=>{H(),I({sticker:a.content.sticker})},[H,a.content.sticker,I]),te=Object(n.m)(()=>{H(),S({sticker:a.content.sticker})},[H,a.content.sticker,S]),ae=Object(n.m)(()=>{const e=c&&c.messages?{messageId:a.id,childMessageIds:c.messages.map(({id:e})=>e),withShift:!1}:{messageId:a.id,withShift:!1};w(e),H()},[H,a.id,w,c]),ne=Object(n.m)(()=>{P({chatId:a.chatId,id:a.id}),H()},[H,a.chatId,a.id,P]),ce=Object(n.m)(()=>{T(!1),q()},[q]),re=Object(n.m)(e=>{M({chatId:a.chatId,messageId:a.id,scheduledAt:Math.round(e.getTime()/1e3)})},[a.chatId,a.id,M]),se=Object(n.m)(()=>{F({messageId:a.id,chatId:a.chatId}),H()},[H,F,a.chatId,a.id]);if(Object(n.n)(()=>(jn(),Cn),[]),o)return void H();const le=new Date;return le.setFullYear(le.getFullYear()+1),n.a.createElement("div",{className:["ContextMenuContainer",L].join(" ")},n.a.createElement(wn,{message:a,isOpen:A,anchor:r,canSendNow:i,canReschedule:d,canReply:m,canDelete:b,canPin:u,canUnpin:h,canEdit:g,canForward:p,canFaveSticker:v,canUnfaveSticker:E,canCopy:O,canCopyLink:f,canSelect:j,onReply:Y,onEdit:Z,onPin:Q,onUnpin:X,onForward:J,onDelete:$,onFaveSticker:ee,onUnfaveSticker:te,onSelect:ae,onSend:ne,onReschedule:ce,onClose:H,onCopyLink:se}),n.a.createElement(Te,{isOpen:R,isSchedule:"scheduled"===t,onClose:_,album:c,message:a}),n.a.createElement(Re,{isOpen:x,messageId:a.id,chatId:a.chatId,onClose:V}),n.a.createElement(Ae,{isOpen:G,withTimePicker:!0,selectedAt:1e3*a.date,maxAt:Object(D.k)(le),isFutureMode:!0,onClose:W,onSubmit:re}))}));a(282);var Mn=Object(n.h)(Object(c.h)((e,{fromSticker:t})=>({stickerSet:Object(d.xb)(e,t.stickerSetId)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet","sendMessage"]))(({isOpen:e,fromSticker:t,stickerSet:a,onClose:c,loadStickers:r,toggleStickerSet:s,sendMessage:o})=>{const i=Object(n.q)(null),d=Object(F.a)(),{observe:m}=Object(ra.a)({rootRef:i,throttleMs:200,isDisabled:!e});Object(n.n)(()=>{if(e){const{stickerSetId:e,stickerSetAccessHash:a}=t;r({stickerSetId:e,stickerSetAccessHash:a})}},[e,t,r]);const u=Object(n.m)(e=>{e={...e,isPreloadedGlobally:!0},o({sticker:e}),c()},[c,o]),h=Object(n.m)(()=>{s({stickerSetId:t.stickerSetId}),c()},[t.stickerSetId,c,s]);return n.a.createElement(ge.a,{className:"StickerSetModal",isOpen:e,onClose:c,hasCloseButton:!0,title:a?a.title:d("AccDescrStickerSet")},a&&a.stickers?n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{ref:i,className:"stickers custom-scroll"},a.stickers.map(e=>n.a.createElement(ua,{sticker:e,size:l.xb,observeIntersection:m,onClick:u,clickArg:e}))),n.a.createElement("div",{className:"button-wrapper"},n.a.createElement(R.a,{size:"smaller",fluid:!0,color:a.installedDate?"danger":"primary",onClick:h},d(a.installedDate?"StickerPack.RemoveStickerCount":"StickerPack.AddStickerCount",a.count,"i")))):n.a.createElement(be.a,null))})),Fn=a(122);a(283);var Ln=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);return!a||a.isRestricted?{}:{chat:a,isMuted:a.isMuted,isPrivate:Object(m.lb)(a.id),canDeleteChat:Object(m.d)(a)}},(e,t)=>Object(u.l)(t,["updateChatMutedState","enterMessageSelectMode"]))(({chatId:e,isOpen:t,anchor:a,isChannel:c,canSubscribe:r,canSearch:s,canMute:l,canSelect:i,canLeave:d,chat:m,isPrivate:u,isMuted:h,canDeleteChat:b,onSubscribeChannel:g,onSearchClick:p,onClose:v,onCloseAnimationEnd:E,updateChatMutedState:O,enterMessageSelectMode:f})=>{const[j,C]=Object(n.r)(!0),[y,k]=Object(n.r)(!1),{x:N,y:I}=a;Object(K.a)(t,E,void 0,!1);const S=Object(n.m)(()=>{C(!1),k(!0)},[]),w=Object(n.m)(()=>{C(!1),v()},[v]),P=Object(n.m)(()=>{k(!1),v()},[v]),M=Object(n.m)(()=>{O({chatId:e,isMuted:!h}),w()},[e,w,h,O]),L=Object(n.m)(()=>{g(),w()},[w,g]),A=Object(n.m)(()=>{p(),w()},[w,p]),T=Object(n.m)(()=>{f(),w()},[w,f]);Object(n.n)(()=>(jn(),Cn),[]);const R=Object(F.a)();return n.a.createElement(Fn.a,null,n.a.createElement("div",{className:"HeaderMenuContainer"},n.a.createElement(Sn.a,{isOpen:j,positionX:"right",style:`left: ${N}px;top: ${I}px;`,onClose:w},o.g&&r&&n.a.createElement(z.a,{icon:c?"channel":"group",onClick:L},R(c?"Subscribe":"Join Group")),o.g&&s&&n.a.createElement(z.a,{icon:"search",onClick:A},R("Search")),l&&n.a.createElement(z.a,{icon:h?"unmute":"mute",onClick:M},R(h?"ChatsUnmute":"ChatsMute")),i&&n.a.createElement(z.a,{icon:"select",onClick:T},R("ReportSelectMessages")),d&&n.a.createElement(z.a,{destructive:!0,icon:"delete",onClick:S},R(u?"Delete":b?"GroupInfo.DeleteAndExit":c?"LeaveChannel":"Group.LeaveGroup"))),m&&n.a.createElement(_e.a,{isOpen:y,onClose:P,chat:m})))})),An=a(154);a(284);const Tn=Object(_.a)(e=>e(),200,!1);var Rn=Object(n.h)(Object(c.h)(e=>{const t=Object(d.r)(e);if(!t)return{};const{query:a,results:n}=Object(d.A)(e)||{},{totalCount:c,foundIds:r}=n||{};return{chat:t,query:a,totalCount:c,foundIds:r}},(e,t)=>Object(u.l)(t,["setLocalTextSearchQuery","searchTextMessagesLocal","focusMessage","closeLocalTextSearch","searchMessagesByDate"]))(({isActive:e,chat:t,query:a,totalCount:c,foundIds:r,setLocalTextSearchQuery:s,searchTextMessagesLocal:l,focusMessage:o,closeLocalTextSearch:i,searchMessagesByDate:d})=>{const m=Object(n.q)(null),[u,h]=Object(n.r)(0),[b,g,p]=Object(Be.a)();Object(n.n)(()=>{const{visualViewport:e}=window;if(!e)return;const t=document.getElementById("Main"),a=()=>{const{activeElement:a}=document;if(a&&a===m.current){const{pageTop:a,height:n}=e;t.style.transform=`translateY(${a}px)`,t.style.height=n+"px",document.documentElement.scrollTop=a}else t.style.transform="",t.style.height=""};return e.addEventListener("resize",a),()=>{e.removeEventListener("resize",a)}},[]),Object(n.n)(()=>{t&&r&&r.length?(o({chatId:t.id,messageId:r[r.length-1]}),h(0)):h(-1)},[t,o,r]),Object(n.n)(()=>{Array.from(document.querySelectorAll("input")).forEach(t=>{t.disabled=Boolean(e&&t!==m.current)}),Array.from(document.querySelectorAll("div[contenteditable]")).forEach(t=>{t.contentEditable=e?"false":"true"})},[e]),Object(n.n)(()=>{e||m.current.blur()},[e]),Object(n.o)(()=>{document.querySelector("#MobileSearch input").blur()},[b]);const v=Object(n.m)(e=>{s({query:e}),e.length&&Tn(l)},[l,s]),E=Object(n.m)(e=>{d({timestamp:e.valueOf()/1e3}),p()},[p,d]),O=Object(n.m)(()=>{if(t&&r){const e=u+1;o({chatId:t.id,messageId:r[r.length-1-e]}),h(e)}},[t,u,o,r]),f=Object(n.m)(()=>{if(t&&r){const e=u-1;o({chatId:t.id,messageId:r[r.length-1-e]}),h(e)}},[t,u,o,r]),j=Object(F.a)();return n.a.createElement("div",{id:"MobileSearch",className:e?"active":""},n.a.createElement("div",{className:"header"},n.a.createElement(R.a,{size:"smaller",round:!0,color:"translucent",onClick:i},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement(An.a,{ref:m,value:a,onChange:v})),n.a.createElement("div",{className:"footer"},n.a.createElement("div",{className:"counter"},a?r&&r.length?`${u+1} of ${c}`:r&&!r.length?"No results":"":n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:g,ariaLabel:"Search messages by date"},n.a.createElement("i",{className:"icon-calendar"}))),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:O,disabled:!r||!r.length||u===r.length-1},n.a.createElement("i",{className:"icon-up"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:f,disabled:!r||!r.length||0===u},n.a.createElement("i",{className:"icon-down"}))),n.a.createElement(Ae,{isOpen:b,isPastMode:!0,submitButtonLabel:j("JumpToDate"),onClose:p,onSubmit:E}))})),Dn=a(59),Bn=a(190),xn=a(182),Un=a(179),Gn=a(184);function qn(e,t,a=0,n=!1,c=!1,r=!1){const s=e[r?"scrollLeft":"scrollTop"],l=s+e[r?"offsetWidth":"offsetHeight"],o="string"==typeof t?e.querySelectorAll(t):t,{length:i}=o,d=[];let m=!1;for(let e=0;e=s-a&&u<=l+a:i<=l+a&&u>=s-a)d.push(e),m=!0;else if(m&&!n)break}return{allElements:o,visibleIndexes:d}}var zn=function(e,t,a=!1){const n=e[a?"scrollLeft":"scrollTop"],c=n+e[a?"offsetWidth":"offsetHeight"],r=t[a?"offsetLeft":"offsetTop"],s=r+t[a?"offsetWidth":"offsetHeight"];return r>n&&s{const l=Object(n.q)(null),{shouldRender:o,transitionClassNames:i}=Object(K.a)(e,void 0,void 0,!1),d=Object(n.m)(e=>{if(!s)return-1;const t=s.length;return Object(Hn.a)(t,e)},[s]),[m,u]=Object(n.r)(-1),h=Object(n.m)((e,t)=>{t.preventDefault(),u(t=>d(t+e))},[u,d]),b=Object(n.m)((e,t=!1)=>{const a=r&&r[e];a&&c(a,t)},[r,c]),g=Object(n.m)(e=>{if(s&&s.length&&m>-1){const t=s[m];t&&(e.preventDefault(),b(t.userId,!0))}},[s,m,b]);Object(n.n)(()=>e?Object(xe.a)({onEsc:a,onUp:e=>h(-1,e),onDown:e=>h(1,e),onEnter:g,onTab:g}):void 0,[e,a,h,g]),Object(n.n)(()=>{s&&!s.length&&a()},[s,a]),Object(n.n)(()=>{u(0)},[t]),Object(n.n)(()=>{!function(e,t){const a=t.current;if(!a||e<0)return;const{visibleIndexes:n,allElements:c}=qn(a,".chat-item-clickable",8,!0,!0);if(!c.length||!c[e])return;const r=n[0];if(!n.includes(e)||e===r&&!zn(a,c[r])){const t=e>n[n.length-1]?"start":"end";Object($n.a)(a,c[e],t,10)}}(m,l)},[m]);const p=Object(f.a)(s&&s.length?s:void 0,o),v=s&&!s.length?p:s;if(!o||v&&!v.length)return;const E=Object(ce.a)("MentionTooltip composer-tooltip custom-scroll",i);return n.a.createElement("div",{className:E,ref:l},v&&v.map(({userId:e},t)=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable scroll-item",onClick:()=>b(e),focus:m===t},n.a.createElement(Oe.a,{userId:e,avatarSize:"small",withUsername:!0}))))}),Vn=a(183);a(286);var Kn=Object(n.h)(({attachments:e,caption:t,canSuggestMembers:a,groupChatMembers:c,currentUserId:r,usersById:s,recentEmojis:o,language:i,onCaptionUpdate:d,addRecentEmoji:m,loadEmojiKeywords:u,onSend:h,onFileAppend:g,onClear:p})=>{const v=Object(n.q)(null),E=Object(f.a)(e),O=e.length?e:E,j=Boolean(e.length),[C,y,k]=Object(Be.a)(),N=O&&O.every(e=>e.quick),I=Object(F.a)(),{isMentionTooltipOpen:S,mentionFilter:w,closeMentionTooltip:P,insertMention:M,mentionFilteredMembers:L}=Object(Bn.a)(a&&j,t,d,l.w,c,r,s),{isEmojiTooltipOpen:A,closeEmojiTooltip:T,filteredEmojis:D,insertEmoji:B}=Object(xn.a)(j,t,o,l.w,d);Object(n.n)(()=>j?Object(b.a)(p):void 0,[j,p]);const x=Object(n.m)(()=>{j&&h()},[j,h]),U=Object(n.m)(e=>{e.preventDefault(),k();const{dataTransfer:{files:t}}=e;if(t&&t.length){const e=N?Array.from(t).filter(e=>e.type&&l.l.includes(e.type)):Array.from(t);g(e,!1)}},[N,g,k]);if(!O)return;const G=O.every(e=>e.mimeType.startsWith("image/")),q=O.every(e=>e.mimeType.startsWith("video/"));let z="";return z=I(G?"PreviewSender.SendPhoto":q?"PreviewSender.SendVideo":"PreviewSender.SendFile",O.length,"i"),n.a.createElement(ge.a,{isOpen:j,onClose:p,header:function(){if(O)return n.a.createElement("div",{className:"modal-header-condensed",dir:I.isRtl?"rtl":void 0},n.a.createElement(R.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel attachments",onClick:p},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},z),n.a.createElement(R.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:x},I("Send")))}(),className:"AttachmentModal "+(C?"hovered":"")},n.a.createElement("div",{className:"drop-target",onDragEnter:y,onDrop:U,onDragOver:function(e){e.preventDefault(),e.stopPropagation(),v.current&&window.clearTimeout(v.current)},onDragLeave:e=>{const{relatedTarget:t,target:a}=e;a.matches(".drop-target")&&!t&&(v.current=window.setTimeout(k,150)),a&&a.closest(".AttachmentModal.hovered")||(t&&e.stopPropagation(),k())},"data-attach-description":I("Preview.Dragging.AddItems",10)},N?n.a.createElement("div",{className:"media-wrapper custom-scroll"},O.map(e=>e.mimeType.startsWith("image/")?n.a.createElement("img",{src:e.blobUrl,alt:""}):n.a.createElement("video",{src:e.blobUrl,autoPlay:!0,muted:!0,loop:!0}))):n.a.createElement("div",{className:"document-wrapper custom-scroll"},O.map(e=>n.a.createElement(Un.a,{name:e.filename,extension:Object(Dn.d)(e.filename,e.mimeType),previewData:e.previewBlobUrl,size:e.size,smaller:!0}))),n.a.createElement("div",{className:"attachment-caption-wrapper"},n.a.createElement(_n,{isOpen:S,onClose:P,filter:w,onInsertUserName:M,filteredChatMembers:L,usersById:s}),n.a.createElement(Vn.a,{isOpen:A,emojis:D,onClose:T,language:i,onEmojiSelect:B,addRecentEmoji:m,loadEmojiKeywords:u}),n.a.createElement(Gn.a,{id:"caption-input-text",html:t,editableInputId:l.w,placeholder:I("Caption"),onUpdate:d,onSend:h,shouldSetFocus:j}))))}),Wn=a(138);a(287);var Yn=Object(n.h)(({isOpen:e,onSend:t,onClear:a})=>{const c=Object(n.q)(null),r=Object(n.q)(null),s=Object(n.q)(null),[l,o]=Object(n.r)(""),[i,d]=Object(n.r)([""]),[m,u]=Object(n.r)(!0),[h,g]=Object(n.r)(!1),[p,v]=Object(n.r)(!1),[E,O]=Object(n.r)(),[f,j]=Object(n.r)(),[C,y]=Object(n.r)(!1),k=Object(F.a)(),N=Object(n.m)(t=>{e&&t.current&&t.current.focus()},[e]);Object(n.n)(()=>e?Object(b.a)(a):void 0,[e,a]),Object(n.n)(()=>{e||(o(""),d([""]),u(!0),g(!1),v(!1),O(""),j(""),y(!1))},[e]),Object(n.n)(()=>N(c),[N,e]),Object(n.o)(()=>{const e=s.current;e&&E!==e.innerHTML&&(e.innerHTML=E)},[E]);const I=Object(n.m)((e=[])=>{d([...e,""]),requestAnimationFrame(()=>{const e=r.current;e&&(e.classList.toggle("overflown",e.scrollHeight>320),e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))})},[]),S=Object(n.m)(()=>{if(y(!1),!e)return;const a=l.trim().substring(0,255),n=i.map(e=>e.trim().substring(0,100)).filter(e=>e.length);if(!a||n.length<2)return o(a),n.length?n.length<2?I(n):d(n):I(),void y(!0);if(p&&(!f||!n[Number(f)]))return void y(!0);const c={summary:{question:a,answers:n.map((e,t)=>({text:e.trim(),option:String(t),...String(t)===f&&{correct:!0}})),...!m&&{isPublic:!0},...h&&{multipleChoice:!0},...p&&{quiz:!0}}};if(p){const{text:e,entities:t}=E&&Object(Wn.a)(E.substring(0,200))||{};c.quiz={correctAnswers:[f],...e&&{solution:e},...t&&{solutionEntities:t}}}t(c)},[e,l,i,p,f,m,h,t,I,E]),w=Object(n.m)((e,t)=>{const a=[...i];a[e]=t,a[a.length-1].trim().length&&a.length<10?I(a):d(a)},[i,I]),P=Object(n.m)(e=>{const t=[...i];t.splice(e,1),d(t),requestAnimationFrame(()=>{r.current&&r.current.classList.toggle("overflown",r.current.scrollHeight>320)})},[i]),M=Object(n.m)(e=>{j(e)},[j]),L=Object(n.m)(e=>{u(e.target.checked)},[]),A=Object(n.m)(e=>{g(e.target.checked)},[]),T=Object(n.m)(e=>{v(e.target.checked)},[]),D=Object(n.m)(e=>{13===e.keyCode&&S()},[S]),B=Object(n.m)(()=>{if(C&&!l.trim().length)return k("lng_polls_choose_question")},[C,k,l]),x=Object(n.m)(e=>{const t=i.map(e=>e.trim()).filter(e=>e.length);if(C&&t.length<2&&!i[e].trim().length)return k("lng_polls_choose_answers")},[C,k,i]);function U(){return i.map((e,t)=>n.a.createElement("div",{className:"option-wrapper"},n.a.createElement(pe.a,{label:t!==i.length-1||10===i.length?k("OptionHint"):k("CreatePoll.AddOption"),error:x(t),value:e,onChange:e=>w(t,e.currentTarget.value),onKeyPress:D}),t!==i.length-1&&n.a.createElement(R.a,{className:"option-remove-button",round:!0,color:"translucent",size:"smaller",ariaLabel:k("Delete"),onClick:()=>P(t)},n.a.createElement("i",{className:"icon-close"}))))}return n.a.createElement(ge.a,{isOpen:e,onClose:a,header:n.a.createElement("div",{className:"modal-header-condensed"},n.a.createElement(R.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel poll creation",onClick:a},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},k("NewPoll")),n.a.createElement(R.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:S},k("Create"))),className:"PollModal"},n.a.createElement(pe.a,{ref:c,label:k("AskAQuestion"),value:l,error:B(),onChange:e=>o(e.currentTarget.value),onKeyPress:D}),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"options-list custom-scroll",ref:r},n.a.createElement("h3",{className:"options-header"},"Options"),C&&function(){const e=i.map(e=>e.trim()).filter(e=>e.length);return p&&(!f||!e[Number(f)])&&n.a.createElement("p",{className:"error"},k("lng_polls_choose_correct"))}(),p?n.a.createElement(la.a,{name:"correctOption",options:U().map((e,t)=>({value:String(t),label:e,hidden:t===i.length-1})),onChange:M}):U()),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"quiz-mode"},n.a.createElement(ta.a,{label:k("PollAnonymous"),checked:m,onChange:L}),n.a.createElement(ta.a,{label:k("PollMultiple"),checked:h,disabled:p,onChange:A}),n.a.createElement(ta.a,{label:k("PollQuiz"),checked:p,disabled:h,onChange:T}),p&&n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",{className:"options-header"},"Solution"),n.a.createElement("div",{ref:s,className:"form-control",contentEditable:!0,dir:"auto",onChange:e=>O(e.currentTarget.innerHTML)}),n.a.createElement("div",{className:"note"},k("CreatePoll.ExplanationInfo")))))});let Zn;function Qn(e,t,a=250){const c=Object(n.q)(!1);Object(n.n)(()=>{Zn&&(clearTimeout(Zn),Zn=void 0),e&&!o.l&&(Zn=window.setTimeout(()=>{c.current||t()},2*a))},[e,a,t]);return[Object(n.m)(()=>{c.current=!0},[]),Object(n.m)(()=>{c.current=!1,Zn&&(clearTimeout(Zn),Zn=void 0),Zn=window.setTimeout(()=>{c.current||t()},a)},[a,t])]}var Xn=a(65),Jn=a(142);a(288);var ec=Object(n.h)(({emoji:e,focus:t,onClick:a})=>{const c=Object(n.m)(t=>{t.preventDefault(),a(e.native,e.id)},[e,a]);return n.a.createElement("div",{className:"EmojiButton "+(t?"focus":""),onMouseDown:c,title:`:${e.names[0]}:`},o.d?n.a.createElement("span",{className:"font-emoji"},e.native):n.a.createElement("img",{src:`./img-apple-64/${e.image}.png`,alt:"",loading:"lazy"}))});var tc=Object(n.h)(({category:e,index:t,allEmojis:a,observeIntersection:c,shouldRender:r,onEmojiSelect:s})=>{const l=Object(n.q)(null);Object(ra.c)(l,c);const{transitionClassNames:i}=Object(K.a)(r,void 0,void 0,"slow"),d=Object(F.a)(),m=o.g?Math.floor((y.a.get().width-8)/44):9,u=44*Math.ceil(e.emojis.length/m);return n.a.createElement("div",{ref:l,key:e.id,id:"emoji-category-"+t,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name",dir:"auto"},d("recent"===e.id?"RecentStickers":"Emoji"+t)),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",i),style:`height: ${u}px;`,dir:d.isRtl?"rtl":void 0},r&&e.emojis.map(e=>{const t=a[e],c="id"in t?t:t[1];return n.a.createElement(ec,{key:c.id,emoji:c,onClick:s})})))});a(289);const ac={recent:"icon-recent",people:"icon-smile",nature:"icon-animals",foods:"icon-eats",activity:"icon-sport",places:"icon-car",objects:"icon-lamp",symbols:"icon-language",flags:"icon-flag"},nc=[];let cc,rc,sc;var lc=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["recentEmojis"]))(({className:e,onEmojiSelect:t,recentEmojis:c})=>{const r=Object(n.q)(null),s=Object(n.q)(null),[i,d]=Object(n.r)(),[m,u]=Object(n.r)(),[h,b]=Object(n.r)(0),{observe:g}=Object(ra.a)({rootRef:r,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("emoji-category-"))return;const a=Number(t.replace("emoji-category-",""));nc[a]=e.isIntersecting});const t=nc.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&b(t[Math.floor(t.length/2)].index)});Object(Ke.a)(s,!o.g),Object(n.n)(()=>{if(!i)return;const e=s.current;if(!e)return;const t=42*h-e.offsetWidth/2+21;Object(Jn.a)(e,t)},[i,h]);const p=Object(F.a)(),v=Object(n.p)(()=>{if(!i)return ze.a;const e=[...i];return c&&c.length&&e.unshift({id:"recent",name:p("RecentStickers"),emojis:c}),e},[i,p,c]);Object(n.n)(()=>{setTimeout(()=>{const e=()=>{d(sc.categories),u(sc.emojis)};sc?e():async function(){cc||(cc=a.e(1).then(a.t.bind(null,314,3)),rc=(await cc).default,sc=Object(Xn.b)(rc));return cc}().then(e)},200)},[]);const E=Object(n.m)(e=>{b(e);const t=document.getElementById("emoji-category-"+e);Object($n.a)(r.current,t,"start",50,800)},[]),O=Object(n.m)((e,a)=>{t(e,a)},[t]),f=Object(lt.a)([],l.T);const j=Object(ce.a)("EmojiPicker",e);return m&&f?n.a.createElement("div",{className:j},n.a.createElement("div",{ref:s,className:"EmojiPicker-header",dir:p.isRtl?"rtl":""},v.map((function(e,t){const a=ac[e.id];return a&&n.a.createElement(R.a,{className:"symbol-set-button "+(t===h?"activated":""),round:!0,faded:!0,color:"translucent",onClick:()=>E(t),ariaLabel:e.name},n.a.createElement("i",{className:a}))}))),n.a.createElement("div",{ref:r,className:"EmojiPicker-main no-selection no-scrollbar"},v.map((e,t)=>n.a.createElement(tc,{category:e,index:t,allEmojis:m,observeIntersection:g,shouldRender:h>=t-1&&h<=t+1,onEmojiSelect:O})))):n.a.createElement("div",{className:j},n.a.createElement(be.a,null))}));const oc=o.g?8:16;var ic=Object(n.h)(({stickerSet:e,loadAndPlay:t,index:a,observeIntersection:c,shouldRender:r,onStickerSelect:s,onStickerUnfave:i})=>{const d=Object(n.q)(null);Object(ra.c)(d,c);const{transitionClassNames:m}=Object(K.a)(r,void 0,void 0,"slow"),u=o.g?Math.floor((y.a.get().width-8)/(l.yb+oc)):5,h=Math.ceil(e.count/u)*(l.yb+oc);return n.a.createElement("div",{ref:d,key:e.id,id:"sticker-set-"+a,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name"},e.title),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",m),style:`height: ${h}px;`},r&&e.stickers&&e.stickers.map(a=>n.a.createElement(ua,{key:a.id,sticker:a,size:l.yb,observeIntersection:c,noAnimate:!t,onClick:s,clickArg:a,onUnfaveClick:"favorite"===e.id?i:void 0}))))});a(290);const dc=[];var mc=Object(n.h)(Object(c.h)(e=>{const{setsById:t,added:a,recent:n,favorite:c}=e.stickers;return{recentStickers:n.stickers,favoriteStickers:c.stickers,stickerSetsById:t,addedSetIds:a.setIds,shouldPlay:e.settings.byKey.shouldLoopStickers}},(e,t)=>Object(u.l)(t,["loadStickerSets","loadRecentStickers","loadFavoriteStickers","loadAddedStickers","addRecentSticker","unfaveSticker"]))(({className:e,loadAndPlay:t,canSendStickers:a,recentStickers:c,favoriteStickers:r,addedSetIds:s,stickerSetsById:o,shouldPlay:i,onStickerSelect:d,loadStickerSets:m,loadRecentStickers:u,loadFavoriteStickers:h,loadAddedStickers:b,addRecentSticker:g,unfaveSticker:p})=>{const v=Object(n.q)(null),E=Object(n.q)(null),[O,f]=Object(n.r)(0),{observe:j}=Object(ra.a)({rootRef:v,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("sticker-set-"))return;const a=Number(t.replace("sticker-set-",""));dc[a]=e.isIntersecting});const t=dc.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&f(t[Math.floor(t.length/2)].index)}),{observe:C}=Object(ra.a)({rootRef:E}),y=Object(F.a)(),k=Boolean(s),N=Object(n.p)(()=>s?[{id:"recent",title:y("RecentStickers"),stickers:c,count:c.length},{id:"favorite",title:y("FavoriteStickers"),stickers:r,count:r.length},...s.map(e=>o[e]).filter(Boolean)]:ze.a,[s,y,c,r,o]),I=Object(n.p)(()=>k&&0===N.filter(e=>e.stickers&&e.stickers.length).length,[N,k]);Object(n.n)(()=>{t&&(m(),u(),h())},[t,h,u,m]),Object(n.n)(()=>{s&&s.length&&b()},[s,b]),Object(Ke.a)(E),Object(n.n)(()=>{if(!k)return;const e=E.current;if(!e)return;const t=52*O-(e.offsetWidth/2-26);Object(Jn.a)(e,t)},[k,O]);const S=Object(n.m)(e=>{f(e);const t=document.getElementById("sticker-set-"+e);Object($n.a)(v.current,t,"start",void 0,500)},[]),w=Object(n.m)(e=>{d(e),g({sticker:e})},[g,d]),P=Object(n.m)(e=>{p({sticker:e})},[p]),M=Object(lt.a)([],l.pb);const L=Object(ce.a)("StickerPicker",e);return k&&M&&!I&&a?n.a.createElement("div",{className:L},n.a.createElement("div",{ref:E,className:"StickerPicker-header no-selection no-scrollbar"},N.map((function(e,t){const a=e.stickers&&e.stickers[0],c=Object(ce.a)("symbol-set-button sticker-set-button",t===O&&"activated");return"recent"===e.id||"favorite"===e.id||e.hasThumbnail||!a?n.a.createElement(R.a,{key:e.id,className:c,ariaLabel:e.title,round:!0,faded:"recent"===e.id||"favorite"===e.id,color:"translucent",onClick:()=>S(t)},"recent"===e.id?n.a.createElement("i",{className:"icon-recent"}):"favorite"===e.id?n.a.createElement("i",{className:"icon-favorite"}):e.isAnimated?n.a.createElement(da,{stickerSet:e,observeIntersection:C}):n.a.createElement(ma,{stickerSet:e,observeIntersection:C})):n.a.createElement(ua,{key:e.id,sticker:a,size:l.zb,title:e.title,className:c,observeIntersection:C,onClick:S,clickArg:t})}))),n.a.createElement("div",{ref:v,className:"StickerPicker-main no-scrollbar"},N.map((e,a)=>n.a.createElement(ic,{key:e.id,stickerSet:e,loadAndPlay:Boolean(i&&t),index:a,observeIntersection:j,shouldRender:O>=a-1&&O<=a+1,onStickerSelect:w,onStickerUnfave:P})))):n.a.createElement("div",{className:L},a?I?n.a.createElement("div",{className:"picker-disabled"},"You have no saved Stickers."):n.a.createElement(be.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending stickers is not allowed in this chat."))}));a(291);function uc(){return(uc=Object.assign||function(e){for(var t=1;t{const s=Object(n.q)(null),l=Object(n.q)(null),o=e.thumbnail&&!!e.thumbnail.dataUri,i="gif"+e.id,d=Object(ra.b)(s,t)&&!a,m=Object(v.a)(i+"?size=m",!d,r.ApiMediaFormat.BlobUrl),u=Object(Ia.a)(e.thumbnail&&e.thumbnail.dataUri,Boolean(m)),h=Object(v.a)(i,!d,r.ApiMediaFormat.BlobUrl),b=Boolean(d&&h),{transitionClassNames:g}=Object(oa.a)(o||m||h,"slow"),{isBuffered:p,bufferingHandlers:E}=Object(W.a)(!0),O=d&&!p;Object(Z.a)(l,[b]);const f=Object(n.m)(()=>c({...e,blobUrl:h}),[c,e,h]),j=Object(ce.a)("GifButton",e.width&&e.height&&e.width({savedGifs:e.gifs.saved.gifs}),(e,t)=>Object(u.l)(t,["loadSavedGifs"]))(({className:e,loadAndPlay:t,canSendGifs:a,savedGifs:c,onGifSelect:r,loadSavedGifs:s})=>{const o=Object(n.q)(null),{observe:i}=Object(ra.a)({rootRef:o,debounceMs:300});Object(n.n)(()=>{t&&s()},[t,s]);const d=Object(lt.a)([],l.pb);return n.a.createElement("div",{ref:o,className:Object(ce.a)("GifPicker no-scrollbar",e)},a?d&&c&&c.length?c.map(e=>n.a.createElement(hc,{key:e.id,gif:e,observeIntersection:i,isDisabled:!t,onClick:r})):d&&c?n.a.createElement("div",{className:"picker-disabled"},"No saved GIFs."):n.a.createElement(be.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending GIFs is not allowed in this chat."))}));let gc;!function(e){e[e.Emoji=0]="Emoji",e[e.Stickers=1]="Stickers",e[e.GIFs=2]="GIFs"}(gc||(gc={}));const pc=Object.values(gc).filter(e=>"string"==typeof e),vc={[gc.Emoji]:"icon-smile",[gc.Stickers]:"icon-stickers",[gc.GIFs]:"icon-gifs"};var Ec=Object(n.h)(({activeTab:e,onSwitchTab:t,onRemoveSymbol:a,onSearchOpen:c})=>{const r=Object(F.a)();function s(a){return n.a.createElement(R.a,{className:"symbol-tab-button "+(e===a?"activated":""),onClick:()=>t(a),ariaLabel:pc[a],round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:vc[a]}))}const l=Object(n.m)(()=>{c(e===gc.Stickers?"stickers":"gifs")},[e,c]);return n.a.createElement("div",{className:"SymbolMenu-footer",onClick:function(e){e.stopPropagation()},dir:r.isRtl?"rtl":void 0},e!==gc.Emoji&&n.a.createElement(R.a,{className:"symbol-search-button",ariaLabel:e===gc.Stickers?"Search Stickers":"Search GIFs",round:!0,faded:!0,color:"translucent",onClick:l},n.a.createElement("i",{className:"icon-search"})),s(gc.Emoji),s(gc.Stickers),s(gc.GIFs),e===gc.Emoji&&n.a.createElement(R.a,{className:"symbol-delete-button",onClick:a,ariaLabel:"Remove Symbol",round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:"icon-delete-left"})))});a(293);let Oc=!1;var fc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onLoad:a,onClose:c,onEmojiSelect:r,onStickerSelect:s,onGifSelect:l,onRemoveSymbol:i,onSearchOpen:d,addRecentEmoji:m})=>{const[u,h]=Object(n.r)(0),[b,g]=Object(n.r)([]),[p,v]=Qn(e,c),{shouldRender:E,transitionClassNames:O}=Object(K.a)(e,c,!1,!1);!Oc&&e&&(Oc=!0),Object(n.n)(()=>{a()},[a]),Object(n.o)(()=>{if(o.g)return e&&(document.body.classList.add("enable-symbol-menu-transforms"),document.body.classList.add("is-symbol-menu-open")),()=>{e&&Object(_.b)(()=>{document.body.classList.remove("is-symbol-menu-open"),setTimeout(()=>{document.body.classList.remove("enable-symbol-menu-transforms")},350)})}},[e]);const f=Object(n.q)(b);f.current=b,Object(n.n)(()=>{f.current.length&&(f.current.forEach(e=>{m({emoji:e})}),g([]))},[e,u,m]);const j=Object(n.m)((e,t)=>{g(e=>[...e,t]),r(e)},[r]),C=Object(n.m)(e=>{c(),d(e)},[c,d]),y=Object(F.a)(),{canSendStickers:k,canSendGifs:N}=t;function I(t,a){switch(u){case gc.Emoji:return n.a.createElement(lc,{className:"picker-tab",onEmojiSelect:j});case gc.Stickers:return n.a.createElement(mc,{className:"picker-tab",loadAndPlay:!!k&&(e&&(t||a)),canSendStickers:k,onStickerSelect:s});case gc.GIFs:return n.a.createElement(bc,{className:"picker-tab",loadAndPlay:!!N&&(e&&(t||a)),canSendGifs:N,onGifSelect:l})}}const S=n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"SymbolMenu-main",onClick:function(e){e.stopPropagation()}},Oc&&n.a.createElement(T.a,{name:"slide",activeKey:u,renderCount:pc.length},I)),o.g&&n.a.createElement(R.a,{round:!0,faded:!0,color:"translucent",ariaLabel:y("Close"),className:"symbol-close-button",size:"tiny",onClick:c},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(Ec,{activeTab:u,onSwitchTab:h,onRemoveSymbol:i,onSearchOpen:C}));if(o.g){if(!E)return;const e=Object(ce.a)("SymbolMenu mobile-menu",O);return n.a.createElement(Fn.a,null,n.a.createElement("div",{className:e},S))}return n.a.createElement(Sn.a,{isOpen:e,positionX:"left",positionY:"bottom",onClose:c,className:"SymbolMenu",onCloseAnimationEnd:c,onMouseEnter:o.l?void 0:p,onMouseLeave:o.l?void 0:v,noCloseOnBackdrop:!o.l},S)});a(294);var jc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onFileSelect:a,onPollCreate:c,onClose:r})=>{const[s,i]=Qn(e,r),d=Object(n.m)((e,t)=>{const{files:n}=e.target;n&&n.length>0&&a(Array.from(n),t)},[a]),m=Object(n.m)(()=>{Ea(l.l,e=>d(e,!0))},[d]),u=Object(n.m)(()=>{Ea("*",e=>d(e,!1))},[d]),h=Object(F.a)(),{canAttachMedia:b,canAttachPolls:g}=t;return n.a.createElement(Sn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:r,className:"AttachMenu fluid",onCloseAnimationEnd:r,onMouseEnter:o.l?void 0:s,onMouseLeave:o.l?void 0:i,noCloseOnBackdrop:!o.l},!b&&n.a.createElement(z.a,{className:"media-disabled",disabled:!0},"Posting media content is not allowed in this group."),b&&n.a.createElement(n.a.Fragment,null,n.a.createElement(z.a,{icon:"photo",onClick:m},h("AttachmentMenu.PhotoOrVideo")),n.a.createElement(z.a,{icon:"document",onClick:u},h("AttachDocument"))),g&&n.a.createElement(z.a,{icon:"poll",onClick:c},h("Poll")))});a(295);var Cc=Object(n.h)(Object(c.h)(e=>{const{stickers:t}=e.stickers.forEmoji;return{stickers:t}},(e,t)=>Object(u.l)(t,["clearStickersForEmoji"]))(({isOpen:e,onStickerSelect:t,stickers:a,clearStickersForEmoji:c})=>{const r=Object(n.q)(null),{shouldRender:s,transitionClassNames:i}=Object(K.a)(e,void 0,void 0,!1),d=Object(f.a)(a,!0),m=a||d,{observe:u}=Object(ra.a)({rootRef:r,throttleMs:200});Object(n.n)(()=>e?Object(b.a)(c):void 0,[e,c]);const h=Object(ce.a)("StickerTooltip composer-tooltip custom-scroll",i,!(m&&m.length)&&"hidden");return n.a.createElement("div",{ref:r,className:h,onMouseEnter:o.l?void 0:()=>{document.body.classList.add("no-select")},onMouseLeave:o.l?void 0:()=>{document.body.classList.remove("no-select")}},s&&m?m.map(e=>n.a.createElement(ua,{key:e.id,sticker:e,size:l.yb,observeIntersection:u,onClick:t,clickArg:e})):s?n.a.createElement(be.a,null):void 0)}));a(296);var yc=Object(n.h)(Object(c.h)((e,{messageId:t})=>{const{chatId:a}=Object(d.y)(e)||{};return a?{message:Object(d.k)(e,a,t)}:{}},(e,t)=>Object(u.l)(t,["clickInlineButton"]))(({isOpen:e,message:t,onClose:a,clickInlineButton:c})=>{const[r,s]=Qn(e,a);if(t&&t.keyboardButtons)return n.a.createElement(Sn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:a,className:"KeyboardMenu",onCloseAnimationEnd:a,onMouseEnter:o.l?void 0:r,onMouseLeave:o.l?void 0:s,noCloseOnBackdrop:!o.l},n.a.createElement("div",{className:"content"},t.keyboardButtons.map(e=>n.a.createElement("div",{className:"row"},e.map(e=>n.a.createElement(R.a,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>c({button:e})},e.text))))))}));a(297);var kc=Object(n.h)(({isOpen:e,onSilentSend:t,onScheduleSend:a,onClose:c,onCloseAnimationEnd:r})=>{const[s,l]=Qn(e,c),i=Object(F.a)();return n.a.createElement(Sn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",className:"CustomSendMenu",onClose:c,onCloseAnimationEnd:r,onMouseEnter:o.l?void 0:s,onMouseLeave:o.l?void 0:l,noCloseOnBackdrop:!o.l},t&&n.a.createElement(z.a,{icon:"mute",onClick:t},i("SendWithoutSound")),a&&n.a.createElement(z.a,{icon:"schedule",onClick:a},i("ScheduleMessage")))}),Nc=a(139),Ic=a(164),Sc=a(175);a(298);var wc=Object(n.h)(({isOpen:e,language:t,emojis:a,onClose:c,onEmojiSelect:r,addRecentEmoji:s,loadEmojiKeywords:l})=>{const i=Object(n.q)(null),{shouldRender:d,transitionClassNames:m}=Object(K.a)(e,void 0,void 0,!1),u=Object(Sc.a)(a.length?a:void 0,350)||[],[h,b]=Object(n.r)(-1);Object(n.n)(()=>{l({language:t})},[l,t]),Object(n.n)(()=>{b(0)},[a]),Object(n.n)(()=>{!function(e,t){const a=t.current;if(!a)return;const{visibleIndexes:n,allElements:c}=qn(a,".EmojiButton",8,!0,!0,!0);if(!c.length||!c[e])return;const r=n[0];if(!n.includes(e)||e===r&&!zn(a,c[r],!0)){const t="start"===(e>n[n.length-1]?"start":"end")?44*e:0;Object(Jn.a)(a,t)}}(h,i)},[h]);const g=Object(n.m)(e=>{if(!a.length)return-1;const t=a.length;return Object(Hn.a)(t,e)},[a]),p=Object(n.m)((e,t)=>{t.preventDefault(),b(t=>g(t+e))},[b,g]),v=Object(n.m)(e=>{if(a.length&&h>-1){const t=a[h];t&&(e.preventDefault(),r(t.native),s({emoji:t.id}))}},[s,a,r,h]);Object(n.n)(()=>e?Object(xe.a)({onEsc:c,onLeft:e=>p(-1,e),onRight:e=>p(1,e),onEnter:v}):void 0,[p,v,e,c]);const E=Object(ce.a)("EmojiTooltip composer-tooltip custom-scroll-x",m);return n.a.createElement("div",{ref:i,className:E,onMouseEnter:o.l?void 0:()=>{document.body.classList.add("no-select")},onMouseLeave:o.l?void 0:()=>{document.body.classList.remove("no-select")}},d&&u?u.map((e,t)=>n.a.createElement(ec,{key:e.id,emoji:e,focus:h===t,onClick:r})):d?n.a.createElement(be.a,null):void 0)}),Pc=a(171);a(299);var Mc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(d.m)(e,a.id);if(!a||!n)return{};const{query:c,results:r}=Object(d.A)(e)||{},{totalCount:s,foundIds:l}=r||{};return{chat:a,messagesById:n,query:c,totalCount:s,foundIds:l}},(e,t)=>Object(u.l)(t,["searchTextMessagesLocal","focusMessage"]))(({chatId:e,threadId:t,chat:a,messagesById:r,query:s,totalCount:l,foundIds:o,searchTextMessagesLocal:i,focusMessage:h})=>{const b=Object(F.a)(),g=Object(n.p)(()=>{if(!(s&&o&&o.length&&r))return ze.a;const n=o.map(n=>{const s=r[n];if(!s)return;const l=s.senderId?Object(d.Gb)(Object(c.e)(),s.senderId):void 0;let o;if(a&&Object(m.jb)(a))o=a;else if(s.forwardInfo){const{isChannelPost:e,fromChatId:t}=s.forwardInfo;o=e&&t?Object(d.f)(Object(c.e)(),t):void 0}else o=s.senderId?Object(d.f)(Object(c.e)(),s.senderId):void 0;return{message:s,senderUser:l,senderChat:o,onClick:()=>h({chatId:e,threadId:t,messageId:n})}}).filter(Boolean);return Object(u.k)(n,({message:e})=>e.date,"desc")},[e,t,h,o,a,r,s]),p=Object(n.q)(null),v=Object(he.a)(p,!0,e=>{g&&g[e]&&g[e].onClick()},".ListItem-button",!0);return n.a.createElement(ve.a,{className:"RightSearch custom-scroll",items:g,preloadBackwards:0,onLoadMore:i,noFastList:!0,onKeyDown:v,ref:p},n.a.createElement("p",{className:"helper-text",dir:"auto"},s?0!==l&&g.length?1===l?"1 message found":(g.length&&(l||g.length))+" messages found":b("lng_search_no_results"):b("lng_dlg_search_for_messages")),g.map(({message:e,senderUser:t,senderChat:a,onClick:c})=>{const r=a?Object(m.l)(b,a):Object(m.Z)(t),l=Object(m.N)(b,e);return n.a.createElement(Ee.a,{className:"chat-item-clickable search-result-message m-0",onClick:c},n.a.createElement(x.a,{chat:a,user:t}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",{dir:"auto"},r&&Object(B.a)(r)),n.a.createElement(Pc.a,{message:e})),n.a.createElement("div",{className:"subtitle",dir:"auto"},Object(B.a)(l,["emoji","highlight"],{highlight:s}))))}))})),Fc=a(51);var Lc=Object(n.h)(Object(c.h)((e,{stickerSetId:t})=>({set:Object(d.xb)(e,t),shouldPlay:Object(d.wb)(e)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet"]))(({stickerSetId:e,observeIntersection:t,set:a,shouldPlay:c,loadStickers:r,toggleStickerSet:s,isSomeModalOpen:o,onModalToggle:i})=>{const d=Object(F.a)(),m=a&&Boolean(a.installedDate),u=Boolean(a&&a.stickers),[h,b,g]=Object(Be.a)();Object(Fc.a)(()=>{i(h)},[h,i]);const p=Object(n.p)(()=>{if(!a)return[];const e=(a.covers||[]).map(({id:e})=>e),t=a.stickers?a.stickers.filter(({id:t})=>!e.includes(t)):[];return[...a.covers||[],...t].slice(0,5)},[a]);Object(n.n)(()=>{!u&&p.length<5&&r({stickerSetId:e})},[u,p.length,r,e]);const v=Object(n.m)(()=>{s({stickerSetId:e})},[s,e]);if(!a)return;const E=p.length>0;return n.a.createElement("div",{key:a.id,className:"sticker-set",dir:d.isRtl?"rtl":void 0},n.a.createElement("div",{className:"sticker-set-header"},n.a.createElement("div",{className:"title-wrapper"},n.a.createElement("h3",{className:"title",dir:"auto"},a.title),n.a.createElement("p",{className:"count",dir:"auto"},d("Stickers",a.count,"i"))),n.a.createElement(R.a,{className:m?"is-added":void 0,color:"primary",size:"tiny",pill:!0,fluid:!0,onClick:v},d(m?"Stickers.Installed":"Stickers.Install"))),n.a.createElement("div",{className:"sticker-set-main"},!E&&n.a.createElement(L.a,null),E&&p.map(e=>n.a.createElement(ua,{sticker:e,size:l.Ab,observeIntersection:t,noAnimate:!c||h||o,onClick:b}))),E&&n.a.createElement(ba.a,{isOpen:h,fromSticker:p[0],onClose:g}))}));a(300);const Ac=Object(_.g)(e=>e(),6e4,!0);var Tc=Object(n.h)(Object(c.h)(e=>{const t=Object(d.z)(e),{query:a,resultIds:n}=t||{},{featured:c}=e.stickers;return{query:a,featuredIds:c.setIds,resultIds:n}},(e,t)=>Object(u.l)(t,["loadFeaturedStickers"]))(({query:e,featuredIds:t,resultIds:a,loadFeaturedStickers:c})=>{const r=Object(n.q)(null),s=Object(F.a)(),[l,o]=Object(n.r)(!1),{observe:i}=Object(ra.a)({rootRef:r,throttleMs:200});return Object(n.n)(()=>{Ac(()=>{c()})}),n.a.createElement("div",{ref:r,className:"StickerSearch custom-scroll",dir:s.isRtl?"rtl":void 0},function(){if(void 0!==e)return!e&&t?t.map(e=>n.a.createElement(Lc,{key:e,stickerSetId:e,observeIntersection:i,isSomeModalOpen:l,onModalToggle:o})):a?a.length?a.map(e=>n.a.createElement(Lc,{key:e,stickerSetId:e,observeIntersection:i,isSomeModalOpen:l,onModalToggle:o})):n.a.createElement("p",{className:"helper-text",dir:"auto"},"Nothing found."):n.a.createElement(be.a,null)}())}));a(301);var Rc=Object(n.h)(Object(c.h)(e=>{const t=Object(d.s)(e),{query:a,results:n}=t||{},{chatId:c}=Object(d.y)(e)||{},r=c?Object(d.f)(e,c):void 0;return{query:a,results:n,chat:r,isChatWithBot:r?Object(d.O)(e,r):void 0}},(e,t)=>Object(u.l)(t,["searchMoreGifs","sendMessage","setGifSearchQuery"]))(({query:e,results:t,chat:a,isChatWithBot:c,searchMoreGifs:r,sendMessage:s,setGifSearchQuery:l})=>{const i=Object(n.q)(null),{observe:d}=Object(ra.a)({rootRef:i,debounceMs:300}),{canSendGifs:u}=Object(m.c)(a,c),h=Object(n.m)(e=>{u&&s({gif:e}),o.l&&l({query:void 0})},[u,s,l]),b=Object(F.a)();const g=Boolean(void 0!==e&&t&&t.length);return n.a.createElement("div",{className:"GifSearch",dir:b.isRtl?"rtl":void 0},n.a.createElement(ve.a,{ref:i,className:Object(ce.a)("gif-container custom-scroll",g&&"grid"),items:t,itemSelector:".GifButton",preloadBackwards:96,noFastList:!0,onLoadMore:r},function(){if(void 0!==e)return t?t.length?t.map(e=>n.a.createElement(hc,{key:e.id,gif:e,observeIntersection:d,onClick:h})):n.a.createElement("p",{className:"helper-text",dir:"auto"},b("NoGIFsFound")):n.a.createElement(be.a,null)}()))}));a(302);var Dc=Object(n.h)(Object(c.h)((e,{answer:t})=>{const{voters:a,offsets:n}=e.pollResults;return{voters:a&&a[t.option],offset:n&&n[t.option]||""}},(e,t)=>Object(u.l)(t,["loadPollOptionResults","openChat","closePollResults"]))(({chat:e,message:t,answer:a,answerVote:c,totalVoters:r,voters:s,offset:l,loadPollOptionResults:o,openChat:i,closePollResults:d})=>{const m=Object(f.a)(c.votersCount),[u,h]=Object(n.r)(!0),b=Boolean(s),{option:g,text:p}=a,v=Object(F.a)();Object(n.n)(()=>{b&&m===c.votersCount||o({chat:e,messageId:t.id,option:g,offset:l,limit:4,shouldResetVoters:!0})},[c.votersCount,b]);const E=Object(n.m)(()=>{h(!0),o({chat:e,messageId:t.id,option:g,offset:l,limit:50})},[e,o,t.id,l,g]);Object(n.n)(()=>{h(!1)},[s]);const O=Object(n.m)(e=>{i({id:e}),d()},[d,i]);return n.a.createElement("div",{className:"PollAnswerResults"},n.a.createElement("div",{className:"poll-voters"},s?s.map(e=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable",onClick:()=>O(e)},n.a.createElement(Oe.a,{avatarSize:"tiny",userId:e,forceShowSelf:!0,noStatusOrTyping:!0}))):n.a.createElement(be.a,null),s&&function(){const e=c.votersCount-s.length;return c.votersCount>4&&e>0&&n.a.createElement(Qt,{count:e,itemName:"voter",isLoading:u,onClick:E})}()),n.a.createElement("div",{className:"answer-head",dir:v.isRtl?"rtl":void 0},n.a.createElement("span",{className:"answer-title",dir:"auto"},p),n.a.createElement("span",{className:"answer-percent",dir:v.isRtl?"auto":void 0},(j=c.votersCount,(C=r)>0?(j/C*100).toFixed():0),"%")));var j,C}));a(303);var Bc=Object(n.h)(Object(c.h)(e=>{const{pollResults:{chatId:t,messageId:a},lastSyncTime:n}=e;if(!t||!a)return{};return{chat:Object(d.f)(e,t),message:Object(d.k)(e,t,a),lastSyncTime:n}})(({chat:e,message:t,lastSyncTime:a})=>{const c=Object(F.a)();if(!t||!e)return n.a.createElement(be.a,null);const{summary:r,results:s}=Object(m.H)(t);if(!s.results)return;const l=Object(u.c)(s.results,"option");return n.a.createElement("div",{className:"PollResults",dir:c.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"poll-question",dir:"auto"},r.question),n.a.createElement("div",{className:"poll-results-list custom-scroll"},a&&r.answers.map(a=>n.a.createElement(Dc,{key:`${t.id}-${a.option}`,chat:e,message:t,answer:a,answerVote:l[a.option],totalVoters:s.totalVoters})),!a&&n.a.createElement(be.a,null)))}));a(166);var xc=Object(n.h)(Object(c.h)((e,{userId:t})=>{const a=Object(d.Gb)(e,t),n=Object(d.f)(e,t),{progress:c}=e.management;return{user:a,chat:n,progress:c}},(e,t)=>Object(u.l)(t,["updateContact","deleteUser","closeManagement","openChat","deleteHistory"]))(({userId:e,user:t,chat:a,progress:c,updateContact:r,deleteUser:l,deleteHistory:o,closeManagement:i,openChat:d})=>{const[m,u,h]=Object(Be.a)(),[b,g]=Object(n.r)(!1),[p,v]=Object(n.r)(),E=Object(F.a)(),O=t&&t.firstName||"",f=t&&t.lastName||"",j=a?a.isMuted:void 0,[C,y]=Object(n.r)(O),[k,N]=Object(n.r)(f),[I,S]=Object(n.r)(!j);Object(n.n)(()=>{S(!j)},[j]),Object(n.n)(()=>{g(!1),h()},[h,e]),Object(n.n)(()=>{y(O),N(f)},[O,f,t]),Object(n.n)(()=>{c===s.f.Complete&&(g(!1),v(void 0),h())},[h,c]);const w=Object(n.m)(e=>{y(e.target.value),g(!0)},[]),P=Object(n.m)(e=>{N(e.target.value),g(!0)},[]),M=Object(n.m)(e=>{S(e.target.checked),g(!0)},[]),A=Object(n.m)(()=>{const t=C.trim(),a=k.trim();t.length||v("Please provide first name"),r({userId:e,isMuted:!I,firstName:t,lastName:a})},[C,k,r,e,I]),T=Object(n.m)(()=>{o({chatId:a.id,shouldDeleteForAll:!1}),l({userId:e}),h(),i(),d({id:void 0})},[a.id,h,i,o,l,d,e]);if(!t)return;const R=c===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Oe.a,{userId:t.id,avatarSize:"jumbo",status:"original name",withFullInfo:!0}),n.a.createElement(pe.a,{id:"user-first-name",label:E("UserInfo.FirstNamePlaceholder"),onChange:w,value:C,error:"Please provide first name"===p?p:void 0}),n.a.createElement(pe.a,{id:"user-last-name",label:E("UserInfo.LastNamePlaceholder"),onChange:P,value:k}),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(ta.a,{checked:I,label:E("Notifications"),subLabel:E(I?"UserInfo.NotificationsEnabled":"UserInfo.NotificationsDisabled"),onChange:M}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:u},E("DeleteContact")))),n.a.createElement(Gt,{isShown:b,onClick:A,disabled:R,ariaLabel:E("Save")},R?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:m,onClose:h,text:E("AreYouSureDeleteContact"),confirmLabel:E("DeleteContact"),confirmHandler:T,confirmIsDestructive:!0}))}));var Uc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management,c=Boolean(a.fullInfo&&a.fullInfo.linkedChatId);return{chat:a,progress:n,isBasicGroup:Object(m.ib)(a),hasLinkedChannel:c,canChangeInfo:Object(m.q)(a,"changeInfo"),canBanUsers:Object(m.q)(a,"banUsers")}},(e,t)=>Object(u.l)(t,["togglePreHistoryHidden","updateChat","closeManagement","deleteHistory","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isBasicGroup:c,hasLinkedChannel:l,canChangeInfo:o,canBanUsers:i,onScreenSelect:d,togglePreHistoryHidden:u,updateChat:h,deleteHistory:b,leaveChannel:g,deleteChannel:p,closeManagement:E,openChat:O})=>{const[f,j,C]=Object(Be.a)(),y=t.title,k=t.fullInfo&&t.fullInfo.about||"",[N,I]=Object(n.r)(!1),[S,w]=Object(n.r)(y),[P,M]=Object(n.r)(k),[A,T]=Object(n.r)(),[R,D]=Object(n.r)(),x=Object(m.f)(t),U=Object(v.a)(x,!1,r.ApiMediaFormat.BlobUrl),G=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(I(!1),D(void 0))},[a]);const q=Object(n.m)(()=>{d(s.g.ChatPrivacyType)},[d]),z=Object(n.m)(()=>{d(s.g.Discussion)},[d]),$=Object(n.m)(()=>{d(s.g.GroupPermissions)},[d]),H=Object(n.m)(()=>{d(s.g.ChatAdministrators)},[d]),_=Object(n.m)(e=>{T(e),I(!0)},[]),V=Object(n.m)(e=>{w(e.target.value),I(!0)},[]),K=Object(n.m)(e=>{M(e.target.value),I(!0)},[]),W=Object(n.m)(()=>{const t=S.trim(),a=P.trim();t.length?h({chatId:e,title:t,about:a,photo:A}):D("Group title can't be empty")},[P,e,A,S,h]),Y=Object(n.m)(()=>{d(s.g.GroupMembers)},[d]),Z=Object(n.m)(()=>{if(!t.fullInfo)return;const{isPreHistoryHidden:e}=t.fullInfo;u({chatId:t.id,isEnabled:!e})},[t,u]),Q=Object(n.p)(()=>{if(!t.defaultBannedRights)return 0;let e=["sendMessages","sendMedia","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages"].filter(e=>!t.defaultBannedRights[e]).length;const{sendStickers:a,sendGifs:n}=t.defaultBannedRights;return a||n||(e+=1),e},[t]),X=t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,J=Object(n.m)(()=>{c?b({chatId:t.id,shouldDeleteForAll:!1}):t.isCreator?p({chatId:t.id}):g({chatId:t.id}),C(),E(),O({id:void 0})},[c,t.isCreator,t.id,C,E,b,g,p,O]);if(t.isRestricted)return;const ee=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ut.a,{currentAvatarBlobUrl:U,onChange:_,disabled:!o}),n.a.createElement(pe.a,{id:"group-title",label:G("GroupName"),onChange:V,value:S,error:"Group title can't be empty"===R?R:void 0,disabled:!o}),n.a.createElement(pe.a,{id:"group-about",className:"mb-2",label:G("DescriptionPlaceholder"),onChange:K,value:P,disabled:!o}),t.isCreator&&n.a.createElement(Ee.a,{icon:"lock",multiline:!0,ripple:!0,onClick:q},n.a.createElement("span",{className:"title"},G("GroupType")),n.a.createElement("span",{className:"subtitle"},t.username?G("TypePublic"):G("TypePrivate"))),l&&n.a.createElement(Ee.a,{icon:"message",multiline:!0,ripple:!0,onClick:z},n.a.createElement("span",{className:"title"},G("LinkedChannel")),n.a.createElement("span",{className:"subtitle"},G("DiscussionUnlink"))),n.a.createElement(Ee.a,{icon:"permissions",multiline:!0,ripple:!0,onClick:$,disabled:!i},n.a.createElement("span",{className:"title"},G("ChannelPermissions")),n.a.createElement("span",{className:"subtitle",dir:"auto"},Q,"/",8)),n.a.createElement(Ee.a,{icon:"admin",multiline:!0,ripple:!0,onClick:H},n.a.createElement("span",{className:"title"},G("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},Object(ia.a)(X)))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"group",multiline:!0,ripple:!0,onClick:Y},n.a.createElement("span",{className:"title"},G("GroupMembers")),n.a.createElement("span",{className:"subtitle"},Object(ia.a)(t.membersCount))),t.fullInfo&&n.a.createElement("div",{className:"ListItem narrow no-selection"},n.a.createElement(ta.a,{checked:!t.fullInfo.isPreHistoryHidden,label:G("ChatHistory"),onChange:Z,disabled:!i}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},G("DeleteMega")))),n.a.createElement(Gt,{isShown:N,onClick:W,disabled:ee,ariaLabel:G("Save")},ee?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:f,onClose:C,textParts:Object(B.a)(c||!t.isCreator?G("AreYouSureDeleteAndExit"):G("AreYouSureDeleteThisChatWithGroup",t.title),["br","simple_markdown"]),confirmLabel:c||!t.isCreator?G("DeleteMega"):G("DeleteGroupForAll"),confirmHandler:J,confirmIsDestructive:!0}))}));var Gc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t),currentUserId:e.currentUserId}),(e,t)=>Object(u.l)(t,["updateChatDefaultBannedRights"]))(({onScreenSelect:e,onChatMemberSelect:t,chat:a,currentUserId:c,updateChatDefaultBannedRights:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(F.a)(),b=Object(n.m)(()=>{e(s.g.GroupRemovedUsers)},[e]),g=Object(n.m)(()=>{e(s.g.GroupUserPermissionsCreate)},[e]),p=Object(n.m)(a=>{t(a.userId,a.promotedByUserId===c),e(s.g.GroupUserPermissions)},[c,t,e]);Object(n.n)(()=>{o(a&&a.defaultBannedRights||{}),d(!1),setTimeout(()=>{u(!1)},250)},[a]);const v=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),E=Object(n.m)(()=>{a&&(u(!0),r({chatId:a.id,bannedRights:l}))},[a,l,r]),O=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.kickedMembers?a.fullInfo.kickedMembers.length:0,[a]),f=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.members?a.fullInfo.members.filter(({bannedRights:e})=>!!e):[],[a]),j=Object(n.m)(e=>{const{bannedRights:t}=e;if(!t||!a)return;const{defaultBannedRights:n}=a;return Object.keys(t).reduce((e,a)=>{if(!t[a]||n&&n[a]||"sendInline"===a||"viewMessages"===a||"sendGames"===a)return e;const c=function(e){switch(e){case"sendMessages":return"UserRestrictionsNoSend";case"sendMedia":return"UserRestrictionsNoSendMedia";case"sendStickers":return"UserRestrictionsNoSendStickers";case"embedLinks":return"UserRestrictionsNoEmbedLinks";case"sendPolls":return"UserRestrictionsNoSendPolls";case"changeInfo":return"UserRestrictionsNoChangeInfo";case"inviteUsers":return"UserRestrictionsInviteUsers";case"pinMessages":return"UserRestrictionsPinMessages";default:return}}(a);if(!c)return e;const r=h(c);return`${e}${e.length?", "+r:r}`},"")},[a,h]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading",dir:"auto"},h("ChannelPermissionsHeader")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendMessages",checked:!l.sendMessages,label:h("UserRestrictionsSend"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendMedia",checked:!l.sendMedia,label:h("UserRestrictionsSendMedia"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:h("UserRestrictionsSendStickers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendPolls",checked:!l.sendPolls,label:h("UserRestrictionsSendPolls"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"embedLinks",checked:!l.embedLinks,label:h("UserRestrictionsEmbedLinks"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"inviteUsers",checked:!l.inviteUsers,label:h("UserRestrictionsInviteUsers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"pinMessages",checked:!l.pinMessages,label:h("UserRestrictionsPinMessages"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!l.changeInfo,label:h("UserRestrictionsChangeInfo"),blocking:!0,onChange:v}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete-user",multiline:!0,ripple:!0,narrow:!0,onClick:b},n.a.createElement("span",{className:"title"},h("ChannelBlockedUsers")),n.a.createElement("span",{className:"subtitle"},O))),n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading",dir:"auto"},h("PrivacyExceptions")),n.a.createElement(Ee.a,{icon:"add-user",ripple:!0,onClick:g},h("ChannelAddException")),f.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable exceptions-member",ripple:!0,onClick:()=>p(e)},n.a.createElement(Oe.a,{userId:e.userId,status:j(e)}))))),n.a.createElement(Gt,{isShown:i,onClick:E,ariaLabel:h("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var qc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,usersById:n}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,usersById:t,updateChatMemberBannedRights:a})=>{const c=Object(F.a)(),r=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.kickedMembers?e.fullInfo.kickedMembers:[],[e]),s=Object(n.m)(e=>{if(!e.kickedByUserId)return;const a=t[e.kickedByUserId];return a?c("UserRemovedBy",Object(m.Z)(a)):void 0},[c,t]),l=Object(n.m)(t=>{if(e)return[{title:c("Unblock"),icon:"delete",destructive:!0,handler:()=>a({chatId:e.id,userId:t.userId,bannedRights:{}})}]},[c,e,a]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",dir:c.isRtl?"rtl":void 0},n.a.createElement("p",{className:"text-muted"},c("NoBlockedGroup2")),r.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,contextActions:l(e)},n.a.createElement(Oe.a,{userId:e.userId,status:s(e)}))))))}));var zc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management;return{chat:a,progress:n,isSignaturesShown:Boolean(a&&a.isSignaturesShown),canChangeInfo:Object(m.q)(a,"changeInfo")}},(e,t)=>Object(u.l)(t,["toggleSignatures","updateChat","closeManagement","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isSignaturesShown:c,canChangeInfo:l,onScreenSelect:o,updateChat:i,toggleSignatures:d,closeManagement:u,leaveChannel:h,deleteChannel:b,openChat:g})=>{const p=t&&t.title||"",E=t&&t.fullInfo&&t.fullInfo.about||"",O=t&&t.fullInfo&&t.fullInfo.linkedChatId,[f,j,C]=Object(Be.a)(),[y,k]=Object(n.r)(!1),[N,I]=Object(n.r)(p),[S,w]=Object(n.r)(E),[P,M]=Object(n.r)(),[A,T]=Object(n.r)(),R=t&&Object(m.f)(t),D=Object(v.a)(R,!1,r.ApiMediaFormat.BlobUrl),B=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(k(!1),T(void 0))},[a]);const x=t&&t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,U=Object(n.m)(()=>{o(s.g.ChatPrivacyType)},[o]),G=Object(n.m)(()=>{o(s.g.Discussion)},[o]),q=Object(n.m)(()=>{o(s.g.ChatAdministrators)},[o]),z=Object(n.m)(e=>{M(e),k(!0)},[]),$=Object(n.m)(e=>{I(e.target.value),k(!0)},[]),H=Object(n.m)(e=>{w(e.target.value),k(!0)},[]),_=Object(n.m)(()=>{const t=N.trim(),a=S.trim();t.length?i({chatId:e,title:t,about:a,photo:P}):T("Channel title can't be empty")},[S,e,P,N,i]),V=Object(n.m)(()=>{d({chatId:e,isEnabled:!c})},[e,c,d]),K=Object(n.m)(()=>{o(s.g.ChannelSubscribers)},[o]),W=Object(n.m)(()=>{t.isCreator?b({chatId:t.id}):h({chatId:t.id}),C(),u(),g({id:void 0})},[t.isCreator,t.id,C,u,h,b,g]);if(t.isRestricted)return;const Y=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ut.a,{currentAvatarBlobUrl:D,onChange:z,disabled:!l}),n.a.createElement(pe.a,{id:"channel-title",label:B("EnterChannelName"),onChange:$,value:N,error:"Channel title can't be empty"===A?A:void 0,disabled:!l}),n.a.createElement(pe.a,{id:"channel-about",className:"mb-2",label:B("DescriptionPlaceholder"),onChange:H,value:S,disabled:!l}),t.isCreator&&n.a.createElement(Ee.a,{icon:"lock",ripple:!0,multiline:!0,onClick:U},n.a.createElement("span",{className:"title"},B("ChannelType")),n.a.createElement("span",{className:"subtitle"},t.username?B("TypePublic"):B("TypePrivate"))),n.a.createElement(Ee.a,{icon:"message",multiline:!0,ripple:!0,onClick:G,disabled:!l},n.a.createElement("span",{className:"title"},B("Discussion")),n.a.createElement("span",{className:"subtitle"},B(O?"DiscussionUnlink":"Add"))),n.a.createElement(Ee.a,{icon:"admin",multiline:!0,ripple:!0,onClick:q},n.a.createElement("span",{className:"title"},B("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},x)),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(ta.a,{checked:c,label:B("ChannelSignMessages"),onChange:V}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"group",multiline:!0,ripple:!0,onClick:K},n.a.createElement("span",{className:"title",dir:"auto"},B("ChannelSubscribers")),n.a.createElement("span",{className:"subtitle",dir:"auto"},B("Subscribers",t.membersCount,"i")))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},t.isCreator?B("ChannelDelete"):B("LeaveChannel")))),n.a.createElement(Gt,{isShown:y,onClick:_,disabled:Y,ariaLabel:B("Save")},Y?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:f,onClose:C,text:t.isCreator?B("ChannelDeleteAlert"):B("ChannelLeaveAlert"),confirmLabel:t.isCreator?B("ChannelDelete"):B("LeaveChannel"),confirmHandler:W,confirmIsDestructive:!0}))})),$c=a(57);var Hc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{isUsernameAvailable:n}=Object(d.Z)(e,t);return{chat:a,isChannel:Object(m.jb)(a),progress:e.management.progress,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["checkPublicLink","updatePublicLink","updatePrivateLink"]))(({chat:e,isChannel:t,progress:a,isUsernameAvailable:c,checkPublicLink:r,updatePublicLink:l,updatePrivateLink:o})=>{const i=Boolean(e.username),d=e.fullInfo&&e.fullInfo.inviteLink,[m,u]=Object(n.r)(i?"public":"private"),[h,b]=Object(n.r)(),[g,p,v]=Object(Be.a)(),E="public"===m&&h&&c||"private"===m&&i;Object(n.n)(()=>{m&&!d&&o()},[m,d,o]);const O=Object(n.m)(e=>{u(e)},[]),f=Object(n.m)(()=>{l({username:"public"===m?h:""})},[m,l,h]),j=Object(n.m)(()=>{v(),o()},[v,o]),C=Object(F.a)(),y=t?"Channel":"Mega",k=t?"Channel":"Group",N=[{value:"private",label:C(y+"Private"),subLabel:C(y+"PrivateInfo")},{value:"public",label:C(y+"Public"),subLabel:C(y+"PublicInfo")}],I=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",dir:C.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"section-heading"},C(k+"Type")),n.a.createElement(la.a,{selected:m,name:"channel-type",options:N,onChange:O})),"private"===m?n.a.createElement("div",{className:"section",dir:C.isRtl?"rtl":void 0},d?n.a.createElement(n.a.Fragment,null,n.a.createElement($c.a,{url:d,className:"group-link",text:d}),n.a.createElement("p",{className:"section-info",dir:C.isRtl?"rtl":void 0},C(y+"PrivateLinkHelp")),n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:p},C("RevokeLink")),n.a.createElement(we.a,{isOpen:g,onClose:v,text:C("RevokeAlert"),confirmLabel:C("RevokeButton"),confirmHandler:j,confirmIsDestructive:!0})):n.a.createElement(be.a,null)):n.a.createElement("div",{className:"section no-border"},n.a.createElement(Ht,{asLink:!0,currentUsername:e.username,isLoading:I,isUsernameAvailable:c,checkUsername:r,onChange:b}),n.a.createElement("p",{className:"section-info",dir:"auto"},C(k+".Username.CreatePublicLinkHelp")))),n.a.createElement(Gt,{isShown:E,disabled:I,ariaLabel:C("Save"),onClick:f},I?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var _c=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{forDiscussionIds:n,byId:c}=e.chats;return{chat:a,chatsByIds:c,forDiscussionIds:n,linkedChat:a&&a.fullInfo&&a.fullInfo.linkedChatId?Object(d.f)(e,a.fullInfo.linkedChatId):void 0,isChannel:a&&Object(m.jb)(a)}},(e,t)=>Object(u.l)(t,["loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup"]))(({chat:e,chatId:t,chatsByIds:a,linkedChat:c,forDiscussionIds:r,isChannel:o,onScreenSelect:i,loadGroupsForDiscussion:d,linkDiscussionGroup:m,unlinkDiscussionGroup:u})=>{const[h,b]=Object(n.r)(),[g,p]=Object(n.r)(),[v,E]=Object(n.r)(!1),O=Object(n.m)(()=>E(!0),[]),[f,j,C]=Object(Be.a)(),[y,k,N]=Object(Be.a)(),I=Object(F.a)(),S=c&&c.id;Object(n.n)(()=>{d()},[d]),Object(n.n)(()=>{g||Object(Kt.a)("DiscussionGroups").then(p)},[g]);const w=Object(n.m)(()=>{C(),u({channelId:o?t:S}),o||i(s.g.Initial)},[C,u,o,t,S,i]),P=Object(n.m)(()=>{N(),m({channelId:t,chatId:h})},[N,m,t,h]);function M(){const e=a[h];if(e)return n.a.createElement("div",{className:"modal-header"},n.a.createElement(x.a,{size:"tiny",chat:e}),n.a.createElement("div",{className:"modal-title"},I("Channel.DiscussionGroup.LinkGroup")))}function L(){const t=a[h];if(t)return t.hasPrivateLink?Object(B.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?`,["br","simple_markdown"]):Object(B.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?\n\nAnyone from the channel will be able to see messages in this group.`,["br","simple_markdown"])}return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("div",{className:"section-icon"},g&&n.a.createElement(Wt.a,{id:"discussionGroupsDucks",size:l.sb,animationData:g,play:v,noLoop:!0,onLoad:O})),c&&n.a.createElement("div",null,n.a.createElement(Ee.a,{className:"chat-item-clickable",inactive:!0},n.a.createElement(fe.a,{chatId:c.id})),n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel")),n.a.createElement(we.a,{isOpen:f,onClose:C,header:n.a.createElement("div",{className:"modal-header"},n.a.createElement(x.a,{size:"tiny",chat:c}),n.a.createElement("div",{className:"modal-title"},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"))),textParts:Object(B.a)(I(o?"DiscussionUnlinkChannelAlert":"DiscussionUnlinkGroupAlert",c.title),["br","simple_markdown"]),confirmLabel:I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"),confirmHandler:w,confirmIsDestructive:!0})),!c&&n.a.createElement("div",null,n.a.createElement("p",{className:"section-help",dir:"auto"},I("DiscussionChannelHelp")),n.a.createElement("div",{teactFastList:!0},n.a.createElement(Ee.a,{key:"create-group",icon:"group",ripple:!0,teactOrderKey:0,className:"not-implemented"},I("DiscussionCreateGroup")),r?r.map((e,t)=>n.a.createElement(Ee.a,{key:e,teactOrderKey:t+1,className:"chat-item-clickable scroll-item",onClick:()=>{b(e),k()}},n.a.createElement(fe.a,{chatId:e}))):n.a.createElement(et.a,{key:"nothing-found",teactOrderKey:0,text:"No discussion groups found"})),n.a.createElement("p",{className:"mt-4 mb-0 section-help",dir:"auto"},I("DiscussionChannelHelp2")),n.a.createElement(we.a,{isOpen:y,onClose:N,header:M(),textParts:L(),confirmLabel:I("DiscussionLinkGroup"),confirmHandler:P,isButtonsInOneRow:!0})))))}));var Vc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t);return{chat:n,isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,selectedChatMemberId:t,onScreenSelect:a,updateChatMemberBannedRights:c,isFormFullyDisabled:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),[h,b,g]=Object(Be.a)(),p=Object(F.a)(),v=Object(n.p)(()=>{if(e&&e.fullInfo&&e.fullInfo.members)return e.fullInfo.members.find(({userId:e})=>e===t)},[e,t]);Object(n.n)(()=>{e&&e.fullInfo&&t&&!v&&a(s.g.GroupPermissions)},[e,a,v,t]),Object(n.n)(()=>{o(v&&v.bannedRights||e&&e.defaultBannedRights||{}),d(!1),u(!1)},[e,v]);const E=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),O=Object(n.m)(()=>{e&&t&&(u(!0),c({chatId:e.id,userId:t,bannedRights:l}))},[e,t,l,c]),f=Object(n.m)(()=>{e&&t&&c({chatId:e.id,userId:t,bannedRights:{viewMessages:!0}})},[e,t,c]),j=Object(n.m)(t=>!!r||!(!e||!e.defaultBannedRights)&&e.defaultBannedRights[t],[e,r]);if(v)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Oe.a,{userId:v.userId})),n.a.createElement("h3",{className:"section-heading mt-4",dir:"auto"},p("UserRestrictionsCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendMessages",checked:!l.sendMessages,label:p("UserRestrictionsSend"),blocking:!0,disabled:j("sendMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendMedia",checked:!l.sendMedia,label:p("UserRestrictionsSendMedia"),blocking:!0,disabled:j("sendMedia"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:p("UserRestrictionsSendStickers"),blocking:!0,disabled:j("sendStickers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"sendPolls",checked:!l.sendPolls,label:p("UserRestrictionsSendPolls"),blocking:!0,disabled:j("sendPolls"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"embedLinks",checked:!l.embedLinks,label:p("UserRestrictionsEmbedLinks"),blocking:!0,disabled:j("embedLinks"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"inviteUsers",checked:!l.inviteUsers,label:p("UserRestrictionsInviteUsers"),blocking:!0,disabled:j("inviteUsers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"pinMessages",checked:!l.pinMessages,label:p("UserRestrictionsPinMessages"),blocking:!0,disabled:j("pinMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!l.changeInfo,label:p("UserRestrictionsChangeInfo"),blocking:!0,disabled:j("changeInfo"),onChange:E}))),!r&&n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete-user",ripple:!0,destructive:!0,onClick:b},p("UserRestrictionsBlock")))),n.a.createElement(Gt,{isShown:i,onClick:O,ariaLabel:p("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:h,onClose:g,text:"Are you sure you want to ban and remove this user from the group?",confirmLabel:"Remove",confirmHandler:f,confirmIsDestructive:!0}))}));var Kc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,currentUserId:e.currentUserId,isChannel:Object(m.jb)(a),usersById:n}})(({chat:e,isChannel:t,currentUserId:a,usersById:c,onScreenSelect:r,onChatMemberSelect:l})=>{const o=Object(F.a)();const i=Object(n.p)(()=>e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),d=Object(n.m)(e=>{l(e.userId,e.promotedByUserId===a),r(s.g.ChatAdminRights)},[a,l,r]),u=Object(n.m)(e=>{if(e.isOwner)return o("ChannelCreator");const t=e.promotedByUserId?c[e.promotedByUserId]:void 0;return t?o("EditAdminPromotedBy",Object(m.Z)(t)):o("ChannelAdmin")},[o,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"recent",multiline:!0,ripple:!0,onClick:function(){r(s.g.GroupRecentActions)}},n.a.createElement("span",{className:"title"},o("EventLog")),n.a.createElement("span",{className:"subtitle"},o(t?"EventLogInfoDetailChannel":"EventLogInfoDetail")))),n.a.createElement("div",{className:"section",dir:o.isRtl?"rtl":void 0},n.a.createElement("p",{className:"text-muted",dir:"auto"},t?"You can add administrators to help you manage your channel.":"You can add administrators to help you manage your group."),i.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,onClick:()=>d(e)},n.a.createElement(Oe.a,{userId:e.userId,status:u(e),forceShowSelf:!0}))))))}));var Wc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t)}))(({chat:e})=>{const t=Object(F.a)(),a=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),c=Object(n.m)(e=>e.isOwner?t("ChannelCreator"):t("ChannelAdmin"),[t]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section not-implemented",dir:t.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"section-heading",dir:"auto"},"Actions"),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogAllEvents"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewAdmins"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewMembers"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterChannelInfo"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterDeletedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterEditedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterLeavingMembers"),onChange:void 0}))),n.a.createElement("div",{className:"section not-implemented",dir:t.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"section-heading",dir:"auto"},t("Channel.Management.Title")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!0,label:t("EventLogAllAdmins"),onChange:void 0})),a.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable picker-list-item",onClick:void 0,ripple:!0},n.a.createElement(ta.a,{label:"",checked:!0}),n.a.createElement(Oe.a,{userId:e.userId,status:c(e),forceShowSelf:!0}))))))}));var Yc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t),{byId:c}=e.users,{currentUserId:r}=e;return{chat:n,usersById:c,currentUserId:r,isChannel:Object(m.jb)(n),isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatAdmin"]))(({selectedChatMemberId:e,onScreenSelect:t,chat:a,usersById:c,currentUserId:r,isChannel:l,isFormFullyDisabled:o,updateChatAdmin:i})=>{const[d,u]=Object(n.r)({}),[h,b]=Object(n.r)(!1),[g,p]=Object(n.r)(!1),[v,E,O]=Object(Be.a)(),[f,j]=Object(n.r)(""),C=Object(F.a)(),y=Object(n.p)(()=>{if(a.fullInfo&&a.fullInfo.adminMembers)return a.fullInfo.adminMembers.find(({userId:t})=>t===e)},[a,e]);Object(n.n)(()=>{a&&a.fullInfo&&e&&!y&&t(s.g.ChatAdministrators)},[a,t,y,e]),Object(n.n)(()=>{u(y&&y.adminRights||{}),j((y&&y.customTitle||"").substr(0,16)),b(!1),p(!1)},[y]);const k=Object(n.m)(e=>{const{name:t}=e.target;u(e=>{return{...e,[t]:(a=e[t],!a||void 0)};var a}),b(!0)},[]),N=Object(n.m)(()=>{e&&(p(!0),i({chatId:a.id,userId:e,adminRights:d,customTitle:f}))},[a,e,d,f,i]),I=Object(n.m)(()=>{e&&(i({chatId:a.id,userId:e,adminRights:{}}),O())},[a.id,O,e,i]),S=Object(n.m)(e=>!Object(m.ib)(a)&&(!(!o&&a.adminRights)||!a.adminRights[e]),[a,o]),w=Object(n.p)(()=>{if(!y)return;if(y.isOwner)return C("ChannelCreator");const e=y.promotedByUserId?c[y.promotedByUserId]:void 0;return e?C("EditAdminPromotedBy",Object(m.Z)(e)):C("ChannelAdmin")},[y,c,C]),P=Object(n.m)(e=>{const{value:t}=e.target;j(t),b(!0)},[]);if(y)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Oe.a,{userId:y.userId,status:w,forceShowSelf:!0})),n.a.createElement("h3",{className:"section-heading mt-4",dir:"auto"},C("EditAdminWhatCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"changeInfo",checked:!!d.changeInfo,label:C(l?"EditAdminChangeChannelInfo":"EditAdminChangeGroupInfo"),blocking:!0,disabled:S("changeInfo"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"postMessages",checked:!!d.postMessages,label:C("EditAdminPostMessages"),blocking:!0,disabled:S("postMessages"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"editMessages",checked:!!d.editMessages,label:C("EditAdminEditMessages"),blocking:!0,disabled:S("editMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"deleteMessages",checked:!!d.deleteMessages,label:C(l?"EditAdminDeleteMessages":"EditAdminGroupDeleteMessages"),blocking:!0,disabled:S("deleteMessages"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"banUsers",checked:!!d.banUsers,label:C("EditAdminBanUsers"),blocking:!0,disabled:S("banUsers"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"inviteUsers",checked:!!d.inviteUsers,label:C("EditAdminAddUsers"),blocking:!0,disabled:S("inviteUsers"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"pinMessages",checked:!!d.pinMessages,label:C("EditAdminPinMessages"),blocking:!0,disabled:S("pinMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"addAdmins",checked:!!d.addAdmins,label:C("EditAdminAddAdmins"),blocking:!0,disabled:S("addAdmins"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(ta.a,{name:"anonymous",checked:!!d.anonymous,label:C("EditAdminSendAnonymously"),blocking:!0,disabled:S("anonymous"),onChange:k})),o&&n.a.createElement("p",{className:"section-info mb-4",dir:"auto"},C("Channel.EditAdmin.CannotEdit")),!l&&n.a.createElement(pe.a,{id:"admin-title",label:C("EditAdminRank"),onChange:P,value:f,disabled:o,maxLength:16}),r!==e&&!o&&n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:E},C("EditAdminRemoveAdmin")))),n.a.createElement(Gt,{isShown:h,onClick:N,ariaLabel:C("Save"),disabled:g},g?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:v,onClose:O,text:"Are you sure you want to dismiss this admin?",confirmLabel:"Dismiss",confirmHandler:I,confirmIsDestructive:!0}))}));var Zc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.jb)(a)}},(e,t)=>Object(u.l)(t,["openUserInfo"]))(({members:e,usersById:t,isChannel:a,openUserInfo:c})=>{const r=Object(n.p)(()=>{if(e&&t)return Object(m.Eb)(e.map(({userId:e})=>e),t)},[e,t]),s=Object(n.m)(e=>{c({id:e})},[c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},r?r.map((e,t)=>n.a.createElement(Ee.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>s(e)},n.a.createElement(Oe.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(et.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var Qc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.jb)(a)}})(({usersById:e,members:t,isChannel:a,onScreenSelect:c,onChatMemberSelect:r})=>{const l=Object(n.p)(()=>{if(t&&e)return Object(m.Eb)(t.filter(e=>!e.isOwner).map(({userId:e})=>e),e)},[t,e]),o=Object(n.m)(e=>{r(e),c(s.g.GroupUserPermissions)},[r,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},l?l.map((e,t)=>n.a.createElement(Ee.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>o(e)},n.a.createElement(Oe.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(et.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var Xc=Object(n.h)(Object(c.h)(e=>({managementType:Object(d.u)(e)}))(({chatId:e,currentScreen:t,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r,onChatMemberSelect:l,managementType:o})=>{switch(t){case s.g.Initial:switch(o){case"user":return n.a.createElement(xc,{key:e,userId:e});case"group":return n.a.createElement(Uc,{key:e,chatId:e,onScreenSelect:r});case"channel":return n.a.createElement(zc,{key:e,chatId:e,onScreenSelect:r})}break;case s.g.ChatPrivacyType:return n.a.createElement(Hc,{chatId:e});case s.g.Discussion:return n.a.createElement(_c,{chatId:e,onScreenSelect:r});case s.g.GroupPermissions:return n.a.createElement(Gc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRemovedUsers:return n.a.createElement(qc,{chatId:e});case s.g.GroupUserPermissionsCreate:return n.a.createElement(Qc,{chatId:e,onChatMemberSelect:l,onScreenSelect:r});case s.g.GroupUserPermissions:return n.a.createElement(Vc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChatAdministrators:return n.a.createElement(Kc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRecentActions:return n.a.createElement(Wc,{chatId:e});case s.g.ChatAdminRights:return n.a.createElement(Yc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChannelSubscribers:case s.g.GroupMembers:return n.a.createElement(Zc,{chatId:e})}}));const Jc={USD:"$",EUR:"€",GBP:"£",JPY:"¥",RUB:"₽",UAH:"₴",INR:"₹",AED:"د.إ"};function er(e){return e&&Jc[e]||""}const tr=/^4[0-9]{12}(?:[0-9]{1,3})?$/,ar=/^5[1-5][0-9]{11,14}$/,nr=/^2[2-7][0-9]{11,14}$/;let cr;!function(e){e[e.Default=0]="Default",e[e.Visa=1]="Visa",e[e.Mastercard=2]="Mastercard"}(cr||(cr={}));const rr={[cr.Default]:"",[cr.Visa]:"visa",[cr.Mastercard]:"mastercard"};function sr(e){return e=e.replace(/\s/g,""),tr.test(e)?cr.Visa:ar.test(e)||nr.test(e)?cr.Mastercard:cr.Default}var lr=a(60);const or={streetLine1:"",streetLine2:"",city:"",state:"",countryIso2:"",postCode:"",fullName:"",email:"",phone:"",shipping:"",cardNumber:"",cardholder:"",expiry:"",cvv:"",billingCountry:"",billingZip:"",saveInfo:!0,saveCredentials:!1,formErrors:{}},ir=(e,t)=>{switch(t.type){case"changeAddress1":return{...e,streetLine1:t.payload,formErrors:{...e.formErrors,streetLine1:void 0}};case"changeAddress2":return{...e,streetLine2:t.payload,formErrors:{...e.formErrors,streetLine2:void 0}};case"changeCity":return{...e,city:t.payload,formErrors:{...e.formErrors,city:void 0}};case"changeState":return{...e,state:t.payload,formErrors:{...e.formErrors,state:void 0}};case"changeCountry":return{...e,countryIso2:t.payload,billingCountry:dr(t.payload),formErrors:{...e.formErrors,countryIso2:void 0}};case"changePostCode":return{...e,postCode:t.payload,formErrors:{...e.formErrors,postCode:void 0}};case"changeFullName":return{...e,fullName:t.payload,formErrors:{...e.formErrors,fullName:void 0}};case"changeEmail":return{...e,email:t.payload,formErrors:{...e.formErrors,email:void 0}};case"changePhone":return{...e,phone:t.payload,formErrors:{...e.formErrors,phone:void 0}};case"changeShipping":return{...e,shipping:t.payload};case"changeCardNumber":return{...e,cardNumber:t.payload,formErrors:{...e.formErrors,cardNumber:void 0}};case"changeCardholder":return{...e,cardholder:t.payload,formErrors:{...e.formErrors,cardholder:void 0}};case"changeExpiryDate":return{...e,expiry:t.payload,formErrors:{...e.formErrors,expiry:void 0}};case"changeCvvCode":return{...e,cvv:t.payload,formErrors:{...e.formErrors,cvv:void 0}};case"changeBillingCountry":return{...e,billingCountry:t.payload,formErrors:{...e.formErrors,billingCountry:void 0}};case"changeBillingZip":return{...e,billingZip:t.payload,formErrors:{...e.formErrors,billingZip:void 0}};case"changeSaveInfo":return{...e,saveInfo:t.payload};case"changeSaveCredentials":return{...e,saveCredentials:t.payload};case"updateUserInfo":return t.payload.countryIso2?{...e,...t.payload,billingCountry:dr(t.payload.countryIso2)}:{...e,...t.payload};case"setFormErrors":return{...e,formErrors:{...e.formErrors,...t.payload}};default:return e}};function dr(e){const t=Bt.a.find(({id:t})=>t===e);return t?t.name:""}function mr(e,t=400){Object(n.n)(()=>{o.l||setTimeout(()=>{Object(_.b)(()=>{e.current&&e.current.focus()})},t)},[e,t])}var ur=Object(n.h)(e=>{const{id:t,value:a,label:c,hasArrow:r,error:s,ref:l,placeholder:o,onChange:i,children:d}=e,m=s||c,u=Object(ce.a)("input-group",a&&"touched",s&&"error",m&&"with-label",r&&"with-arrow","input-group");return n.a.createElement("div",{className:u},n.a.createElement("select",{className:"form-control",id:t,value:a||"",onChange:i,placeholder:o||c,ref:l},d),m&&t&&n.a.createElement("label",{htmlFor:t},m))});a(304);var hr=Object(n.h)(({state:e,needEmail:t,needPhone:a,needName:c,needAddress:r,dispatch:s})=>{const l=Object(n.q)(null),o=Object(n.q)(null),i=Object(n.q)(null);Object(n.n)(()=>{i.current&&i.current.value!==e.countryIso2&&(i.current.value=e.countryIso2)},[e.countryIso2]);const d=Object(F.a)();mr(l);const m=Object(n.m)(e=>{s({type:"changeAddress1",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeAddress2",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeCity",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeState",payload:e.target.value})},[s]),g=Object(n.m)(e=>{s({type:"changeCountry",payload:e.target.value})},[s]),p=Object(n.m)(e=>{s({type:"changePostCode",payload:e.target.value})},[s]),v=Object(n.m)(e=>{s({type:"changeFullName",payload:e.target.value})},[s]),E=Object(n.m)(e=>{s({type:"changeEmail",payload:e.target.value})},[s]),O=Object(n.m)(e=>{let{value:t}=e.target;t="+"+t.replace(/\D/g,""),o.current&&(o.current.value=t),s({type:"changePhone",payload:t})},[s]),f=Object(n.m)(e=>{s({type:"changeSaveInfo",payload:e.target.value})},[s]),{formErrors:j}=e;return n.a.createElement("div",{className:"ShippingInfo"},n.a.createElement("form",null,r?n.a.createElement("div",null,n.a.createElement("h5",null,d("PaymentShippingAddress")),n.a.createElement(pe.a,{ref:l,label:"Address1 (Street)",onChange:m,value:e.streetLine1,inputMode:"text",error:j.streetLine1}),n.a.createElement(pe.a,{label:"Address2 (Street)",onChange:u,value:e.streetLine2,inputMode:"text",error:j.streetLine2}),n.a.createElement(pe.a,{label:"City",onChange:h,value:e.city,inputMode:"text",error:j.city}),n.a.createElement(pe.a,{label:"State",onChange:b,value:e.state,inputMode:"text",error:j.state}),n.a.createElement(ur,{label:"Country",placeholder:"Country",onChange:g,value:e.countryIso2,hasArrow:Boolean(!0),id:"shipping-country",error:j.countryIso2,ref:i},Bt.a.map(({name:e,id:t})=>n.a.createElement("option",{value:t,className:"county-item"},e))),n.a.createElement(pe.a,{label:"Post Code",onChange:p,value:e.postCode,inputMode:"text",error:j.postCode})):void 0,c||t||a?n.a.createElement("h5",null,d("PaymentShippingReceiver")):void 0,c&&n.a.createElement(pe.a,{label:"Full name",onChange:v,value:e.fullName,inputMode:"text",error:j.fullName}),t&&n.a.createElement(pe.a,{label:"Email",onChange:E,value:e.email,inputMode:"email",error:j.email}),a&&n.a.createElement(pe.a,{label:"Phone number",onChange:O,value:e.phone,inputMode:"tel",error:j.phone,ref:o}),n.a.createElement(ta.a,{label:d("PaymentShippingSave"),subLabel:d("PaymentShippingSaveInfo"),checked:Boolean(e.saveInfo),onChange:f})))});a(305);var br=Object(n.h)(({state:e,shippingOptions:t,currency:a,dispatch:c})=>{Object(n.n)(()=>{t&&!e.shipping&&c({type:"changeShipping",payload:t[0].id})},[t,e.shipping,c]);const r=Object(n.m)(e=>{c({type:"changeShipping",payload:e})},[c]),s=Object(n.p)(()=>t.map(({id:e,title:t,amount:n})=>({label:t,subLabel:`${a} ${String(n/100)}`,value:e})),[t,a]);return n.a.createElement("div",{className:"Shipping"},n.a.createElement("form",null,n.a.createElement("p",null,"Select shipping method"),n.a.createElement(la.a,{name:"shipping-options",options:s,onChange:r,selected:e.shipping})))});a(306);function gr(e,t,a,c=!1){return n.a.createElement("div",{className:"price-info-item "+(c?"price-info-item-main":"")},n.a.createElement("div",{className:"title"},e),n.a.createElement("div",{className:"value"},`${a||""} ${(t/100).toFixed(2)}`))}function pr(e,t,a){return n.a.createElement("div",{className:"checkout-info-item"},n.a.createElement("i",{className:e}," "),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},t),n.a.createElement("p",{className:"data"},a)))}var vr=Object(n.h)(({invoiceContent:e,prices:t,shippingPrices:a,checkoutInfo:c,currency:r,totalPrice:s})=>{const{photoUrl:l,title:o,text:i}=e||{},{paymentMethod:d,paymentProvider:m,shippingAddress:u,name:h,phone:b,shippingMethod:g}=c||{};return n.a.createElement("div",{className:"Checkout"},n.a.createElement("div",{className:"description has-image"},l&&n.a.createElement("img",{src:l,alt:""}),n.a.createElement("div",{className:"text"},n.a.createElement("h5",null,o),n.a.createElement("p",null,i))),n.a.createElement("div",{className:"price-info"},t&&t.map(e=>gr(e.label,e.amount,r,!1)),a&&a.map(e=>gr(e.label,e.amount,r,!1)),void 0!==s&&gr("Total",s,r,!0)),n.a.createElement("div",{className:"invoice-info"},d&&pr("icon-card",d,"Payment method"),m&&pr("stripe-provider",m,"Payment provider"),u&&pr("icon-location",u,"Shipping address"),h&&pr("icon-user",h,"Name"),b&&pr("icon-phone",b,"Phone number"),g&&pr("icon-truck",g,"Shipping method")))});var Er=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null),r=Object(n.m)(t=>{if("Backspace"===t.key&&"/"===e.charAt(e.length-1)){const t=e.slice(0,e.length-1);c.current&&(c.current.value=t)}},[e]),s=Object(n.m)(e=>{a(function(e){const t=(e=e.replace(/[^\d]/g,"").slice(0,4)).match(/.{1,2}/g);return t&&t[0]&&Number(t[0])>12&&(t[0]="12"),t&&t[0]&&2===t[0].length&&!t[1]&&(t[1]=""),t?t.join("/"):""}(e.target.value))},[a]);return n.a.createElement(pe.a,{label:"Expiry date",ref:c,onChange:s,onKeyDown:r,value:e,error:t,inputMode:"numeric",maxLength:5})}),Or=(a(307),a.p+"mastercard.4216118edafe23cc2dec7b8807ba4622.svg"),fr=a.p+"visa.e5a7c336e1deb4b92a636e2e053878c4.svg";var jr=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null);mr(c);const[r,s]=Object(n.r)(cr.Default);Object(n.n)(()=>{const t=sr(e);s(t)},[]);const l=Object(n.m)(e=>{const t=function(e){const t=(e=e.replace(/[^\d]/g,"")).match(/.{1,4}/g);return t?t.join(" "):""}(e.target.value),n=sr(e.target.value);s(n),a(t),c.current&&(c.current.value=t)},[a,c]),o=function(e){switch(e){case cr.Mastercard:return n.a.createElement("img",{src:Or,alt:""});case cr.Visa:return n.a.createElement("img",{src:fr,alt:""});default:return}}(r);return n.a.createElement("div",{className:"CardInput"},n.a.createElement("span",{className:"left-addon"},o),n.a.createElement(pe.a,{ref:c,label:"Card number",onChange:l,value:e,inputMode:"numeric",className:r?"has-left-addon":"",error:t,maxLength:23}))});a(308);var Cr=Object(n.h)(({state:e,canSaveCredentials:t,needCardholderName:a,needCountry:c,needZip:r,dispatch:s})=>{const l=Object(n.q)(null);Object(n.n)(()=>{l.current&&l.current.value!==e.billingCountry&&(l.current.value=e.billingCountry)},[e.billingCountry]);const o=Object(n.m)(e=>{s({type:"changeCardNumber",payload:e})},[s]),i=Object(n.m)(e=>{s({type:"changeCardholder",payload:e.target.value.toUpperCase()})},[s]),d=Object(n.m)(e=>{s({type:"changeExpiryDate",payload:e})},[s]),m=Object(n.m)(e=>{s({type:"changeCvvCode",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeBillingCountry",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeBillingZip",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeSaveCredentials",payload:e.target.value})},[s]),g=Object(F.a)(),{formErrors:p={}}=e;return n.a.createElement("div",{className:"PaymentInfo"},n.a.createElement("form",null,n.a.createElement("h5",null,g("PaymentCardTitle")),n.a.createElement(jr,{onChange:o,value:e.cardNumber,error:p.cardNumber}),a&&n.a.createElement(pe.a,{label:"Name on card",onChange:i,value:e.cardholder,inputMode:"text",error:p.cardholder}),n.a.createElement("section",{className:"inline-inputs"},n.a.createElement(Er,{value:e.expiry,onChange:d,error:p.expiry}),n.a.createElement(pe.a,{label:"CVV code",onChange:m,value:e.cvv,inputMode:"numeric",maxLength:3,error:p.cvv})),c||r?n.a.createElement("h5",null,g("PaymentBillingAddress")):void 0,c&&n.a.createElement(ur,{label:"Country",placeholder:"Country",onChange:u,value:e.billingCountry,hasArrow:Boolean(!0),id:"billing-country",error:p.billingCountry,ref:l},Bt.a.map(({name:e})=>n.a.createElement("option",{value:e,className:"county-item"},e))),r&&n.a.createElement(pe.a,{label:"Post Code",onChange:h,value:e.billingZip,inputMode:"text",error:p.billingZip}),t&&n.a.createElement(ta.a,{label:g("PaymentCardSavePaymentInformation"),checked:e.saveCredentials,onChange:b})))});a(187);var yr=Object(n.h)(Object(c.h)(e=>{const{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,invoice:r,invoiceContent:s,nativeProvider:l,nativeParams:o,passwordMissing:i,error:d}=e.payment,m=Boolean(r&&(!l||"stripe"!==l)),{needCardholderName:u,needCountry:h,needZip:b}=o||{},{nameRequested:g,phoneRequested:p,emailRequested:v,shippingAddressRequested:E,flexible:O,phoneToProvider:f,emailToProvider:j,currency:C,prices:y}=r||{};return{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,nativeProvider:l,passwordMissing:i,nameRequested:g,shippingAddressRequested:E,phoneRequested:p,emailRequested:v,flexible:O,phoneToProvider:f,emailToProvider:j,currency:C,prices:y,isProviderError:m,invoiceContent:s,needCardholderName:u,needCountry:h,needZip:b,error:d,globalErrors:e.errors}},(e,t)=>Object(u.l)(t,["validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError"]))(({isOpen:e,onClose:t,step:a,shippingOptions:c,savedInfo:r,canSaveCredentials:l,nameRequested:o,shippingAddressRequested:i,phoneRequested:d,emailRequested:m,phoneToProvider:u,emailToProvider:h,currency:b,passwordMissing:g,isProviderError:p,invoiceContent:v,nativeProvider:E,prices:O,needCardholderName:f,needCountry:j,needZip:C,error:y,globalErrors:k,validateRequestedInfo:N,sendPaymentForm:I,setPaymentStep:S,sendCredentialsInfo:w,clearPaymentError:P})=>{const[M,A]=Nt(ir,or),D=er(b),[B,x]=Object(n.r)(!1),U=Object(F.a)();Object(n.n)(()=>{(a||y||k)&&x(!1)},[a,y,k]),Object(n.n)(()=>{if(y&&y.field)A({type:"setFormErrors",payload:{[y.field]:y.fieldError}});else if(k&&k.length){const e=Object(lr.a)(k);A({type:"setFormErrors",payload:{...e}})}},[y,k,A]),Object(n.n)(()=>{if(r){const{name:e,phone:t,email:a,shippingAddress:n}=r;A({type:"updateUserInfo",payload:{fullName:e,phone:t&&"+"!==t.charAt(0)?"+"+t:t,email:a,...n||{}}})}},[r,A]);const G=Object(n.m)(()=>{P()},[P]),q=Object(n.p)(()=>a!==s.i.Checkout?0:function(e=[],t,a){const n=t?Nr(t,a):[];let c=0;const r=e.concat(n||[]);return c=r.reduce((e,t)=>e+t.amount,c),c}(O,c,M.shipping),[a,M.shipping,O,c]),z=Object(n.p)(()=>{if(a===s.i.Checkout)return function(e,t,a){const n=`${function(e){const t=sr(e);return rr[t]||""}(e.cardNumber)} *${e.cardNumber.slice(-4)}`,c=e.streetLine1?`${e.streetLine1}, ${e.city}, ${e.countryIso2}`:void 0,{phone:r,fullName:s}=e,l=t?kr(t,e.shipping):void 0,o=l?l.title:void 0;return{paymentMethod:n,paymentProvider:a,shippingAddress:c,name:s,phone:r,shippingMethod:o}}(M,c,E||"")},[a,M,c,E]);const $=Object(n.m)(()=>{const{saveInfo:e}=M,t=function(e){const{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s,fullName:l,phone:o,email:i}=e;return{name:l,phone:o,email:i,shippingAddress:{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s}}}(M);N({requestInfo:t,saveInfo:e})},[N,M]),H=Object(n.m)(()=>{const e=function(e){const{cardNumber:t,cardholder:a,expiry:n,cvv:c,billingCountry:r,billingZip:s}=e,[l,o]=n.split("/");return{data:{cardNumber:t,cardholder:a,expiryMonth:l,expiryYear:o,cvv:c,country:r,zip:s}}}(M);w({credentials:e})},[w,M]),_=Object(n.m)(()=>{I({shippingOptionId:M.shipping,saveCredentials:M.saveCredentials})},[I,M]),V=Object(n.m)(e=>{S({step:e})},[S]),K=Object(n.m)(()=>{switch(x(!0),a){case s.i.ShippingInfo:return $();case s.i.Shipping:return V(s.i.PaymentInfo);case s.i.PaymentInfo:return H();case s.i.Checkout:return _();default:return()=>{}}},[a,$,V,H,_]),W=Object(n.p)(()=>{switch(a){case s.i.ShippingInfo:return U("PaymentShippingInfo");case s.i.Shipping:return U("PaymentShippingMethod");case s.i.PaymentInfo:return U("PaymentCardInfo");case s.i.Checkout:return U("PaymentCheckout");default:return""}},[a,U]),Y=Object(n.p)(()=>{switch(a){case s.i.Checkout:return U("Checkout.PayPrice",`${D}${(q/100).toFixed(2)}`);default:return U("Next")}},[a,U,D,q]);return p?n.a.createElement(ge.a,{className:"error",isOpen:e,onClose:t},n.a.createElement("p",null,"Sorry, Telegram T doesn't support payments with this provider yet. ",n.a.createElement("br",null),"Please use one of our mobile apps to do this."),n.a.createElement(R.a,{isText:!0,onClick:t},U("OK"))):n.a.createElement(ge.a,{className:"PaymentModal",isOpen:e,onClose:t},n.a.createElement("div",{className:"header",dir:U.isRtl?"rtl":void 0},n.a.createElement(R.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null,W)),void 0!==a?n.a.createElement(T.a,{name:"slide",activeKey:a},()=>n.a.createElement("div",{className:"content custom-scroll"},function(e){switch(e){case s.i.ShippingInfo:return n.a.createElement(hr,{state:M,dispatch:A,needAddress:Boolean(i),needEmail:Boolean(m||h),needPhone:Boolean(d||u),needName:Boolean(o)});case s.i.Shipping:return n.a.createElement(br,{state:M,dispatch:A,shippingOptions:c||[],currency:D});case s.i.PaymentInfo:return n.a.createElement(Cr,{state:M,dispatch:A,canSaveCredentials:Boolean(!g&&l),needCardholderName:f,needCountry:j,needZip:C});case s.i.Checkout:return n.a.createElement(vr,{prices:O,shippingPrices:M.shipping&&c?Nr(c,M.shipping):void 0,totalPrice:q,invoiceContent:v,checkoutInfo:z,currency:D});default:return}}(a))):n.a.createElement("div",{className:"empty-content"},n.a.createElement(L.a,{color:"gray"})),n.a.createElement("div",{className:"footer"},n.a.createElement(R.a,{type:"submit",onClick:K,disabled:B,isLoading:B},Y)),y&&!y.field&&function(){if(y)return n.a.createElement(ge.a,{className:"error",isOpen:Boolean(y),onClose:G},n.a.createElement("h4",null,y.description||"Error"),n.a.createElement("p",null,y.description||"Error"),n.a.createElement(R.a,{isText:!0,onClick:P},U("OK")))}())}));function kr(e,t){return e.find(({id:e})=>e===t)}function Nr(e,t){const a=kr(e,t);return a?a.prices:void 0}var Ir=Object(n.h)(Object(c.h)(e=>{const{receipt:t}=e.payment,{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}=t||{};return{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}})(({isOpen:e,onClose:t,prices:a,shippingPrices:c,totalAmount:r,currency:s,info:l,photoUrl:o,text:i,title:d,credentialsTitle:m,shippingMethod:u})=>{const h=Object(F.a)(),b=er(s),g=Object(n.p)(()=>function(e,t,a){if(!t)return{paymentMethod:e};const{shippingAddress:n}=t,c=n&&n.streetLine1?`${n.streetLine1}, ${n.city}, ${n.countryIso2}`:void 0,{phone:r,name:s}=t;return{paymentMethod:e,paymentProvider:"Stripe",shippingAddress:c,name:s,phone:r,shippingMethod:a}}(m,l,u),[l,u,m]);return n.a.createElement(ge.a,{className:"PaymentModal PaymentModal-receipt",isOpen:e,onClose:t},n.a.createElement("div",null,n.a.createElement("div",{className:"header",dir:h.isRtl?"rtl":void 0},n.a.createElement(R.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null," ",h("PaymentReceipt")," ")),n.a.createElement("div",{className:"receipt-content custom-scroll"},n.a.createElement(vr,{prices:a,shippingPrices:c,totalPrice:r,invoiceContent:{photoUrl:o,text:i,title:d},checkoutInfo:g,currency:b}))))}))},,,,,,,,,,,,,,,,,,,,,,function(e,t,a){"use strict";a.d(t,"a",(function(){return s}));var n=a(5),c=a(54);const r={MonkeyIdle:a.p+"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs",MonkeyTracking:a.p+"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs",MonkeyClose:a.p+"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs",MonkeyPeek:a.p+"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs",FoldersAll:a.p+"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs",FoldersNew:a.p+"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs",DiscussionGroups:a.p+"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs"};function s(e){const t=r[e].replace(window.location.origin,"");return c.b("file"+t,n.ApiMediaFormat.Lottie)}},,,,,function(e,t,a){"use strict";var n=a(0),c=a(8),r=a(1),s=a(13),l=a(25),o=a(32),i=a(110),d=a(16);a(151);const m={type:"blob",quality:.8,format:"jpeg",circle:!1};let u,h,b;var g=Object(n.h)(({file:e,onChange:t,onClose:c})=>{const[g,p]=Object(n.r)(!1);Object(n.n)(()=>{e&&(g?async function(e){try{const t=document.getElementById("avatar-crop");if(!t)return;const{offsetWidth:a,offsetHeight:n}=t;b=new u(t,{enableZoom:!0,boundary:{width:a,height:n},viewport:{width:a-16,height:n-16,type:"circle"}});const c=await Object(s.a)(e);await b.bind({url:c})}catch(e){r.p&&console.error(e)}}(e):async function(){return h||(h=Promise.all([a.e(6),a.e(8)]).then(a.bind(null,315)),u=(await h).default),h}().then(()=>p(!0)))},[e,g]);const v=Object(l.a)();return n.a.createElement(i.a,{isOpen:Boolean(e),onClose:c,title:"Drag to reposition",className:"CropModal",hasCloseButton:!0},g?n.a.createElement("div",{id:"avatar-crop"}):n.a.createElement(d.a,null),n.a.createElement(o.a,{className:"confirm-button",round:!0,color:"primary",onClick:async function(){if(!b)return;const e=await b.result(m),a="string"==typeof e?e:Object(s.b)(e,"avatar.jpg");t(a)},ariaLabel:v("CropImage")},n.a.createElement("i",{className:"icon-check"})))});a(152);t.a=Object(n.h)(({title:e="Change your profile picture",disabled:t,currentAvatarBlobUrl:a,onChange:r})=>{const[s,l]=Object(n.r)(),[o,i]=Object(n.r)(a);Object(n.n)(()=>{i(a)},[a]);const d=Object(c.a)(o&&"filled",t&&"disabled");return n.a.createElement("div",{className:"AvatarEditable"},n.a.createElement("label",{className:d,role:"button",tabIndex:0,title:e},n.a.createElement("input",{type:"file",onChange:function(e){const t=e.target;t&&t.files&&t.files[0]&&(l(t.files[0]),t.value="")},accept:"image/png, image/jpeg"}),n.a.createElement("i",{className:"icon-camera-add"}),o&&n.a.createElement("img",{src:o,alt:"Avatar"})),n.a.createElement(g,{file:s,onClose:function(){l(void 0)},onChange:function(e){l(void 0),r(e),o&&URL.revokeObjectURL(o),i(URL.createObjectURL(e))}}))})},,,,,,,,,,function(e,t,a){},,,,,,,,function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(125),l=a(116);a(140);const o=[0,50],i=[0,20],d=[20,0],m=r.g?c.rb:c.qb;t.a=Object(n.h)(({isPasswordVisible:e,isBig:t})=>{const[a,r]=Object(n.r)(),[u,h]=Object(n.r)(),[b,g]=Object(n.r)(!1),[p,v]=Object(n.r)(!1);Object(n.n)(()=>{a?setTimeout(()=>v(!0),2e3):Object(s.a)("MonkeyClose").then(r)},[a]),Object(n.n)(()=>{u||Object(s.a)("MonkeyPeek").then(h)},[u]);const E=Object(n.m)(()=>g(!0),[]);return n.a.createElement("div",{id:"monkey",className:t?"big":""},!b&&n.a.createElement("div",{className:"monkey-preview"}),a&&n.a.createElement(l.a,{id:"closeMonkey",size:t?c.Bb:m,className:p?"hidden":"shown",animationData:a,playSegment:o,noLoop:!0,onLoad:E}),u&&n.a.createElement(l.a,{id:"peekMonkey",size:t?c.Bb:m,className:p?"shown":"hidden",animationData:u,playSegment:e?i:d,noLoop:!0}))})},function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(8),l=a(25),o=a(32);const i=r.g?550:400;t.a=Object(n.h)(({isLoading:e=!1,isPasswordVisible:t,error:a,hint:d,placeholder:m="Password",submitLabel:u="Next",clearError:h,onChangePasswordVisibility:b,onInputChange:g,onSubmit:p})=>{const v=Object(n.q)(null),E=Object(l.a)(),[O,f]=Object(n.r)(""),[j,C]=Object(n.r)(!1);return Object(n.n)(()=>{r.l||setTimeout(()=>{v.current.focus()},i)},[]),Object(n.n)(()=>{a&&requestAnimationFrame(()=>{v.current.focus(),v.current.select()})},[a]),n.a.createElement("form",{action:"",onSubmit:function(t){t.preventDefault(),e||j&&p(O)},autoComplete:"off"},n.a.createElement("div",{className:Object(s.a)("input-group password-input",O&&"touched",a&&"error"),dir:E.isRtl?"rtl":void 0},n.a.createElement("input",{ref:v,className:"form-control",type:t?"text":"password",id:"sign-in-password",value:O||"",autoComplete:"current-password",onChange:function(e){a&&h();const{target:t}=e;f(t.value),C(t.value.length>=c.Y),g&&g(t.value)},dir:"auto"}),n.a.createElement("label",null,a||d||m),n.a.createElement("div",{className:"toggle-password",onClick:function(){b(!t)},role:"button",tabIndex:0,title:"Toggle password visibility"},n.a.createElement("i",{className:t?"icon-eye":"icon-eye-closed"}))),j&&n.a.createElement(o.a,{type:"submit",ripple:!0,isLoading:e},u))})},,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,function(e,t,a){},,,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){}])]); -//# sourceMappingURL=3.048f19f68ad10b65610e.js.map \ No newline at end of file diff --git a/dist/3.048f19f68ad10b65610e.js.map b/dist/3.048f19f68ad10b65610e.js.map deleted file mode 100644 index 36d7880b..00000000 --- a/dist/3.048f19f68ad10b65610e.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///./src/components/mediaViewer/helpers/ghostAnimation.ts","webpack:///./src/components/mediaViewer/SenderInfo.tsx","webpack:///./src/components/mediaViewer/MediaViewerActions.tsx","webpack:///./src/components/mediaViewer/MediaViewerFooter.tsx","webpack:///./src/hooks/useFullscreen.ts","webpack:///./src/components/mediaViewer/helpers/formatFileSize.ts","webpack:///./src/components/mediaViewer/VideoPlayerControls.tsx","webpack:///./src/components/mediaViewer/VideoPlayer.tsx","webpack:///./src/components/mediaViewer/ZoomControls.tsx","webpack:///./src/components/mediaViewer/PanZoom.tsx","webpack:///./src/components/mediaViewer/MediaViewer.tsx","webpack:///./src/components/main/ForwardPicker.tsx","webpack:///./src/components/main/Errors.tsx","webpack:///./src/components/main/Notifications.tsx","webpack:///./src/components/main/SafeLinkModal.tsx","webpack:///./src/components/common/CalendarModal.tsx","webpack:///./src/components/common/DeleteMessageModal.tsx","webpack:///./src/components/common/PinMessageModal.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.tsx","webpack:///./src/components/middle/DeleteSelectedMessagesModal.tsx","webpack:///./src/components/middle/MessageSelectToolbar.tsx","webpack:///./src/hooks/useSelectWithEnter.ts","webpack:///./src/components/left/search/LeftSearchResultChat.tsx","webpack:///./src/components/left/search/RecentContacts.tsx","webpack:///./src/components/left/search/ChatMessage.tsx","webpack:///./src/components/left/search/DateSuggest.tsx","webpack:///./src/components/left/search/ChatResults.tsx","webpack:///./src/components/left/search/ChatMessageResults.tsx","webpack:///./src/components/left/search/helpers/createMapStateToProps.ts","webpack:///./src/components/left/search/MediaResults.tsx","webpack:///./src/components/left/search/helpers/getSenderName.ts","webpack:///./src/components/left/search/LinkResults.tsx","webpack:///./src/components/left/search/FileResults.tsx","webpack:///./src/components/left/search/AudioResults.tsx","webpack:///./src/components/left/search/LeftSearch.tsx","webpack:///./src/hooks/useReducer.ts","webpack:///./src/hooks/reducers/useFoldersReducer.ts","webpack:///./src/hooks/reducers/useTwoFaReducer.ts","webpack:///./src/components/left/settings/SettingsHeader.tsx","webpack:///./src/components/left/settings/SettingsMain.tsx","webpack:///./src/components/ui/FloatingActionButton.tsx","webpack:///./src/components/common/UsernameInput.tsx","webpack:///./src/components/left/settings/SettingsEditProfile.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersMain.tsx","webpack:///./src/components/ui/ShowMoreButton.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersEdit.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatFilters.tsx","webpack:///./src/components/left/settings/folders/SettingsFolders.tsx","webpack:///./src/components/ui/RangeSlider.tsx","webpack:///./src/components/middle/composer/StickerSetCoverAnimated.tsx","webpack:///./src/components/middle/composer/StickerSetCover.tsx","webpack:///./src/components/common/StickerButton.tsx","webpack:///./src/components/left/settings/SettingsStickerSet.tsx","webpack:///./src/components/left/settings/SettingsGeneral.tsx","webpack:///./src/util/systemFilesDialog.ts","webpack:///./src/util/colors.ts","webpack:///./src/components/left/settings/WallpaperTile.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackground.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackgroundColor.tsx","webpack:///./src/components/left/settings/SettingsNotifications.tsx","webpack:///./src/components/left/settings/SettingsPrivacy.tsx","webpack:///./src/components/left/settings/SettingsLanguage.tsx","webpack:///./src/components/left/settings/helper/privacy.ts","webpack:///./src/components/left/settings/SettingsPrivacyVisibility.tsx","webpack:///./src/components/left/settings/SettingsPrivacyActiveSessions.tsx","webpack:///./src/components/left/settings/SettingsPrivacyBlockedUsers.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEnabled.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaPassword.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaStart.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaSkippableForm.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaCongratulations.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEmailCode.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFa.tsx","webpack:///./src/components/common/Picker.tsx","webpack:///./src/components/left/settings/SettingsPrivacyVisibilityExceptionList.tsx","webpack:///./src/components/left/settings/Settings.tsx","webpack:///./src/components/left/main/ContactList.tsx","webpack:///./src/components/left/newChat/NewChatStep1.tsx","webpack:///./src/components/left/newChat/NewChatStep2.tsx","webpack:///./src/components/left/newChat/NewChat.tsx","webpack:///./src/components/left/ArchivedChats.tsx","webpack:///./src/util/scrollLock.ts","webpack:///./src/components/middle/message/helpers/copyOptions.ts","webpack:///./src/components/middle/message/MessageContextMenu.tsx","webpack:///./src/components/middle/message/ContextMenuContainer.tsx","webpack:///./src/components/common/StickerSetModal.tsx","webpack:///./src/components/middle/HeaderMenuContainer.tsx","webpack:///./src/components/middle/MobileSearch.tsx","webpack:///./src/util/findInViewport.ts","webpack:///./src/util/isFullyVisible.ts","webpack:///./src/components/middle/composer/MentionTooltip.tsx","webpack:///./src/components/middle/composer/AttachmentModal.tsx","webpack:///./src/components/middle/composer/PollModal.tsx","webpack:///./src/hooks/useMouseInside.ts","webpack:///./src/components/middle/composer/EmojiButton.tsx","webpack:///./src/components/middle/composer/EmojiCategory.tsx","webpack:///./src/components/middle/composer/EmojiPicker.tsx","webpack:///./src/components/middle/composer/StickerSet.tsx","webpack:///./src/components/middle/composer/StickerPicker.tsx","webpack:///./src/components/common/GifButton.tsx","webpack:///./src/components/middle/composer/GifPicker.tsx","webpack:///./src/components/middle/composer/SymbolMenuFooter.tsx","webpack:///./src/components/middle/composer/SymbolMenu.tsx","webpack:///./src/components/middle/composer/AttachMenu.tsx","webpack:///./src/components/middle/composer/StickerTooltip.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.tsx","webpack:///./src/components/right/RightSearch.tsx","webpack:///./src/components/right/StickerSetResult.tsx","webpack:///./src/components/right/StickerSearch.tsx","webpack:///./src/components/right/GifSearch.tsx","webpack:///./src/components/right/PollAnswerResults.tsx","webpack:///./src/components/right/PollResults.tsx","webpack:///./src/components/right/management/ManageUser.tsx","webpack:///./src/components/right/management/ManageGroup.tsx","webpack:///./src/components/right/management/ManageGroupPermissions.tsx","webpack:///./src/components/right/management/ManageGroupRemovedUsers.tsx","webpack:///./src/components/right/management/ManageChannel.tsx","webpack:///./src/components/right/management/ManageChatPrivacyType.tsx","webpack:///./src/components/right/management/ManageDiscussion.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissions.tsx","webpack:///./src/components/right/management/ManageChatAdministrators.tsx","webpack:///./src/components/right/management/ManageGroupRecentActions.tsx","webpack:///./src/components/right/management/ManageGroupAdminRights.tsx","webpack:///./src/components/right/management/ManageGroupMembers.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissionsCreate.tsx","webpack:///./src/components/right/management/Management.tsx","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/components/common/helpers/detectCardType.ts","webpack:///./src/hooks/reducers/usePaymentReducer.ts","webpack:///./src/hooks/useFocusAfterAnimation.tsx","webpack:///./src/components/ui/Select.tsx","webpack:///./src/components/payment/ShippingInfo.tsx","webpack:///./src/components/payment/Shipping.tsx","webpack:///./src/components/payment/Checkout.tsx","webpack:///./src/components/payment/ExpiryInput.tsx","webpack:///./src/components/middle/helpers/inputFormatters.ts","webpack:///./src/assets/mastercard.svg","webpack:///./src/assets/visa.svg","webpack:///./src/components/payment/CardInput.tsx","webpack:///./src/components/payment/PaymentInfo.tsx","webpack:///./src/components/payment/PaymentModal.tsx","webpack:///./src/components/payment/ReceiptModal.tsx","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx"],"names":["animateOpening","hasFooter","origin","bestImageData","message","mediaEl","fromImage","getNodes","width","windowWidth","windowSize","get","mediaSize","isVideo","photo","video","webPage","getMessageContent","Boolean","getVideoDimensions","getPhotoFullDimensions","AVATAR_FULL_DIMENSIONS","availableWidth","height","availableHeight","getMediaViewerAvailableDimensions","toWidth","toHeight","calculateDimensions","toLeft","toTop","mql","window","matchMedia","MEDIA_VIEWER_MEDIA_QUERY","topOffsetRem","matches","REM","getTopOffset","top","fromTop","left","fromLeft","fromWidth","fromHeight","getBoundingClientRect","MediaViewerOrigin","SharedMedia","Album","ScheduledAlbum","SearchResult","includes","uncovered","realWidth","realHeight","size","Math","max","srcWidth","srcHeight","uncover","fromTranslateX","fromTranslateY","fromScaleX","fromScaleY","ghost","createGhost","applyStyles","transform","applyShape","document","body","classList","add","requestAnimationFrame","appendChild","style","firstChild","objectFit","remove","clearShape","setTimeout","contains","removeChild","ANIMATION_END_DELAY","animateClosing","container","toImage","getElementById","querySelector","targetTop","el","display","rect","windowHeight","isElementInViewport","shouldFadeOut","Inline","ScheduledInline","isMessageImageFullyVisible","existingGhost","getElementsByClassName","ProfileAvatar","transition","transformOrigin","opacity","source","shouldAppendProfileInfo","createElement","img","Image","src","HTMLVideoElement","poster","profileInfo","cloneNode","imageEl","messageListElement","imgOffsetTop","offsetTop","closest","id","parentElement","scrollTop","offsetHeight","element","styles","Object","assign","containerSelector","mediaSelector","MiddleHeaderAvatar","mediaEls","querySelectorAll","length","withGlobal","global","chatId","messageId","isAvatar","sender","isChatPrivate","selectUser","selectChat","selectChatMessage","selectSender","setGlobal","actions","pick","closeMediaViewer","focusMessage","handleFocusMessage","useCallback","lang","useLang","isFromChat","senderTitle","getSenderTitle","className","onClick","Avatar","key","chat","user","dir","renderText","formatMediaDateTime","date","MediaViewerActions","mediaData","isZoomed","fileName","onCloseMediaViewer","onForward","onZoomToggle","isVideoDownloadAllowed","setIsVideoDownloadAllowed","useState","videoMediaHash","getMessageMediaHash","undefined","videoBlobUrl","downloadProgress","useMediaWithDownloadProgress","useEffect","download","handleVideoDownloadClick","e","stopPropagation","isAllowed","MenuButton","useMemo","onTrigger","isOpen","Button","round","color","ariaLabel","IS_MOBILE_SCREEN","DropdownMenu","trigger","positionX","MenuItem","icon","href","ProgressSpinner","progress","noCross","MediaViewerFooter","text","isHideable","isMultiline","setIsMultiline","footerContent","checkIsMultiline","clientHeight","handleResize","throttle","addEventListener","removeEventListener","prop","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","getBrowserFullscreenElementProp","units","bytes","number","floor","log","toFixed","stopEvent","VideoPlayerControls","bufferedProgress","currentTime","duration","fileSize","isForceVisible","isForceMobileVersion","isPlayed","isFullscreenSupported","isFullscreen","onChangeFullscreen","onPlayPause","onSeek","isVisible","setVisibility","timeout","clearTimeout","downloadedPercent","totalSize","percentagePlayed","percentageBuffered","min","step","type","onInput","value","renderSeekLine","ripple","formatMediaDuration","renderTime","formatFileSize","memo","url","isGif","posterData","posterSize","isMediaViewerOpen","noPlay","onClose","videoRef","useRef","setIsPlayed","IS_TOUCH_ENV","IS_IOS","setCurrentTime","isControlsVisible","setIsControlsVisible","setFullscreen","exitFullscreen","elRef","setIsFullscreen","useLayoutEffect","listener","listenerEnter","listenerExit","current","PLATFORM_ENV","requestFullscreen","webkitRequestFullscreen","webkitEnterFullscreen","mozRequestFullScreen","mozCancelFullScreen","webkitCancelFullScreen","webkitExitFullscreen","useFullscreenStatus","isBuffered","bufferingHandlers","useBuffering","shouldRender","shouldRenderSpinner","transitionClassNames","spinnerClassNames","useShowTransition","pause","safePlay","togglePlayState","play","useVideoCleanup","handleMouseOver","handleMouseOut","handleTimeUpdate","currentTarget","handleEnded","handleFullscreenChange","handleSeek","Number","target","toggleControls","togglePayingStateBySpace","wrapperStyle","videoStyle","onMouseOver","onMouseOut","ref","autoPlay","playsInline","loop","muted","onEnded","onTimeUpdate","join","square","isShown","onChangeZoom","prevIsShown","usePrevious","inputRef","zoomLevel","setZoomLevel","isSeeking","handleStartSeek","handleStopSeek","buildClassName","disabled","onChange","onMouseDown","onMouseUp","INITIAL_MATRIX","SCALE_VALUES","1","1.5","2","2.5","3","children","noWrap","canPan","panDeltaX","panDeltaY","onPan","tunedZoomLevel","isDragging","setIsDragging","dragData","setDragData","dx","dy","x","y","matrixData","setMatrixData","panWrapperRef","panContainerRef","newZoomLevel","newPandx","newPandy","newMatrixData","areSortedArraysEqual","oldScale","wrapper","image","wrapperRect","imageRect","newImgWidth","newImgHeight","newImgX","newImgY","calculateSafeZoneOnZoom","toString","preventDefault","newDragData","pageX","pageY","onMouseMove","deltaX","deltaY","getNewMatrixData","renderPhoto","blobUrl","imageSize","canDrag","alt","draggable","Spinner","threadId","avatarOwnerId","profilePhotoIndex","mediaViewer","animationLevel","settings","byKey","senderId","avatarOwner","chatMessages","collectionIds","selectScheduledMessage","selectScheduledMessages","selectChatMessages","selectOutlyingIds","selectListedIds","currentSearch","selectCurrentMediaSearch","foundIds","resultsByType","media","openMediaViewer","openForwardMenu","animationKey","webPagePhoto","getMessageWebPagePhoto","getMessagePhoto","getMessageVideo","isWebPagePhoto","isPhoto","isFromSharedMedia","isFromSearch","slideAnimation","headerAnimation","isGhostAnimation","getMessageMediaFilename","prevSenderId","canPanZoomWrap","setCanPanZoomWrap","setIsZoomed","panDelta","setPanDelta","messageIds","getChatMediaMessageIds","selectedMediaMessageIndex","indexOf","isFirst","isLast","getMediaHash","full","photos","getChatAvatarHash","blobUrlPictogram","useMedia","ApiMediaFormat","BlobUrl","previewMediaHash","blobUrlPreview","startsWith","DataUri","fullMediaData","getMessageMediaFormat","localBlobUrl","thumbDataUri","useBlurSync","getMessageMediaThumbDataUri","photoDimensions","videoDimensions","toggle","forceUpdate","useForceUpdate","addListener","removeListener","prevMessage","prevOrigin","prevAvatarOwner","prevBestImageData","dispatchHeavyAnimationEvent","textParts","renderMessageText","timer","closeZoom","handleZoomToggle","handleZoomValue","level","canCloseZoom","close","handleFooterClick","handleForward","fromChatId","captureEscKeyListener","stopCurrentAudio","getMessageId","fromId","direction","index","selectPreviousMedia","selectNextMedia","handleKeyDown","shouldCloseOnVideo","captureEvents","excludedClosestSelector","onSwipe","SwipeDirection","Right","Left","handlePan","renderSlide","isActive","calculateMediaViewerDimensions","renderSenderInfo","ShowTransition","isRtl","Transition","activeKey","name","aria-label","chats","byId","chatsById","listIds","currentUserId","activeListIds","active","archivedListIds","archived","setForwardChatId","exitForwardMode","loadMoreChats","filter","setFilter","focus","blur","chatIds","sortChatIds","getCanPostInChat","MAIN_THREAD_ID","searchWords","getChatTitle","viewportIds","getMore","useInfiniteScroll","handleFilterChange","containerRef","useKeyboardListNavigation","modalHeader","InputText","onKeyDown","placeholder","Modal","header","InfiniteScroll","items","onLoadMore","noScrollRestore","map","ListItem","PrivateChatInfo","status","userId","GroupChatInfo","Loading","getErrorHeader","error","isSlowMode","errors","dismissError","title","getReadableErrorText","isText","notifications","dismissNotification","Notification","onDismiss","toggleSafeLinkModal","handleOpen","open","handleDismiss","renderingUrl","useCurrentOrPrev","ConfirmDialog","confirmLabel","confirmHandler","WEEKDAY_LETTERS","isDisabledDay","year","month","day","minDate","maxDate","selectedDay","Date","fixedMinDate","getFullYear","getMonth","getDate","fixedMaxDate","formatInputTime","String","padStart","selectedAt","maxAt","isFutureMode","isPastMode","withTimePicker","submitButtonLabel","secondButtonLabel","onSubmit","onSecondButtonClick","now","defaultSelectedDate","selectedDate","setSelectedDate","selectedHours","setSelectedHours","getHours","selectedMinutes","setSelectedMinutes","getMinutes","currentYear","currentMonth","currentDate","shouldDisableNextMonth","shouldDisablePrevMonth","calendarGrid","grid","setFullYear","setMonth","setDate","monthStartDay","getDay","i","push","gridDate","buildCalendarGrid","handleChangeHours","replace","hours","getTime","setHours","hoursStr","handleChangeMinutes","minutes","setMinutes","minutesStr","formatMonthAndYear","d","dateCopy","letter","role","tabIndex","handleDateSelect","inputMode","formatHumanDate","formatTime","formatSubmitLabel","isSchedule","selectCurrentMessageList","canDeleteForAll","selectAllowedMessageActions","contactName","getUserFirstOrLastName","getPrivateChatUserId","willDeleteForCurrentUserOnly","isChatBasicGroup","willDeleteForAll","isChatSuperGroup","album","deleteMessages","deleteScheduledMessages","handleDeleteMessageForAll","messages","shouldDeleteForAll","handleDeleteMessageForSelf","onEnter","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","isChannel","isChatChannel","isGroup","isSuperGroup","canPinForAll","pinMessage","handlePinMessageForAll","isUnpin","handlePinMessage","isOneSide","isSilent","pinnedMessagesCount","onUnpin","selectedMessageIds","selectedMessages","selectCanDeleteSelectedMessages","selectCurrentChat","exitMessageSelectMode","messageListType","canDelete","selectedMessagesCount","selectSelectedMessagesCount","canDeleteMessages","canPost","openForwardMenuForSelectedMessages","isDeleteModalOpen","openDeleteModal","closeDeleteModal","useFlag","captureKeyboardListeners","onBackspace","onDelete","onEsc","prevSelectedMessagesCount","renderingSelectedMessagesCount","formattedMessagesCount","destructive","onSelect","buttonRef","activeElement","privateChatUserId","privateChatUser","isPinned","selectIsChatPinned","withUsername","contextActions","useChatContextActions","handleDelete","handleClick","useSelectWithEnter","avatarSize","DeleteChatModal","runThrottled","cb","userIds","topUserIds","topPeers","usersById","users","recentlyFoundChatIds","globalSearch","onReset","loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats","topUsersRef","useHorizontalScroll","lastSyncTime","searchQuery","mediaThumbnail","mediaBlobUrl","isRoundVideo","getMessageRoundVideo","withOnlineStatus","isSavedMessages","isSelf","isVerified","VerifiedIcon","Link","formatPastTimeShort","getMessageSummaryText","highlight","renderMessageSummary","searchDate","suggestions","match","formatDateToString","suggestion","latestYear","getSuggestionsFromDate","localContactIds","contactList","fetchingStatus","globalResults","localResults","globalChatIds","globalUserIds","localChatIds","localUserIds","byChatId","globalMessagesByChatId","dateSearchQuery","onSearchDateSelect","searchMessagesGlobal","setGlobalSearchChatId","shouldShowMoreLocal","setShouldShowMoreLocal","shouldShowMoreGlobal","setShouldShowMoreGlobal","handleLoadMore","LoadMoreDirection","Backwards","query","handleChatClick","handlePickerItemClick","MEMO_EMPTY_ARRAY","foundContactIds","fullName","getUserFullName","username","unique","foundMessages","split","sort","a","b","handleClickShowMoreLocal","handleClickShowMoreGlobal","nothingFound","noScrollRestoreOnTop","noFastList","NothingFound","description","PickerSelectedItem","chatOrUserId","clickArg","createMapStateToProps","props","currentType","isVoice","isLoading","searchChatId","handleSelectMedia","canRenderContents","useAsyncRendering","SLIDE_TRANSITION_DURATION","isMediaGrid","isMessageList","classNames","itemSelector","Media","idPrefix","getSenderName","senderName","isChatGroup","handleMessageFocus","shouldDrawDateDivider","toYearMonth","WebLink","onMessageClick","getMessageDocument","Document","withDate","datetime","smaller","onDateClick","openAudioPlayer","handlePlayAudio","Audio","renderingFor","onPlay","TABS","GlobalSearchContent","ChatList","Links","Files","Music","Voice","CHAT_TABS","slice","TRANSITION_RENDER_COUNT","keys","currentContent","setGlobalSearchContent","setGlobalSearchDate","activeTab","setActiveTab","parseDateString","handleSwitchTab","tab","content","handleSearchDateSelect","TabList","tabs","onSwitchTab","renderCount","useReducer","reducer","initialState","reducerRef","state","setState","action","currentState","INCLUDED_CHAT_TYPES","EXCLUDED_CHAT_TYPES","INCLUDE_FILTER_FIELDS","EXCLUDE_FILTER_FIELDS","selectChatFilters","mode","selectTemp","selectedChatIds","selectedChatTypes","includedChatIds","includeFilters","folder","excludedChatIds","excludeFilters","getSuggestedFolderName","filters","values","bots","groups","channels","contacts","nonContacts","INITIAL_STATE","chatFilter","foldersReducer","payload","isTouched","omit","folderId","currentPassword","password","hint","email","twoFaReducer","currentScreen","editedFolderId","onSaveFilter","signOut","deleteChatFolder","isSignOutDialogOpen","setIsSignOutDialogOpen","isDeleteFolderDialogOpen","setIsDeleteFolderDialogOpen","openSignOutConfirmation","closeSignOutConfirmation","openDeleteFolderConfirmation","closeDeleteFolderConfirmation","handleSignOutMessage","handleDeleteFolderMessage","SettingsMenuButton","SettingsScreens","EditProfile","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyPhoneNumberAllowedContacts","PrivacyLastSeenAllowedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyForwardingAllowedContacts","PrivacyGroupChatsAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsDeniedContacts","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaNewPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaChangePasswordHint","TwoFaNewPasswordEmail","TwoFaRecoveryEmail","TwoFaNewPasswordEmailCode","TwoFaRecoveryEmailCode","TwoFaCongratulations","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","Folders","FoldersCreateFolder","FoldersEditFolder","FoldersIncludedChats","FoldersExcludedChats","renderHeaderContent","confirmIsDestructive","currentUser","onScreenSelect","formatPhoneNumberWithCode","phoneNumber","FloatingActionButton","buttonClassName","LINK_PREFIX_REGEX","USERNAME_REGEX","runDebouncedForCheckUsername","debounce","currentUsername","asLink","isUsernameAvailable","checkUsername","setUsername","langPrefix","label","usernameSuccess","usernameError","test","handleUsernameChange","newUsername","trim","isValid","isUsernameValid","success","readOnly","profileEdit","firstName","currentFirstName","lastName","currentLastName","fullInfo","bio","currentBio","currentAvatarHash","loadCurrentUser","updateProfile","isUsernameTouched","setIsUsernameTouched","isProfileFieldsTouched","setIsProfileFieldsTouched","setError","setPhoto","setFirstName","setLastName","setBio","currentAvatarBlobUrl","ProfileEditProgress","InProgress","isUsernameError","isSaveButtonShown","Complete","handlePhotoChange","newPhoto","handleFirstNameChange","handleLastNameChange","handleBioChange","handleProfileSave","trimmedFirstName","trimmedLastName","trimmedBio","AvatarEditable","UsernameInput","runThrottledForLoadRecommended","orderedIds","orderedFolderIds","foldersById","recommended","recommendedChatFolders","chatFolders","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","onCreateFolder","onEditFolder","loadRecommendedChatFolders","addChatFolder","showError","animationData","setAnimationData","isAnimationLoaded","setIsAnimationLoaded","handleAnimationLoad","getAnimationData","then","handleCreateFolder","userFolders","subtitle","getFolderDescriptionText","handleCreateFolderFromRecommended","AnimatedSticker","STICKER_SIZE_FOLDER_SETTINGS","noLoop","onLoad","pill","fluid","narrow","multiline","ShowMoreButton","count","itemName","itemPluralName","ERROR_NO_TITLE","ERROR_NO_CHATS","loadedActiveChatIds","loadedArchivedChatIds","dispatch","onAddIncludedChats","onAddExcludedChats","editChatFolder","isIncludedChatsListExpanded","setIsIncludedChatsListExpanded","isExcludedChatsListExpanded","setIsExcludedChatsListExpanded","includedChatTypes","excludedChatTypes","visibleIncludedChatIds","visibleExcludedChatIds","allLoadedChatsSet","Set","loadedIncludedChatIds","findIntersectionWithSet","loadedExcludedChatIds","listType","renderChats","visibleChatIds","isExpanded","leftChatsCount","clickHandler","chatType","find","typeKey","inactive","renderChatType","event","folderUpdate","selectedIds","filterValue","onSelectedIdsChange","onSelectedChatTypesChange","onFilterChange","chatTypes","shouldMinimize","hasMaxChats","handleItemClick","newSelectedIds","splice","handleChatTypeClick","newSelectedChatTypes","selectedType","isMinimized","canClose","Checkbox","checked","isSelected","withChatType","orderedPinnedIds","archivedPinnedIds","activeChatArrays","prepareChatList","archivedChatArrays","pinnedChats","otherChats","displayedIds","newFilter","handleSelectedIdsChange","ids","handleSelectedChatTypesChange","newFilters","forEach","handleReset","handleEditFolder","handleAddIncludedChats","handleAddExcludedChats","options","range","handleChange","trackWidth","possibleValuesLength","option","STICKER_SIZE_PICKER_HEADER","stickerSet","observeIntersection","isIntersecting","useIsIntersecting","mediaHash","lottieData","Lottie","shouldRenderFullMedia","useTransitionForMedia","getFirstLetters","hasThumbnail","sticker","noAnimate","onUnfaveClick","localMediaHash","stickerSelector","thumbnail","dataUri","previewBlobUrl","shouldPlay","isAnimated","markLoaded","unmarkLoaded","canAnimatedPlay","shouldRenderThumb","shouldRenderPreview","previewTransitionClassNames","fullClassName","emoji","data-sticker-id","isLowPriority","stickers","firstSticker","STICKER_SIZE_GENERAL_SETTINGS","ANIMATION_LEVEL_OPTIONS","stickerSetIds","added","setIds","stickerSetsById","setsById","messageTextSize","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers","setSettingOption","loadStickerSets","loadAddedStickers","stickerSettingsRef","observe","observeIntersectionForCovers","useIntersectionObserver","rootRef","isModalOpen","openModal","closeModal","setSticker","KEYBOARD_SEND_OPTIONS","subLabel","IS_MAC_OS","handleAnimationLevelChange","newLevel","_","handleMessageTextSizeChange","newSize","documentElement","setProperty","handleStickerSetClick","stickerSets","installedDate","RadioGroup","selected","onCheck","isChecked","fromSticker","fileSelector","openSystemFilesDialog","accept","callback","noMultiple","setAttribute","removeAttribute","onchange","click","hex2rgb","param","parseInt","substring","rgb2hex","p0","p1","p2","rgb2hsb","r","g","h","s","v","hsb2rgb","f","p","q","t","getPatternColor","rgbColor","hue","saturation","wallpaper","theme","slug","thumbRef","useCanvasBlur","isDownloadAllowed","setIsDownloadAllowed","fullMedia","wasDownloadDisabled","UPLOADING_WALLPAPER_SLUG","cacheKeyRef","handleSelect","blob","fetchBlob","cacheApi","CUSTOM_BG_CACHE_NAME","background","isBlurred","themes","loadedWallpapers","loadWallpapers","uploadWallpaper","setThemeSettings","themeRef","handleFileSelect","files","handleUploadWallpaper","handleSetColor","handleResetToDefault","backgroundColor","patternColor","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","handleWallPaperSelect","currentWallpaper","async","defaultRGB","data","rgb","canvas","context","getContext","preloadImage","naturalHeight","naturalWidth","offsetWidth","drawImage","getImageData","blockSize","getAverageColor","handleWallPaperBlurChange","isUploading","DEFAULT_HSB","PREDEFINED_COLORS","hsb2positions","hsb","rects","colorPosition","colorRect","huePosition","hueRect","positions2hsb","colorPickerRef","huePickerRef","isFirstRunRef","setHsb","getInitialHsb","hsbRef","markIsDragging","unmarkIsDragging","rgbInput","setRgbInput","hexInput","setHexInput","rectsRef","colorCtxRef","offsetLeft","handleColorDrag","handleHueDrag","onCapture","onDrag","onRelease","withCursor","hex","hueHex","w","ctx","imgData","createImageData","pixels","col","perY","st","ed","perX","putImageData","drawColor","drawHue","handleRgbChange","rgbValue","channel","handleHexChange","hexValue","handlePredefinedColorClick","dataset","data-color","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","hasContactJoinedNotifications","loadNotificationSettings","updateContactSignUpNotification","updateNotificationSettings","handleSettingsChange","peerType","setting","currentIsSilent","currentShouldShowPreviews","shouldShowPreviews","handleContactNotificationChange","hasPassword","privacy","blocked","activeSessions","blockedCount","totalCount","sessionsCount","visibilityPrivacyPhoneNumber","visibility","visibilityPrivacyLastSeen","lastSeen","visibilityPrivacyProfilePhoto","profilePhoto","visibilityPrivacyForwarding","forwards","visibilityPrivacyGroupChats","chatInvite","loadPrivacySettings","loadBlockedContacts","loadAuthorizations","getVisibilityValue","languages","language","loadLanguages","selectedLanguage","setSelectedLanguage","markIsLoading","unmarkIsLoading","langCode","setLanguage","currentLangCode","navigator","toLowerCase","shortLangCode","substr","nativeName","buildOptions","loadingOption","getPrivacyKey","screen","privacySettings","allowUserIds","allowChatIds","blockUserIds","blockChatIds","setPrivacyVisibility","visibilityOptions","exceptionLists","shouldShowDenied","shouldShowAllowed","privacyKey","headerText","descriptionText","allowedContactsScreen","deniedContactsScreen","allowedCount","reduce","result","membersCount","blockCount","handleVisibilityChange","getLocation","session","region","country","getDeviceEnvironment","deviceModel","platform","systemVersion","terminateAuthorization","terminateAllAuthorizations","isConfirmTerminateAllDialogOpen","openConfirmTerminateAllDialog","closeConfirmTerminateAllDialog","handleTerminateSessionClick","hash","handleTerminateAllSessions","currentSession","isCurrent","otherSessions","renderSession","handler","dateActive","appName","ip","sessions","chatsByIds","usersByIds","blockedIds","unblockContact","handleUnblockClick","contactId","viewportOffset","isPrivate","CHAT_HEIGHT_PX","renderContact","animatedEmoji","selectAnimatedEmoji","AnimatedEmoji","expectedPassword","submitLabel","clearError","validationError","setValidationError","shouldShowPassword","setShouldShowPassword","handleSubmit","newPassword","handleClearError","PasswordMonkey","isBig","isPasswordVisible","PasswordForm","onChangePasswordVisibility","onStart","FOCUS_DELAY_TIMEOUT_MS","shouldConfirm","setValue","isConfirmShown","markIsConfirmShown","unmarkIsConfirmShown","codeLength","twoFaSettings","waitingEmailCodeLength","newValue","updatePassword","checkPassword","clearTwoFaError","updateRecoveryEmail","provideTwoFaEmailCode","clearPassword","handleStartWizard","handleNewPassword","handleNewPasswordConfirm","handleNewPasswordHint","handleNewPasswordEmail","onSuccess","handleChangePasswordCurrent","handleChangePasswordNew","handleChangePasswordConfirm","handleChangePasswordHint","handleTurnOff","handleRecoveryEmailCurrentPassword","handleRecoveryEmail","handleEmailCode","code","itemIds","filterPlaceholder","notFoundText","searchInputId","getCurrentPrivacySettings","isAllowList","setPrivacySettings","selectedContactIds","setSearchQuery","isSubmitShown","setIsSubmitShown","newSelectedContactIds","setNewSelectedContactIds","handleSelectedContactIdsChange","contactsIds","foldersState","foldersDispatch","twoFaState","twoFaDispatch","handleSaveFilter","renderCurrentSection","Main","renderCurrentSectionContent","contactIds","resultIds","sortUserIds","forceShowSelf","isSearching","selectedMemberIds","onSelectedMemberIdsChange","onNextStep","setGlobalSearchQuery","handleNextStep","creationProgress","creationError","chatCreation","memberIds","createGroupChat","createChannel","setTitle","about","setAbout","ChatCreationProgress","handleTitleChange","handleDescriptionChange","handleCreateGroup","handleCreateChannel","renderedError","RENDER_COUNT","LeftColumnContent","onContentChange","newChatMemberIds","setNewChatMemberIds","NewChannelStep2","NewGroupStep2","NewChannelStep1","NewGroupStep1","folderType","noChatsText","IGNORED_KEYS","Down","ArrowDown","Up","ArrowUp","ArrowLeft","ArrowRight","PageUp","PageDown","End","Home","Tab","preventDefaultForScrollKeys","disableScrolling","passive","ontouchmove","onkeydown","enableScrolling","getCopyLabel","hasSelection","canImageBeCopied","MessageContextMenu","anchor","canSendNow","canReschedule","canReply","canEdit","canPin","canUnpin","canForward","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","onReply","onEdit","onPin","onFaveSticker","onUnfaveSticker","onSend","onReschedule","onCloseAnimationEnd","onCopyLink","copyOptions","afterEffect","getMessageText","CLIPBOARD_ITEM_SUPPORTED","selection","getSelection","mediaLoader","copyImageToClipboard","anchorNode","parentNode","clipboardText","copyTextToClipboard","getMessageCopyOptions","getTriggerElement","getRootElement","getMenuElement","positionY","useContextMenuPosition","Menu","noOptions","isScheduled","setReplyingToId","setEditingId","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink","isMenuOpen","setIsMenuOpen","setIsDeleteModalOpen","isPinModalOpen","setIsPinModalOpen","isCalendarOpen","openCalendar","closeCalendar","closeMenu","closePinModal","handleCloseCalendar","handleReply","handleEdit","handlePin","handleUnpin","handleFaveSticker","handleUnfaveSticker","handleSelectMessage","params","childMessageIds","withShift","handleScheduledMessageSend","handleOpenCalendar","handleRescheduleMessage","scheduledAt","handleCopyLink","scheduledMaxDate","getDayStartAt","selectStickerSet","stickerSetId","loadStickers","toggleStickerSet","sendMessage","throttleMs","isDisabled","stickerSetAccessHash","isPreloadedGlobally","handleButtonClick","hasCloseButton","STICKER_SIZE_MODAL","isRestricted","isMuted","canDeleteChat","getCanDeleteChat","canSubscribe","canSearch","canMute","canLeave","onSubscribeChannel","onSearchClick","updateChatMutedState","enterMessageSelectMode","handleToggleMuteClick","handleSubscribe","handleSearch","handleSelectMessages","Portal","runDebouncedForSearch","results","selectCurrentTextSearch","setLocalTextSearchQuery","searchTextMessagesLocal","closeLocalTextSearch","searchMessagesByDate","focusedIndex","setFocusedIndex","visualViewport","mainEl","pageTop","Array","from","input","div","contentEditable","handleMessageSearchQueryChange","newQuery","handleJumpToDate","timestamp","valueOf","handleUp","newFocusIndex","handleDown","SearchInput","findInViewport","selectorOrElements","margin","isDense","shouldContainBottom","isHorizontal","viewportY1","viewportY2","allElements","visibleIndexes","isFound","y1","y2","isFullyVisible","onInsertUserName","filteredChatMembers","getSelectedIndex","newIndex","cycleRestrict","selectedMentionIndex","setSelectedMentionIndex","handleArrowKey","handleUserSelect","forceFocus","handleSelectMention","member","onUp","onDown","onTab","first","position","fastSmoothScroll","setItemVisible","prevChatMembers","renderedChatMembers","attachments","caption","canSuggestMembers","groupChatMembers","recentEmojis","onCaptionUpdate","addRecentEmoji","loadEmojiKeywords","onFileAppend","onClear","hideTimeoutRef","prevAttachments","renderingAttachments","isHovered","markHovered","unmarkHovered","isQuick","every","quick","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","insertMention","mentionFilteredMembers","useMentionTooltip","EDITABLE_INPUT_MODAL_ID","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","sendAttachments","handleFilesDrop","dataTransfer","newFiles","file","CONTENT_TYPES_FOR_QUICK_UPLOAD","areAllPhotos","mimeType","areAllVideos","renderHeader","onDragEnter","onDrop","onDragOver","onDragLeave","relatedTarget","toTarget","fromTarget","data-attach-description","attachment","File","filename","extension","getFileExtension","previewData","emojis","onEmojiSelect","MessageInput","html","editableInputId","onUpdate","shouldSetFocus","questionInputRef","optionsListRef","solutionRef","question","setQuestion","setOptions","isAnonymous","setIsAnonymous","isMultipleAnswers","setIsMultipleAnswers","isQuizMode","setIsQuizMode","solution","setSolution","correctOption","setCorrectOption","hasErrors","setHasErrors","focusInput","solutionEl","innerHTML","addNewOption","newOptions","list","scrollHeight","scrollTo","behavior","handleCreate","questionTrimmed","optionsTrimmed","o","summary","answers","correct","isPublic","multipleChoice","quiz","entities","parseMessageInput","correctAnswers","solutionEntities","updateOption","removeOption","handleCorrectOptionChange","handleIsAnonymousChange","handleMultipleAnswersChange","handleQuizModeChange","handleKeyPress","keyCode","getQuestionError","getOptionsError","renderOptions","onKeyPress","renderQuizNoOptionError","hidden","closeTimeout","useMouseInside","menuCloseTimeout","isMouseInside","native","names","IS_EMOJI_SUPPORTED","loading","category","allEmojis","useOnIntersect","emojisPerRow","ceil","displayedEmoji","ICONS_BY_CATEGORY","recent","people","nature","foods","activity","places","objects","symbols","flags","categoryIntersections","emojiDataPromise","emojiRawData","emojiData","headerRef","categories","setCategories","setEmojis","activeCategoryIndex","setActiveCategoryIndex","entries","entry","intersectingWithIndexes","newLeft","HEADER_BUTTON_WIDTH","fastSmoothScrollHorizontal","allCategories","themeCategories","unshift","exec","default","uncompressEmoji","ensureEmojiData","selectCategory","categoryEl","handleEmojiSelect","MENU_TRANSITION_DURATION","containerClassName","faded","STICKER_MARGIN","loadAndPlay","onStickerSelect","onStickerUnfave","stickersPerRow","STICKER_SIZE_PICKER","stickerSetIntersections","favorite","recentStickers","favoriteStickers","addedSetIds","canSendStickers","loadRecentStickers","loadFavoriteStickers","addRecentSticker","activeSetIndex","setActiveSetIndex","areAddedLoaded","allSets","noPopulatedSets","set","stickerSetEl","handleStickerSelect","handleStickerUnfave","gif","videoData","shouldRenderVideo","preload","savedGifs","gifs","saved","canSendGifs","onGifSelect","loadSavedGifs","debounceMs","SymbolMenuTabs","SYMBOL_MENU_TAB_TITLES","SYMBOL_MENU_TAB_ICONS","Emoji","Stickers","GIFs","onRemoveSymbol","onSearchOpen","renderTabButton","handleSearchOpen","isActivated","allowedAttachmentOptions","setRecentEmojis","handleMouseEnter","handleMouseLeave","fastRaf","recentEmojisRef","renderContent","isFrom","onMouseEnter","onMouseLeave","noCloseOnBackdrop","onFileSelect","onPollCreate","handleQuickSelect","handleDocumentSelect","canAttachMedia","canAttachPolls","autoClose","forEmoji","clearStickersForEmoji","prevStickers","displayedStickers","clickInlineButton","keyboardButtons","row","button","onSilentSend","onScheduleSend","listEmojis","usePrevDuringAnimation","selectedIndex","setSelectedIndex","emojisCount","handleSelectEmoji","onLeft","onRight","messagesById","foundResults","senderUser","getGlobal","senderChat","forwardInfo","isChannelPost","orderBy","preloadBackwards","LastMessageMeta","selectShouldLoopStickers","isSomeModalOpen","onModalToggle","isAdded","areStickersLoaded","useOnChange","coverStickerIds","covers","otherStickers","handleAddClick","canRenderStickers","STICKER_SIZE_SEARCH","selectCurrentStickerSearch","featured","featuredIds","loadFeaturedStickers","setIsModalOpen","selectCurrentGifSearch","isChatWithBot","selectIsChatWithBot","searchMoreGifs","setGifSearchQuery","getAllowedAttachmentOptions","handleGifClick","hasResults","answer","voters","offsets","pollResults","offset","answerVote","totalVoters","loadPollOptionResults","closePollResults","prevVotersCount","votersCount","setIsLoading","areVotersLoaded","limit","shouldResetVoters","handleViewMoreClick","handleMemberClick","noStatusOrTyping","leftVotersCount","renderViewMoreButton","total","getMessagePoll","resultsByOption","buildCollectionByKey","management","updateContact","deleteUser","deleteHistory","closeManagement","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","currentIsMuted","isNotificationsEnabled","setIsNotificationsEnabled","ManagementProgress","handleNotificationChange","handleDeleteContact","withFullInfo","hasLinkedChannel","linkedChatId","isBasicGroup","canChangeInfo","getHasAdminRight","canBanUsers","togglePreHistoryHidden","updateChat","leaveChannel","deleteChannel","currentTitle","currentAbout","imageHash","handleClickEditType","ManagementScreens","ChatPrivacyType","handleClickDiscussion","Discussion","handleClickPermissions","GroupPermissions","handleClickAdministrators","ChatAdministrators","handleSetPhoto","handleAboutChange","handleUpdateGroup","trimmedTitle","trimmedAbout","handleClickMembers","GroupMembers","handleTogglePreHistory","isPreHistoryHidden","isEnabled","enabledPermissionsCount","defaultBannedRights","sendStickers","sendGifs","adminsCount","adminMembers","handleDeleteGroup","isCreator","formatInteger","onChatMemberSelect","updateChatDefaultBannedRights","permissions","setPermissions","havePermissionChanged","setHavePermissionChanged","handleRemovedUsersClick","GroupRemovedUsers","handleAddExceptionClick","GroupUserPermissionsCreate","handleExceptionMemberClick","promotedByUserId","GroupUserPermissions","handlePermissionChange","getUpdatedPermissionValue","handleSavePermissions","bannedRights","removedUsersCount","kickedMembers","exceptionMembers","members","getMemberExceptions","langKey","getLangKeyForBannedRightKey","translatedString","sendMessages","blocking","sendMedia","sendPolls","embedLinks","inviteUsers","pinMessages","changeInfo","updateChatMemberBannedRights","removedMembers","getRemovedBy","kickedByUserId","kickedByUser","getContextActions","isSignaturesShown","toggleSignatures","hasLinkedChat","handleUpdateChannel","handleToggleSignatures","handleClickSubscribers","ChannelSubscribers","handleDeleteChannel","selectManagement","checkPublicLink","updatePublicLink","updatePrivateLink","privateLink","inviteLink","privacyType","setPrivacyType","isRevokeConfirmDialogOpen","openRevokeConfirmDialog","closeRevokeConfirmDialog","canUpdate","handleOptionChange","handleSave","handleRevokePrivateLink","langPrefix1","langPrefix2","SafeLink","forDiscussionIds","linkedChat","loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup","linkedGroupId","setLinkedGroupId","isConfirmUnlinkGroupDialogOpen","openConfirmUnlinkGroupDialog","closeConfirmUnlinkGroupDialog","isConfirmLinkGroupDialogOpen","openConfirmLinkGroupDialog","closeConfirmLinkGroupDialog","handleUnlinkGroupSessions","channelId","Initial","handleLinkGroupSessions","renderLinkGroupHeader","linkedGroup","renderLinkGroupConfirmText","hasPrivateLink","STICKER_SIZE_DISCUSSION_GROUPS","teactFastList","teactOrderKey","isButtonsInOneRow","isPromotedByCurrentUser","isFormFullyDisabled","selectedChatMemberId","isBanConfirmationDialogOpen","openBanConfirmationDialog","closeBanConfirmationDialog","selectedChatMember","handleBanFromGroup","viewMessages","getControlIsDisabled","isOwner","handleAdminMemberClick","ChatAdminRights","getMemberStatus","promotedByUser","GroupRecentActions","updateChatAdmin","setIsTouched","isDismissConfirmationDialogOpen","openDismissConfirmationDialog","closeDismissConfirmationDialog","customTitle","setCustomTitle","adminRights","handleDismissAdmin","memberStatus","handleCustomTitleChange","postMessages","editMessages","banUsers","addAdmins","anonymous","maxLength","openUserInfo","memberId","managementType","selectCurrentManagementType","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","VISA","MASTERCARD1","MASTERCARD2","CardType","cards","Default","Visa","Mastercard","detectCardType","cardNumber","streetLine1","streetLine2","city","countryIso2","postCode","phone","shipping","cardholder","expiry","cvv","billingCountry","billingZip","saveInfo","saveCredentials","formErrors","getBillingCountry","countryCode","countryList","useFocusAfterAnimation","animationDuration","hasArrow","labelText","htmlFor","needEmail","needPhone","needName","needAddress","phoneRef","selectCountryRef","handleAddress1Change","handleAddress2Change","handleCityChange","handleStateChange","handleCountryChange","handlePostCodeChange","handleFullNameChange","handleEmailChange","handlePhoneChange","handleSaveInfoChange","shippingOptions","handleShippingSelect","amount","renderPaymentItem","main","renderCheckoutItem","invoiceContent","prices","shippingPrices","checkoutInfo","totalPrice","photoUrl","paymentMethod","paymentProvider","shippingAddress","shippingMethod","item","expiryInputRef","charAt","parts","formatCardExpiry","cardNumberRef","cardType","setCardType","newCardType","formatCardNumber","cardIcon","mastercardIconPath","visaIconPath","getCardIcon","canSaveCredentials","needCardholderName","needCountry","needZip","handleCardNumberChange","handleCardholderChange","toUpperCase","handleExpiryChange","handleCvvChange","handleBillingPostCodeChange","handleChangeSaveCredentials","savedInfo","invoice","nativeProvider","nativeParams","passwordMissing","payment","isProviderError","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","globalErrors","validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError","paymentState","paymentDispatch","currencySign","field","fieldError","getShippingError","handleErrorModalClose","PaymentStep","Checkout","shippingOption","getShippingPrices","totalPrices","concat","acc","cur","getTotalPrice","detectCardTypeText","findShippingOption","getCheckoutInfo","validateRequest","requestInfo","getRequestInfo","sendCredentials","credentials","expiryMonth","expiryYear","zip","getCredentials","sendForm","shippingOptionId","setStep","nextStep","ShippingInfo","Shipping","PaymentInfo","buttonText","cuurentStep","renderModalContent","renderError","optionId","receipt","mapedPrices","info","totalAmount","credentialsTitle","fullAddress","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","path","location","cropperResultOptions","quality","format","circle","Croppie","croppiePromise","cropper","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","enableZoom","boundary","viewport","blobToDataUri","bind","err","DEBUG","console","initCropper","ensureCroppie","croppedImg","blobToFile","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","URL","revokeObjectURL","createObjectURL","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","playSegment","onInputChange","setPassword","canSubmit","setCanSubmit","select","autoComplete","MIN_PASSWORD_LENGTH"],"mappings":"0jEAiBO,SAASA,EACdC,EAAoBC,EAA2BC,EAAuBC,GAEtE,MAAQC,QAASC,GAAcC,EAAS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SAA0B/J,GACpB8X,GACF06B,IAGF,MAAM,OAAErqC,GAAWnI,EACnB+xE,EAAY5pE,EAAO7D,OACnB2tE,EAAa9pE,EAAO7D,MAAM3H,QAAUy1E,KAChCN,GACFA,EAAc3pE,EAAO7D,QAkCjB7F,IAAI,SAEN,+BAAQqZ,GAASgW,GAAQ/W,GACzB,yBACE5Y,UAAU,kBACVC,QAnCR,WACEg1C,GAA4BF,IAmCtB91B,KAAK,SACLC,SAAU,EACVnF,MAAM,8BAEN,uBAAG/Z,UAAW+0C,EAAoB,WAAa,sBAGlD8+B,GACC,kBAAC,IAAD,CAAQ5tE,KAAK,SAASI,QAAM,EAACujB,UAAWA,GACrCwqB,O","file":"3.048f19f68ad10b65610e.js","sourcesContent":["import { ApiMessage } from '../../../api/types';\nimport { MediaViewerOrigin } from '../../../types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { getMessageContent, getPhotoFullDimensions, getVideoDimensions } from '../../../modules/helpers';\nimport {\n AVATAR_FULL_DIMENSIONS,\n calculateDimensions,\n getMediaViewerAvailableDimensions,\n MEDIA_VIEWER_MEDIA_QUERY,\n REM,\n} from '../../common/helpers/mediaDimensions';\n\nimport windowSize from '../../../util/windowSize';\n\nconst ANIMATION_DURATION = 200;\n\nexport function animateOpening(\n hasFooter: boolean, origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage,\n) {\n const { mediaEl: fromImage } = getNodes(origin, message);\n if (!fromImage) {\n return;\n }\n\n const { width: windowWidth } = windowSize.get();\n\n let isVideo = false;\n let mediaSize;\n if (message) {\n const { photo, video, webPage } = getMessageContent(message);\n isVideo = Boolean(video);\n mediaSize = video ? getVideoDimensions(video)! : getPhotoFullDimensions((photo || webPage!.photo)!)!;\n } else {\n mediaSize = AVATAR_FULL_DIMENSIONS;\n }\n\n // eslint-disable-next-line max-len\n const {\n width: availableWidth, height: availableHeight,\n } = getMediaViewerAvailableDimensions(hasFooter, isVideo);\n const { width: toWidth, height: toHeight } = calculateDimensions(\n availableWidth, availableHeight, mediaSize.width, mediaSize.height,\n );\n const toLeft = (windowWidth - toWidth) / 2;\n const toTop = getTopOffset(hasFooter) + (availableHeight - toHeight) / 2;\n\n let {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n const uncovered = uncover(toWidth, toHeight, fromTop, fromLeft, fromWidth, fromHeight);\n fromTop = uncovered.top;\n fromLeft = uncovered.left;\n fromWidth = uncovered.width;\n fromHeight = uncovered.height;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n const fromScaleX = fromWidth / toWidth;\n const fromScaleY = fromHeight / toHeight;\n\n const ghost = createGhost(bestImageData || fromImage);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n applyShape(ghost, origin);\n\n document.body.classList.add('ghost-animating');\n\n requestAnimationFrame(() => {\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n clearShape(ghost);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (document.body.contains(ghost)) {\n document.body.removeChild(ghost);\n }\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nexport function animateClosing(origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage) {\n const { container, mediaEl: toImage } = getNodes(origin, message);\n if (!toImage) {\n return;\n }\n\n const fromImage = document.getElementById('MediaViewer')!.querySelector(\n '.active .media-viewer-content img, .active .media-viewer-content video',\n );\n if (!fromImage || !toImage) {\n return;\n }\n\n const {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n const {\n top: targetTop, left: toLeft, width: toWidth, height: toHeight,\n } = toImage.getBoundingClientRect();\n\n let toTop = targetTop;\n if (!isElementInViewport(container)) {\n const { height: windowHeight } = windowSize.get();\n toTop = targetTop < fromTop ? -toHeight : windowHeight;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n let fromScaleX = fromWidth / toWidth;\n let fromScaleY = fromHeight / toHeight;\n\n const shouldFadeOut = (\n [MediaViewerOrigin.Inline, MediaViewerOrigin.ScheduledInline].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n ) || (\n [MediaViewerOrigin.Album, MediaViewerOrigin.ScheduledAlbum].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n );\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n if (fromScaleX > fromScaleY) {\n fromScaleX = fromScaleY;\n } else if (fromScaleY > fromScaleX) {\n fromScaleY = fromScaleX;\n }\n }\n\n const existingGhost = document.getElementsByClassName('ghost')[0] as HTMLDivElement;\n\n const ghost = existingGhost || createGhost(bestImageData || toImage, origin === MediaViewerOrigin.ProfileAvatar);\n if (!existingGhost) {\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n }\n\n requestAnimationFrame(() => {\n if (existingGhost) {\n const {\n top,\n left,\n width,\n height,\n } = existingGhost.getBoundingClientRect();\n const scaleX = width / toWidth;\n const scaleY = height / toHeight;\n\n applyStyles(ghost, {\n transition: 'none',\n top: `${toTop}px`,\n left: `${toLeft}px`,\n transformOrigin: 'top left',\n transform: `translate3d(${left - toLeft}px, ${top - toTop}px, 0) scale(${scaleX}, ${scaleY})`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n });\n }\n document.body.classList.add('ghost-animating');\n if (!existingGhost) document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n if (existingGhost) {\n existingGhost.style.transition = '';\n }\n\n ghost.style.transform = '';\n\n if (shouldFadeOut) {\n ghost.style.opacity = '0';\n }\n\n applyShape(ghost, origin);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (document.body.contains(ghost)) {\n document.body.removeChild(ghost);\n }\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nfunction createGhost(source: string | HTMLImageElement | HTMLVideoElement, shouldAppendProfileInfo = false) {\n const ghost = document.createElement('div');\n ghost.classList.add('ghost');\n\n const img = new Image();\n\n if (typeof source === 'string') {\n img.src = source;\n } else if (source instanceof HTMLVideoElement) {\n img.src = source.poster;\n } else {\n img.src = source.src;\n }\n\n ghost.appendChild(img);\n\n if (shouldAppendProfileInfo) {\n ghost.classList.add('ProfileInfo');\n const profileInfo = document.querySelector('#RightColumn .ProfileInfo .info');\n if (profileInfo) {\n ghost.appendChild(profileInfo.cloneNode(true));\n }\n }\n\n return ghost;\n}\n\nfunction uncover(realWidth: number, realHeight: number, top: number, left: number, width: number, height: number) {\n if (realWidth === realHeight) {\n const size = Math.max(width, height) * (realWidth / realHeight);\n left -= (size - width) / 2;\n top -= (size - height) / 2;\n width = size;\n height = size;\n } else if (realWidth > realHeight) {\n const srcWidth = width;\n width = height * (realWidth / realHeight);\n left -= (width - srcWidth) / 2;\n } else if (realHeight > realWidth) {\n const srcHeight = height;\n height = width * (realHeight / realWidth);\n top -= (height - srcHeight) / 2;\n }\n\n return {\n top, left, width, height,\n };\n}\n\nfunction isElementInViewport(el: HTMLElement) {\n if (el.style.display === 'none') {\n return false;\n }\n\n const rect = el.getBoundingClientRect();\n const { height: windowHeight } = windowSize.get();\n\n return (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n}\n\nfunction isMessageImageFullyVisible(container: HTMLElement, imageEl: HTMLElement) {\n const messageListElement = document.querySelector('.active > .MessageList')!;\n let imgOffsetTop = container.offsetTop + imageEl.closest('.content-inner, .WebPage')!.offsetTop;\n if (container.id.includes('album-media-')) {\n imgOffsetTop += container.parentElement!.offsetTop + container.closest('.Message')!.offsetTop;\n }\n\n return imgOffsetTop > messageListElement.scrollTop\n && imgOffsetTop + imageEl.offsetHeight < messageListElement.scrollTop + messageListElement.offsetHeight;\n}\n\nfunction getTopOffset(hasFooter: boolean) {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n let topOffsetRem = 4.125;\n if (hasFooter) {\n topOffsetRem += mql.matches ? 0.875 : 3.375;\n }\n\n return topOffsetRem * REM;\n}\n\nfunction applyStyles(element: HTMLElement, styles: Record) {\n Object.assign(element.style, styles);\n}\n\nfunction getNodes(origin: MediaViewerOrigin, message?: ApiMessage) {\n let containerSelector;\n let mediaSelector;\n\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n containerSelector = `.active > .MessageList #album-media-${message!.id}`;\n mediaSelector = '.full-media';\n break;\n\n case MediaViewerOrigin.SharedMedia:\n containerSelector = `#shared-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.SearchResult:\n containerSelector = `#search-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n containerSelector = '.MiddleHeader .ChatInfo .Avatar';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ProfileAvatar:\n containerSelector = '#RightColumn .ProfileInfo .active .ProfilePhoto';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ScheduledInline:\n case MediaViewerOrigin.Inline:\n default:\n containerSelector = `.active > .MessageList #message${message!.id}`;\n mediaSelector = '.message-content .full-media, .message-content .thumbnail';\n }\n\n const container = document.querySelector(containerSelector)!;\n const mediaEls = container && container.querySelectorAll(mediaSelector);\n\n return {\n container,\n mediaEl: mediaEls && mediaEls[mediaEls.length - 1],\n };\n}\n\nfunction applyShape(ghost: HTMLDivElement, origin: MediaViewerOrigin) {\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n case MediaViewerOrigin.Inline:\n case MediaViewerOrigin.ScheduledInline:\n ghost.classList.add('rounded-corners');\n break;\n\n case MediaViewerOrigin.SharedMedia:\n case MediaViewerOrigin.ProfileAvatar:\n case MediaViewerOrigin.SearchResult:\n (ghost.firstChild as HTMLElement).style.objectFit = 'cover';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n ghost.classList.add('circle');\n break;\n }\n}\n\nfunction clearShape(ghost: HTMLDivElement) {\n (ghost.firstChild as HTMLElement).style.objectFit = 'default';\n ghost.classList.remove('rounded-corners', 'circle');\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../api/types';\n\nimport { getSenderTitle, isChatPrivate } from '../../modules/helpers';\nimport { formatMediaDateTime } from '../../util/dateFormat';\nimport renderText from '../common/helpers/renderText';\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectUser,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from '../common/Avatar';\n\nimport './SenderInfo.scss';\n\ntype OwnProps = {\n chatId?: number;\n messageId?: number;\n isAvatar?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick;\n\nconst SenderInfo: FC = ({\n chatId, messageId, sender, isAvatar, message, closeMediaViewer, focusMessage,\n}) => {\n const handleFocusMessage = useCallback(() => {\n closeMediaViewer();\n focusMessage({ chatId, messageId });\n }, [chatId, focusMessage, messageId, closeMediaViewer]);\n\n const lang = useLang();\n\n if (!sender || (!message && !isAvatar)) {\n return undefined;\n }\n\n const isFromChat = sender.id < 0;\n const senderTitle = getSenderTitle(lang, sender);\n\n return (\n
\n {isFromChat ? (\n \n ) : (\n \n )}\n
\n
\n {senderTitle && renderText(senderTitle)}\n
\n
\n {isAvatar ? lang('lng_mediaview_profile_photo') : formatMediaDateTime(lang, message!.date * 1000)}\n
\n
\n
\n );\n};\n\nexport default withGlobal(\n (global, { chatId, messageId, isAvatar }): StateProps => {\n if (isAvatar && chatId) {\n return {\n sender: isChatPrivate(chatId) ? selectUser(global, chatId) : selectChat(global, chatId),\n };\n }\n\n if (!messageId || !chatId) {\n return {};\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n message,\n sender: message && selectSender(global, message),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['closeMediaViewer', 'focusMessage']),\n)(SenderInfo);\n","import React, {\n FC, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport download from '../../util/download';\nimport { getMessageMediaHash } from '../../modules/helpers';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './MediaViewerActions.scss';\n\ntype OwnProps = {\n mediaData?: string;\n isVideo: boolean;\n isZoomed: boolean;\n message?: ApiMessage;\n fileName?: string;\n isAvatar?: boolean;\n onCloseMediaViewer: NoneToVoidFunction;\n onForward: NoneToVoidFunction;\n onZoomToggle: NoneToVoidFunction;\n};\n\nconst MediaViewerActions: FC = ({\n mediaData,\n isVideo,\n isZoomed,\n message,\n fileName,\n isAvatar,\n onCloseMediaViewer,\n onForward,\n onZoomToggle,\n}) => {\n const [isVideoDownloadAllowed, setIsVideoDownloadAllowed] = useState(false);\n const videoMediaHash = isVideo && message ? getMessageMediaHash(message, 'download') : undefined;\n const {\n mediaData: videoBlobUrl, downloadProgress,\n } = useMediaWithDownloadProgress(videoMediaHash, !isVideoDownloadAllowed);\n\n // Download with browser when fully loaded\n useEffect(() => {\n if (isVideoDownloadAllowed && videoBlobUrl) {\n download(videoBlobUrl, fileName!);\n setIsVideoDownloadAllowed(false);\n }\n }, [fileName, videoBlobUrl, isVideoDownloadAllowed]);\n\n // Cancel download on slide change\n useEffect(() => {\n setIsVideoDownloadAllowed(false);\n }, [videoMediaHash]);\n\n const handleVideoDownloadClick = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n setIsVideoDownloadAllowed((isAllowed) => !isAllowed);\n }, []);\n\n const lang = useLang();\n\n const MenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n \n \n \n );\n }, []);\n\n if (IS_MOBILE_SCREEN) {\n return (\n
\n \n {!isAvatar && (\n \n {lang('Forward')}\n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? `${Math.round(downloadProgress * 100)}% Downloading...` : 'Download'}\n \n ) : (\n \n {lang('AccActionDownload')}\n \n )}\n \n {isVideoDownloadAllowed && }\n
\n );\n }\n\n return (\n
\n {!isAvatar && (\n <>\n \n \n \n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? (\n \n ) : (\n \n )}\n \n ) : (\n \n \n \n )}\n \n \n \n \n \n \n
\n );\n};\n\nexport default MediaViewerActions;\n","import React, { FC, useEffect, useState } from '../../lib/teact/teact';\nimport { throttle } from '../../util/schedulers';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport { REM } from '../common/helpers/mediaDimensions';\n\nimport './MediaViewerFooter.scss';\n\nconst RESIZE_THROTTLE_MS = 500;\n\ntype OwnProps = {\n text: TextPart | TextPart[];\n onClick: () => void;\n isHideable: boolean;\n};\n\nconst MediaViewerFooter: FC = ({ text = '', isHideable, onClick }) => {\n const [isMultiline, setIsMultiline] = useState(false);\n useEffect(() => {\n const footerContent = document.querySelector('.MediaViewerFooter .media-text') as HTMLDivElement | null;\n\n const checkIsMultiline = () => {\n const height = footerContent ? footerContent.clientHeight : 0;\n\n setIsMultiline(height > REM * 2);\n };\n\n // First run for initial detection of multiline footer text\n checkIsMultiline();\n\n const handleResize = throttle(checkIsMultiline, RESIZE_THROTTLE_MS, true);\n\n window.addEventListener('resize', handleResize, false);\n\n return () => {\n window.removeEventListener('resize', handleResize, false);\n };\n }, []);\n\n function stopEvent(e: React.MouseEvent) {\n if (text) {\n e.stopPropagation();\n }\n }\n\n return (\n
\n {text && (\n
\n

{text}

\n
\n )}\n
\n );\n};\n\nexport default MediaViewerFooter;\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\nimport { PLATFORM_ENV } from '../util/environment';\n\ntype RefType = {\n current: HTMLElement | null;\n};\n\ntype ReturnType = [boolean, () => void, () => void] | [false];\ntype CallbackType = (isPlayed: boolean) => void;\n\nconst prop = getBrowserFullscreenElementProp();\n\nexport default function useFullscreenStatus(elRef: RefType, setIsPlayed: CallbackType): ReturnType {\n const [isFullscreen, setIsFullscreen] = useState(Boolean(prop && document[prop]));\n\n const setFullscreen = () => {\n if (!elRef.current || !(prop || PLATFORM_ENV === 'iOS')) {\n return;\n }\n\n if (elRef.current.requestFullscreen) {\n elRef.current.requestFullscreen();\n } else if (elRef.current.webkitRequestFullscreen) {\n elRef.current.webkitRequestFullscreen();\n } else if (elRef.current.webkitEnterFullscreen) {\n elRef.current.webkitEnterFullscreen();\n } else if (elRef.current.mozRequestFullScreen) {\n elRef.current.mozRequestFullScreen();\n }\n\n setIsFullscreen(true);\n };\n\n const exitFullscreen = () => {\n if (!elRef.current) {\n return;\n }\n\n if (document.exitFullscreen) {\n document.exitFullscreen();\n } else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n } else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n } else if (document.webkitExitFullscreen) {\n document.webkitExitFullscreen();\n }\n\n setIsFullscreen(false);\n };\n\n useLayoutEffect(() => {\n const listener = () => { setIsFullscreen(Boolean(prop && document[prop])); };\n const listenerEnter = () => { setIsFullscreen(true); };\n const listenerExit = () => {\n setIsFullscreen(false);\n setIsPlayed(false);\n };\n const video = elRef.current;\n\n document.addEventListener('fullscreenchange', listener, false);\n document.addEventListener('webkitfullscreenchange', listener, false);\n document.addEventListener('mozfullscreenchange', listener, false);\n\n if (video) {\n video.addEventListener('webkitbeginfullscreen', listenerEnter, false);\n video.addEventListener('webkitendfullscreen', listenerExit, false);\n }\n\n return () => {\n document.removeEventListener('fullscreenchange', listener, false);\n document.removeEventListener('webkitfullscreenchange', listener, false);\n document.removeEventListener('mozfullscreenchange', listener, false);\n if (video) {\n video.removeEventListener('webkitbeginfullscreen', listenerEnter, false);\n video.removeEventListener('webkitendfullscreen', listenerExit, false);\n }\n };\n // eslint-disable-next-line\n }, []);\n\n if (!prop && PLATFORM_ENV !== 'iOS') {\n return [false];\n }\n\n return [isFullscreen, setFullscreen, exitFullscreen];\n}\n\nfunction getBrowserFullscreenElementProp() {\n if (typeof document.fullscreenElement !== 'undefined') {\n return 'fullscreenElement';\n } else if (typeof document.mozFullScreenElement !== 'undefined') {\n return 'mozFullScreenElement';\n } else if (typeof document.webkitFullscreenElement !== 'undefined') {\n return 'webkitFullscreenElement';\n }\n\n return '';\n}\n","const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];\n\nexport default (bytes: number) => {\n const number = bytes === 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024));\n\n return `${(bytes / 1024 ** Math.floor(number)).toFixed(1)} ${units[number]}`;\n};\n","import React, { FC, useState, useEffect } from '../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { formatMediaDuration } from '../../util/dateFormat';\nimport formatFileSize from './helpers/formatFileSize';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './VideoPlayerControls.scss';\n\ntype IProps = {\n bufferedProgress: number;\n currentTime: number;\n duration: number;\n fileSize: number;\n isForceVisible: boolean;\n isForceMobileVersion?: boolean;\n isPlayed: boolean;\n isFullscreenSupported: boolean;\n isFullscreen: boolean;\n onChangeFullscreen: (e: React.MouseEvent) => void;\n onPlayPause: (e: React.MouseEvent) => void;\n onSeek: OnChangeHandler;\n};\n\ntype OnChangeHandler = (e: React.ChangeEvent) => void;\n\nconst stopEvent = (e: React.MouseEvent) => {\n e.stopPropagation();\n};\n\nconst HIDE_CONTROLS_TIMEOUT_MS = 800;\n\nconst VideoPlayerControls: FC = ({\n bufferedProgress,\n currentTime,\n duration,\n fileSize,\n isForceVisible,\n isForceMobileVersion,\n isPlayed,\n isFullscreenSupported,\n isFullscreen,\n onChangeFullscreen,\n onPlayPause,\n onSeek,\n}) => {\n const [isVisible, setVisibility] = useState(true);\n\n useEffect(() => {\n if (isForceVisible) {\n setVisibility(isForceVisible);\n }\n }, [isForceVisible]);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n if (!isForceVisible) {\n if (IS_MOBILE_SCREEN) {\n setVisibility(false);\n } else {\n timeout = window.setTimeout(() => {\n setVisibility(false);\n }, HIDE_CONTROLS_TIMEOUT_MS);\n }\n }\n\n return () => {\n if (timeout) {\n window.clearTimeout(timeout);\n }\n };\n }, [isForceVisible]);\n\n useEffect(() => {\n if (isVisible || isForceVisible) {\n document.body.classList.add('video-controls-visible');\n }\n\n return () => {\n document.body.classList.remove('video-controls-visible');\n };\n }, [isForceVisible, isVisible]);\n\n const lang = useLang();\n\n if (!isVisible && !isForceVisible) {\n return undefined;\n }\n\n return (\n
\n {renderSeekLine(currentTime, duration, bufferedProgress, onSeek)}\n \n \n \n {renderTime(currentTime, duration)}\n {bufferedProgress < 1 && renderFileSize(bufferedProgress, fileSize)}\n {isFullscreenSupported && (\n \n \n \n )}\n
\n );\n};\n\nfunction renderTime(currentTime: number, duration: number) {\n return (\n
\n {`${formatMediaDuration(currentTime)} / ${formatMediaDuration(duration)}`}\n
\n );\n}\n\nfunction renderFileSize(downloadedPercent: number, totalSize: number) {\n return (\n
\n {`${formatFileSize(totalSize * downloadedPercent)} / ${formatFileSize(totalSize)}`}\n
\n );\n}\n\nfunction renderSeekLine(currentTime: number, duration: number, bufferedProgress: number, onSeek: OnChangeHandler) {\n const percentagePlayed = (currentTime / duration) * 100;\n const percentageBuffered = bufferedProgress * 100;\n\n return (\n
\n
\n \n \n \n
\n
\n );\n}\n\nexport default VideoPlayerControls;\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { IDimensions } from '../../modules/helpers';\n\nimport { IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../util/environment';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBuffering from '../../hooks/useBuffering';\nimport useFullscreenStatus from '../../hooks/useFullscreen';\nimport useVideoCleanup from '../../hooks/useVideoCleanup';\nimport safePlay from '../../util/safePlay';\n\nimport VideoPlayerControls from './VideoPlayerControls';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './VideoPlayer.scss';\n\ntype OwnProps = {\n url?: string;\n isGif?: boolean;\n posterData?: string;\n posterSize?: IDimensions;\n downloadProgress?: number;\n fileSize: number;\n isMediaViewerOpen?: boolean;\n noPlay?: boolean;\n onClose: (e: React.MouseEvent) => void;\n};\n\nconst MOBILE_VERSION_CONTROL_WIDTH = 400;\n\nconst VideoPlayer: FC = ({\n url,\n isGif,\n posterData,\n posterSize,\n downloadProgress,\n fileSize,\n isMediaViewerOpen,\n noPlay,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n const [isPlayed, setIsPlayed] = useState(!IS_TOUCH_ENV || !IS_IOS);\n const [currentTime, setCurrentTime] = useState(0);\n const [isControlsVisible, setIsControlsVisible] = useState(true);\n\n const [isFullscreen, setFullscreen, exitFullscreen] = useFullscreenStatus(videoRef, setIsPlayed);\n\n const { isBuffered, bufferedProgress, bufferingHandlers } = useBuffering();\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(!isBuffered, undefined, undefined, 'slow');\n\n useEffect(() => {\n if (noPlay || !isMediaViewerOpen) {\n videoRef.current!.pause();\n } else if (url && !IS_TOUCH_ENV) {\n // Chrome does not automatically start playing when `url` becomes available (even with `autoPlay`),\n // so we force it here. Contrary, iOS does not allow to call `play` without mouse event,\n // so we need to use `autoPlay` instead to allow pre-buffering.\n safePlay(videoRef.current!);\n }\n }, [noPlay, isMediaViewerOpen, url]);\n\n useEffect(() => {\n if (videoRef.current!.currentTime === videoRef.current!.duration) {\n setCurrentTime(0);\n setIsPlayed(false);\n } else {\n setCurrentTime(videoRef.current!.currentTime);\n }\n }, [currentTime]);\n\n const togglePlayState = useCallback((e: React.MouseEvent | KeyboardEvent) => {\n e.stopPropagation();\n if (isPlayed) {\n videoRef.current!.pause();\n setIsPlayed(false);\n } else {\n videoRef.current!.play();\n setIsPlayed(true);\n }\n }, [isPlayed]);\n\n useVideoCleanup(videoRef, []);\n\n const handleMouseOver = useCallback(() => {\n setIsControlsVisible(true);\n }, []);\n\n const handleMouseOut = useCallback(() => {\n setIsControlsVisible(false);\n }, []);\n\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setCurrentTime(e.currentTarget.currentTime);\n }, []);\n\n const handleEnded = useCallback(() => {\n setCurrentTime(0);\n setIsPlayed(false);\n }, []);\n\n const handleFullscreenChange = useCallback(() => {\n if (isFullscreen && exitFullscreen) {\n exitFullscreen();\n } else if (!isFullscreen && setFullscreen) {\n setFullscreen();\n }\n }, [exitFullscreen, isFullscreen, setFullscreen]);\n\n const handleSeek = useCallback((e: React.ChangeEvent) => {\n e.stopPropagation();\n\n videoRef.current!.currentTime = (Number(e.target.value) * videoRef.current!.duration) / 100;\n }, []);\n\n const toggleControls = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n setIsControlsVisible(!isControlsVisible);\n }, [isControlsVisible]);\n\n useEffect(() => {\n const togglePayingStateBySpace = (e: KeyboardEvent) => {\n if (e.key === 'Enter' || e.key === ' ') {\n togglePlayState(e);\n }\n };\n\n document.addEventListener('keydown', togglePayingStateBySpace, false);\n\n return () => {\n document.removeEventListener('keydown', togglePayingStateBySpace, false);\n };\n }, [togglePlayState]);\n\n const wrapperStyle = posterSize && `width: ${posterSize.width}px; height: ${posterSize.height}px`;\n const videoStyle = `background-image: url(${posterData})`;\n\n return (\n \n \n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n {url && }\n \n \n {shouldRenderSpinner && (\n
\n {!isBuffered &&
Buffering...
}\n \n
\n )}\n {!isGif && !shouldRenderSpinner && (\n \n )}\n \n );\n};\n\nexport default memo(VideoPlayer);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport usePrevious from '../../hooks/usePrevious';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ZoomControls.scss';\n\ntype OwnProps = {\n isShown: boolean;\n onChangeZoom: (level: number, canCloseZoom?: boolean) => void;\n};\n\nexport const MAX_ZOOM_LEVEL = 3;\nexport const MIN_ZOOM_LEVEL = 1;\nconst ONE_STEP_PERCENT = 100 / (MAX_ZOOM_LEVEL - MIN_ZOOM_LEVEL);\nconst RESET_ZOOM_LEVEL = 1.5;\n\nconst ZoomControls: FC = ({ isShown, onChangeZoom }) => {\n const { transitionClassNames } = useShowTransition(isShown);\n const prevIsShown = usePrevious(isShown);\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const [zoomLevel, setZoomLevel] = useState(1);\n const isSeeking = useRef(false);\n\n useEffect(() => {\n if (isShown && !prevIsShown) {\n setZoomLevel(RESET_ZOOM_LEVEL);\n }\n }, [isShown, prevIsShown]);\n\n const handleZoomOut = () => {\n if (inputRef.current) {\n setZoomLevel(Math.max(MIN_ZOOM_LEVEL, zoomLevel - 0.5));\n }\n };\n\n const handleZoomIn = () => {\n if (inputRef.current) {\n setZoomLevel(Math.min(MAX_ZOOM_LEVEL, zoomLevel + 0.5));\n }\n };\n\n const handleStartSeek = useCallback(() => {\n isSeeking.current = true;\n }, []);\n\n const handleStopSeek = useCallback(() => {\n isSeeking.current = false;\n if (zoomLevel === 1) {\n onChangeZoom(zoomLevel, !isSeeking.current);\n }\n }, [onChangeZoom, zoomLevel]);\n\n const handleSeeklineChange = (e:React.ChangeEvent) => {\n setZoomLevel(Math.min(MAX_ZOOM_LEVEL, Math.max(Number(e.target.value), MIN_ZOOM_LEVEL)));\n };\n\n useEffect(() => {\n onChangeZoom(zoomLevel, !isSeeking.current);\n }, [zoomLevel, onChangeZoom]);\n\n const lang = useLang();\n\n const className = buildClassName(\n 'ZoomControls',\n transitionClassNames,\n );\n\n return (\n
\n \n \n \n \n \n \n
\n
\n \n \n
\n
\n
\n );\n};\n\nexport default memo(ZoomControls);\n","/*\n @source https://github.com/ajainarayanan/react-pan-zoom\n\n Heavily inspired/lifted from this idea: https://stackoverflow.com/a/39311435/661768\n without jqueryUI or jquery dependency.\n*/\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nimport './PanZoom.scss';\n\nexport interface IDragData {\n x: number;\n y: number;\n dx: number;\n dy: number;\n}\n\nexport interface OwnProps {\n children: any;\n className?: string;\n noWrap: boolean;\n canPan: boolean;\n zoomLevel: number;\n panDeltaX: number;\n panDeltaY: number;\n onPan?: (x: number, y: number) => void;\n}\n\nconst INITIAL_MATRIX = [\n 1, 0, 0, 1, 0, 0,\n];\n\nconst SCALE_VALUES = {\n 1: 1,\n 1.5: 1.5,\n 2: 2.2,\n 2.5: 3.3,\n 3: 5.5,\n};\n\nconst ZOOM_SAFE_AREA = 150;\n\nfunction calculateSafeZoneOnZoom(oldScale: number, matrixData: number[], wrapper: HTMLDivElement | null) {\n const image = wrapper && wrapper.querySelector('.active img');\n if (!wrapper || !image) {\n return matrixData;\n }\n const wrapperRect = wrapper.getBoundingClientRect();\n const imageRect = image.getBoundingClientRect();\n\n const newImgWidth = (imageRect.width / oldScale) * matrixData[0];\n const newImgHeight = (imageRect.height / oldScale) * matrixData[3];\n const newImgX = (wrapperRect.width - newImgWidth) / 2 + matrixData[4];\n const newImgY = (wrapperRect.height - newImgHeight) / 2 + matrixData[5];\n if (wrapperRect.width && wrapperRect.width - ZOOM_SAFE_AREA < newImgX) {\n matrixData[4] -= newImgX + wrapperRect.width - ZOOM_SAFE_AREA;\n } else if (newImgWidth && newImgWidth + newImgX < ZOOM_SAFE_AREA) {\n matrixData[4] -= newImgWidth + newImgX - ZOOM_SAFE_AREA;\n }\n if (wrapperRect.height && wrapperRect.height - ZOOM_SAFE_AREA < newImgY) {\n matrixData[5] -= newImgY + wrapperRect.height - ZOOM_SAFE_AREA;\n } else if (newImgHeight && newImgHeight + newImgY < ZOOM_SAFE_AREA) {\n matrixData[5] -= newImgHeight + newImgY - ZOOM_SAFE_AREA;\n }\n\n return matrixData;\n}\n\nconst PanZoom: FC = ({\n children,\n className,\n noWrap,\n canPan,\n zoomLevel,\n panDeltaX,\n panDeltaY,\n onPan,\n}) => {\n const tunedZoomLevel = SCALE_VALUES[zoomLevel as keyof typeof SCALE_VALUES] || zoomLevel;\n const [isDragging, setIsDragging] = useState(false);\n const [dragData, setDragData] = useState({\n dx: panDeltaX, dy: panDeltaY, x: 0, y: 0,\n });\n // [zoom, skew, skew, zoom, dx, dy] - see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix()\n const [matrixData, setMatrixData] = useState(INITIAL_MATRIX);\n // Used to set cursor while moving.\n // eslint-disable-next-line no-null/no-null\n const panWrapperRef = useRef(null);\n // Used to set transform for pan.\n // eslint-disable-next-line no-null/no-null\n const panContainerRef = useRef(null);\n\n useEffect(() => {\n const newZoomLevel = tunedZoomLevel || matrixData[0];\n const newPandx = panDeltaX || matrixData[4];\n const newPandy = panDeltaY || matrixData[5];\n\n const newMatrixData = [...matrixData];\n if (matrixData[0] !== newZoomLevel) {\n newMatrixData[0] = newZoomLevel || newMatrixData[0];\n newMatrixData[3] = newZoomLevel || newMatrixData[3];\n }\n if (matrixData[4] !== newPandx) {\n newMatrixData[4] = newPandx;\n }\n if (matrixData[5] !== newPandy) {\n newMatrixData[5] = newPandy;\n }\n\n if (!areSortedArraysEqual(matrixData, newMatrixData)) {\n setMatrixData(calculateSafeZoneOnZoom(matrixData[0], newMatrixData, panWrapperRef.current));\n }\n // eslint-disable-next-line\n }, [panDeltaX, panDeltaY, tunedZoomLevel]);\n\n useEffect(() => {\n if (!canPan) {\n setMatrixData(INITIAL_MATRIX);\n }\n }, [canPan]);\n\n useEffect(() => {\n if (panContainerRef.current) {\n panContainerRef.current.style.transform = `matrix(${matrixData.toString()})`;\n }\n }, [noWrap, matrixData]);\n\n const handleMouseDown = (e: React.MouseEvent) => {\n if (!canPan) {\n return;\n }\n\n e.stopPropagation();\n e.preventDefault();\n\n const offsetX = matrixData[4];\n const offsetY = matrixData[5];\n const newDragData: IDragData = {\n dx: offsetX,\n dy: offsetY,\n x: e.pageX,\n y: e.pageY,\n };\n setDragData(newDragData);\n setIsDragging(true);\n\n if (panWrapperRef.current) {\n panWrapperRef.current.classList.add('move');\n }\n };\n\n const handleMouseUp = () => {\n setIsDragging(false);\n\n if (panWrapperRef.current) {\n panWrapperRef.current.classList.remove('move');\n }\n\n if (onPan) {\n onPan(matrixData[4], matrixData[5]);\n }\n };\n\n function getNewMatrixData(x: number, y: number): number[] {\n const newMatrixData = [...matrixData];\n const deltaX = dragData.x - x;\n const deltaY = dragData.y - y;\n newMatrixData[4] = dragData.dx - deltaX;\n newMatrixData[5] = dragData.dy - deltaY;\n\n return newMatrixData;\n }\n\n const handleMouseMove = (e: React.MouseEvent) => {\n if (isDragging) {\n const newMatrixData = getNewMatrixData(e.pageX, e.pageY);\n setMatrixData(newMatrixData);\n\n if (panContainerRef.current) {\n panContainerRef.current.style.transform = `matrix(${matrixData.toString()})`;\n }\n }\n };\n\n if (noWrap) {\n return children;\n }\n\n return (\n \n \n {children}\n \n \n );\n};\n\nexport default memo(PanZoom);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../../api/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../util/environment';\nimport {\n AVATAR_FULL_DIMENSIONS,\n MEDIA_VIEWER_MEDIA_QUERY,\n calculateMediaViewerDimensions,\n} from '../common/helpers/mediaDimensions';\nimport {\n selectChat,\n selectChatMessage,\n selectChatMessages,\n selectCurrentMediaSearch,\n selectListedIds,\n selectOutlyingIds,\n selectScheduledMessage,\n selectScheduledMessages,\n selectUser,\n} from '../../modules/selectors';\nimport {\n getChatAvatarHash,\n getChatMediaMessageIds,\n getMessageMediaFilename,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageMediaThumbDataUri,\n getMessagePhoto,\n getMessageVideo,\n getMessageWebPagePhoto,\n getPhotoFullDimensions,\n getVideoDimensions,\n IDimensions,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { stopCurrentAudio } from '../../util/audioPlayer';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport useMedia from '../../hooks/useMedia';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useBlurSync from '../../hooks/useBlurSync';\nimport usePrevious from '../../hooks/usePrevious';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport { renderMessageText } from '../common/helpers/renderMessageText';\nimport { animateClosing, animateOpening } from './helpers/ghostAnimation';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\nimport ShowTransition from '../ui/ShowTransition';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport SenderInfo from './SenderInfo';\nimport MediaViewerActions from './MediaViewerActions';\nimport MediaViewerFooter from './MediaViewerFooter';\nimport VideoPlayer from './VideoPlayer';\nimport ZoomControls from './ZoomControls';\nimport PanZoom from './PanZoom';\n\nimport './MediaViewer.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageId?: number;\n senderId?: number;\n origin?: MediaViewerOrigin;\n avatarOwner?: ApiChat | ApiUser;\n profilePhotoIndex?: number;\n message?: ApiMessage;\n chatMessages?: Record;\n collectionIds?: number[];\n animationLevel: 0 | 1 | 2;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 350;\n\nconst MediaViewer: FC = ({\n chatId,\n threadId,\n messageId,\n senderId,\n origin,\n avatarOwner,\n profilePhotoIndex,\n message,\n chatMessages,\n collectionIds,\n openMediaViewer,\n closeMediaViewer,\n openForwardMenu,\n focusMessage,\n animationLevel,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const animationKey = useRef(null);\n const isOpen = Boolean(avatarOwner || messageId);\n const webPagePhoto = message ? getMessageWebPagePhoto(message) : undefined;\n const photo = message ? getMessagePhoto(message) : undefined;\n const video = message ? getMessageVideo(message) : undefined;\n const isWebPagePhoto = Boolean(webPagePhoto);\n const isPhoto = Boolean(photo || webPagePhoto);\n const isVideo = Boolean(video);\n const isGif = video ? video.isGif : undefined;\n const isFromSharedMedia = origin === MediaViewerOrigin.SharedMedia;\n const isFromSearch = origin === MediaViewerOrigin.SearchResult;\n const slideAnimation = animationLevel >= 1 ? 'mv-slide' : 'none';\n const headerAnimation = animationLevel === 2 ? 'slide-fade' : 'none';\n const isGhostAnimation = animationLevel === 2;\n const fileName = avatarOwner\n ? `avatar${avatarOwner.id}-${profilePhotoIndex}.jpg`\n : message && getMessageMediaFilename(message);\n const prevSenderId = usePrevious(senderId);\n const [canPanZoomWrap, setCanPanZoomWrap] = useState(false);\n const [isZoomed, setIsZoomed] = useState(false);\n const [zoomLevel, setZoomLevel] = useState(1);\n const [panDelta, setPanDelta] = useState({ x: 0, y: 0 });\n\n const messageIds = useMemo(() => {\n return isWebPagePhoto && messageId\n ? [messageId]\n : getChatMediaMessageIds(chatMessages || {}, collectionIds || [], isFromSharedMedia);\n }, [isWebPagePhoto, messageId, chatMessages, collectionIds, isFromSharedMedia]);\n\n const selectedMediaMessageIndex = messageId ? messageIds.indexOf(messageId) : -1;\n const isFirst = selectedMediaMessageIndex === 0 || selectedMediaMessageIndex === -1;\n const isLast = selectedMediaMessageIndex === messageIds.length - 1 || selectedMediaMessageIndex === -1;\n if (isOpen && (!prevSenderId || prevSenderId !== senderId || !animationKey.current)) {\n animationKey.current = selectedMediaMessageIndex;\n }\n\n function getMediaHash(full?: boolean) {\n if (avatarOwner && profilePhotoIndex !== undefined) {\n const { photos } = avatarOwner;\n return photos && photos[profilePhotoIndex]\n ? `photo${photos[profilePhotoIndex].id}?size=c`\n : getChatAvatarHash(avatarOwner, full ? 'big' : 'normal');\n }\n\n return message && getMessageMediaHash(message, full ? 'viewerFull' : 'viewerPreview');\n }\n\n const blobUrlPictogram = useMedia(\n message && (isFromSharedMedia || isFromSearch) && getMessageMediaHash(message, 'pictogram'),\n undefined,\n ApiMediaFormat.BlobUrl,\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n const previewMediaHash = getMediaHash();\n const blobUrlPreview = useMedia(\n previewMediaHash,\n undefined,\n avatarOwner && previewMediaHash && previewMediaHash.startsWith('profilePhoto')\n ? ApiMediaFormat.DataUri\n : ApiMediaFormat.BlobUrl,\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n const { mediaData: fullMediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMediaHash(true),\n undefined,\n message && getMessageMediaFormat(message, 'viewerFull'),\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n\n const localBlobUrl = (photo || video) ? (photo || video)!.blobUrl : undefined;\n let bestImageData = (!isVideo && (localBlobUrl || fullMediaData)) || blobUrlPreview || blobUrlPictogram;\n const thumbDataUri = useBlurSync(!bestImageData && message && getMessageMediaThumbDataUri(message));\n if (!bestImageData && origin !== MediaViewerOrigin.SearchResult) {\n bestImageData = thumbDataUri;\n }\n\n const photoDimensions = isPhoto ? getPhotoFullDimensions((\n isWebPagePhoto ? getMessageWebPagePhoto(message!) : getMessagePhoto(message!)\n )!) : undefined;\n const videoDimensions = isVideo ? getVideoDimensions(getMessageVideo(message!)!) : undefined;\n\n useEffect(() => {\n if (!IS_MOBILE_SCREEN) {\n return;\n }\n\n document.body.classList.toggle('is-media-viewer-open', isOpen);\n }, [isOpen]);\n\n const forceUpdate = useForceUpdate();\n useEffect(() => {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', forceUpdate);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(forceUpdate);\n }\n\n return () => {\n if (typeof mql.removeEventListener === 'function') {\n mql.removeEventListener('change', forceUpdate);\n } else if (typeof mql.removeListener === 'function') {\n mql.removeListener(forceUpdate);\n }\n };\n }, [forceUpdate]);\n\n const prevMessage = usePrevious(message);\n const prevOrigin = usePrevious(origin);\n const prevAvatarOwner = usePrevious(avatarOwner);\n const prevBestImageData = usePrevious(bestImageData);\n useEffect(() => {\n if (isGhostAnimation && isOpen && !prevMessage && !prevAvatarOwner) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n const textParts = message ? renderMessageText(message) : undefined;\n const hasFooter = Boolean(textParts);\n animateOpening(hasFooter, origin!, bestImageData!, message);\n }\n\n if (isGhostAnimation && !isOpen && (prevMessage || prevAvatarOwner)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n animateClosing(prevOrigin!, prevBestImageData!, prevMessage || undefined);\n }\n }, [\n isGhostAnimation, isOpen, origin, prevOrigin,\n message, prevMessage, prevAvatarOwner, bestImageData, prevBestImageData,\n ]);\n\n useEffect(() => {\n let timer: number | undefined;\n\n if (isZoomed) {\n setCanPanZoomWrap(true);\n } else {\n timer = window.setTimeout(() => {\n setCanPanZoomWrap(false);\n }, ANIMATION_DURATION);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [isZoomed]);\n\n const closeZoom = () => {\n setIsZoomed(false);\n setZoomLevel(1);\n setPanDelta({ x: 0, y: 0 });\n };\n\n const handleZoomToggle = useCallback(() => {\n setIsZoomed(!isZoomed);\n setZoomLevel(!isZoomed ? 1.5 : 1);\n if (isZoomed) {\n setPanDelta({ x: 0, y: 0 });\n }\n }, [isZoomed]);\n\n const handleZoomValue = useCallback((level: number, canCloseZoom = false) => {\n setZoomLevel(level);\n if (level === 1 && canCloseZoom) {\n closeZoom();\n }\n }, []);\n\n const close = useCallback(() => {\n closeMediaViewer();\n closeZoom();\n }, [closeMediaViewer]);\n\n const handleFooterClick = useCallback(() => {\n close();\n focusMessage({ chatId, threadId, messageId });\n }, [close, chatId, threadId, focusMessage, messageId]);\n\n const handleForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n closeZoom();\n }, [openForwardMenu, chatId, messageId]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(() => {\n if (isZoomed) {\n closeZoom();\n } else {\n close();\n }\n }) : undefined), [close, isOpen, isZoomed]);\n\n useEffect(() => {\n if (isVideo && !isGif) {\n stopCurrentAudio();\n }\n }, [isGif, isVideo]);\n\n const getMessageId = useCallback((fromId: number, direction: number): number => {\n let index = messageIds.indexOf(fromId);\n if ((direction === -1 && index > 0) || (direction === 1 && index < messageIds.length - 1)) {\n index += direction;\n }\n\n return messageIds[index];\n }, [messageIds]);\n\n const selectPreviousMedia = useCallback(() => {\n if (isFirst) {\n return;\n }\n\n openMediaViewer({\n chatId,\n threadId,\n messageId: messageId ? getMessageId(messageId, -1) : undefined,\n origin,\n });\n }, [chatId, threadId, getMessageId, isFirst, messageId, openMediaViewer, origin]);\n\n const selectNextMedia = useCallback(() => {\n if (isLast) {\n return;\n }\n\n openMediaViewer({\n chatId,\n threadId,\n messageId: messageId ? getMessageId(messageId, 1) : undefined,\n origin,\n });\n }, [chatId, threadId, getMessageId, isLast, messageId, openMediaViewer, origin]);\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n switch (e.key) {\n case 'Left': // IE/Edge specific value\n case 'ArrowLeft':\n selectPreviousMedia();\n break;\n\n case 'Right': // IE/Edge specific value\n case 'ArrowRight':\n selectNextMedia();\n break;\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n });\n\n // Support for swipe gestures and closing on click\n useEffect(() => {\n const element = document.querySelector('.slide-container > .active, .slide-container > .to');\n if (!element) {\n return undefined;\n }\n\n const shouldCloseOnVideo = isGif && !IS_IOS;\n\n return captureEvents(element, {\n // eslint-disable-next-line max-len\n excludedClosestSelector: `.backdrop, .navigation, .media-viewer-head, .media-viewer-footer${!shouldCloseOnVideo ? ', .VideoPlayer' : ''}`,\n onClick: () => {\n if (!isZoomed) {\n close();\n }\n },\n onSwipe: IS_TOUCH_ENV ? (e, direction) => {\n if (direction === SwipeDirection.Right) {\n selectPreviousMedia();\n } else if (direction === SwipeDirection.Left) {\n selectNextMedia();\n } else {\n close();\n }\n } : undefined,\n });\n }, [close, isGif, isZoomed, selectNextMedia, selectPreviousMedia, canPanZoomWrap]);\n\n const handlePan = useCallback((x: number, y: number) => {\n setPanDelta({ x, y });\n }, []);\n\n const lang = useLang();\n\n function renderSlide(isActive: boolean) {\n if (avatarOwner) {\n return (\n
\n {renderPhoto(\n fullMediaData || blobUrlPreview,\n calculateMediaViewerDimensions(AVATAR_FULL_DIMENSIONS, false),\n !IS_MOBILE_SCREEN && !isZoomed,\n )}\n
\n );\n } else if (message) {\n const textParts = renderMessageText(message);\n const hasFooter = Boolean(textParts);\n\n return (\n
\n {isPhoto && renderPhoto(\n localBlobUrl || fullMediaData || blobUrlPreview || blobUrlPictogram,\n message && calculateMediaViewerDimensions(photoDimensions!, hasFooter),\n !IS_MOBILE_SCREEN && !isZoomed,\n )}\n {isVideo && (\n \n )}\n {textParts && (\n \n )}\n
\n );\n }\n\n return undefined;\n }\n\n function renderSenderInfo() {\n return (\n \n );\n }\n\n return (\n \n {() => (\n <>\n
\n {IS_MOBILE_SCREEN && (\n \n \n \n )}\n \n {renderSenderInfo}\n \n \n
\n \n \n {renderSlide}\n \n \n {!isFirst && (\n \n )}\n {!isLast && (\n \n )}\n \n \n )}\n \n );\n};\n\nfunction renderPhoto(blobUrl?: string, imageSize?: IDimensions, canDrag?: boolean) {\n return blobUrl\n ? (\n \n )\n : (\n \n \n \n );\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = global.mediaViewer;\n const {\n animationLevel,\n } = global.settings.byKey;\n\n if (origin === MediaViewerOrigin.SearchResult) {\n if (!(chatId && messageId)) {\n return { animationLevel };\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n if (!message) {\n return { animationLevel };\n }\n\n return {\n chatId,\n messageId,\n senderId: message.senderId,\n origin,\n message,\n animationLevel,\n };\n }\n\n if (avatarOwnerId) {\n const sender = selectUser(global, avatarOwnerId) || selectChat(global, avatarOwnerId);\n\n return {\n messageId: -1,\n senderId: avatarOwnerId,\n avatarOwner: sender,\n profilePhotoIndex: profilePhotoIndex || 0,\n animationLevel,\n origin,\n };\n }\n\n if (!(chatId && threadId && messageId)) {\n return { animationLevel };\n }\n\n let message: ApiMessage | undefined;\n if (origin && [MediaViewerOrigin.ScheduledAlbum, MediaViewerOrigin.ScheduledInline].includes(origin)) {\n message = selectScheduledMessage(global, chatId, messageId);\n } else {\n message = selectChatMessage(global, chatId, messageId);\n }\n\n if (!message) {\n return { animationLevel };\n }\n\n let chatMessages: Record | undefined;\n\n if (origin && [MediaViewerOrigin.ScheduledAlbum, MediaViewerOrigin.ScheduledInline].includes(origin)) {\n chatMessages = selectScheduledMessages(global, chatId);\n } else {\n chatMessages = selectChatMessages(global, chatId);\n }\n let collectionIds: number[] | undefined;\n\n if (origin === MediaViewerOrigin.Inline || origin === MediaViewerOrigin.Album) {\n collectionIds = selectOutlyingIds(global, chatId, threadId) || selectListedIds(global, chatId, threadId);\n } else if (origin === MediaViewerOrigin.SharedMedia) {\n const currentSearch = selectCurrentMediaSearch(global);\n const { foundIds } = (currentSearch && currentSearch.resultsByType && currentSearch.resultsByType.media) || {};\n collectionIds = foundIds;\n }\n\n return {\n chatId,\n threadId,\n messageId,\n senderId: message.senderId,\n origin,\n message,\n chatMessages,\n collectionIds,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openMediaViewer', 'closeMediaViewer', 'openForwardMenu', 'focusMessage',\n ]),\n)(MediaViewer));\n","import React, {\n FC, useMemo, useState, memo, useRef, useEffect, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, MAIN_THREAD_ID } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n getCanPostInChat, getChatTitle, isChatPrivate, sortChatIds,\n} from '../../modules/helpers';\nimport searchWords from '../../util/searchWords';\nimport { pick } from '../../util/iteratees';\nimport useInfiniteScroll from '../../hooks/useInfiniteScroll';\nimport useLang from '../../hooks/useLang';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\n\nimport Loading from '../ui/Loading';\nimport Modal from '../ui/Modal';\nimport InputText from '../ui/InputText';\nimport Button from '../ui/Button';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\n\nimport './ForwardPicker.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n};\n\ntype StateProps = {\n chatsById: Record;\n activeListIds?: number[];\n archivedListIds?: number[];\n orderedPinnedIds?: number[];\n currentUserId?: number;\n};\n\ntype DispatchProps = Pick;\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\nconst MODAL_HIDE_DELAY_MS = 300;\n\nconst ForwardPicker: FC = ({\n chatsById,\n activeListIds,\n archivedListIds,\n currentUserId,\n isOpen,\n setForwardChatId,\n exitForwardMode,\n loadMoreChats,\n}) => {\n const [filter, setFilter] = useState('');\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (isOpen) {\n if (!IS_MOBILE_SCREEN) {\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (inputRef.current) {\n inputRef.current.focus();\n }\n });\n }, FOCUS_DELAY_MS);\n }\n } else {\n if (inputRef.current) {\n inputRef.current.blur();\n }\n\n setTimeout(() => {\n setFilter('');\n }, MODAL_HIDE_DELAY_MS);\n }\n }, [isOpen]);\n\n const chatIds = useMemo(() => {\n const listIds = [\n ...activeListIds || [],\n ...archivedListIds || [],\n ];\n\n return sortChatIds([\n ...listIds.filter((id) => {\n const chat = chatsById[id];\n if (!chat) {\n return true;\n }\n\n if (!getCanPostInChat(chat, MAIN_THREAD_ID)) {\n return false;\n }\n\n if (!filter) {\n return true;\n }\n\n return searchWords(getChatTitle(lang, chatsById[id], undefined, id === currentUserId), filter);\n }),\n ], chatsById, undefined, currentUserId ? [currentUserId] : undefined);\n }, [activeListIds, archivedListIds, chatsById, currentUserId, filter, lang]);\n\n const [viewportIds, getMore] = useInfiniteScroll(loadMoreChats, chatIds, Boolean(filter));\n\n const handleFilterChange = useCallback((e: React.ChangeEvent) => {\n setFilter(e.currentTarget.value);\n }, []);\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, isOpen, (index) => {\n if (viewportIds) {\n setForwardChatId({ id: viewportIds[index] });\n }\n }, '.ListItem-button', true);\n\n const modalHeader = (\n
\n \n \n \n \n
\n );\n\n return (\n \n {viewportIds && viewportIds.length ? (\n \n {viewportIds.map((id) => (\n setForwardChatId({ id })}\n >\n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n ))}\n \n ) : viewportIds && !viewportIds.length ? (\n

Sorry, nothing found.

\n ) : (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n },\n currentUserId,\n } = global;\n\n return {\n chatsById,\n activeListIds: listIds.active,\n archivedListIds: listIds.archived,\n currentUserId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setForwardChatId', 'exitForwardMode', 'loadMoreChats']),\n)(ForwardPicker));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiError } from '../../api/types';\n\nimport getReadableErrorText from '../../util/getReadableErrorText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './Errors.scss';\n\ntype StateProps = {\n errors: ApiError[];\n};\n\ntype DispatchProps = Pick;\n\nconst Errors: FC = ({ errors, dismissError }) => {\n const lang = useLang();\n\n if (!errors.length) {\n return undefined;\n }\n\n return (\n
\n {errors.map((error) => (\n \n

{getReadableErrorText(error)}

\n \n \n ))}\n
\n );\n};\n\nfunction getErrorHeader(error: ApiError) {\n if (error.isSlowMode) {\n return 'Slowmode enabled';\n }\n\n return 'Something went wrong';\n}\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['errors']),\n (setGlobal, actions): DispatchProps => pick(actions, ['dismissError']),\n)(Errors));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiNotification } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport Notification from '../ui/Notification';\nimport renderText from '../common/helpers/renderText';\n\ntype StateProps = {\n notifications: ApiNotification[];\n};\n\ntype DispatchProps = Pick;\n\nconst Notifications: FC = ({ notifications, dismissNotification }) => {\n if (!notifications.length) {\n return undefined;\n }\n\n return (\n
\n {notifications.map(({ message }) => (\n \n ))}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['notifications']),\n (setGlobal, actions): DispatchProps => pick(actions, ['dismissNotification']),\n)(Notifications));\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\n\nexport type OwnProps = {\n url?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLinkModal: FC = ({ url, toggleSafeLinkModal }) => {\n const lang = useLang();\n\n const handleOpen = useCallback(() => {\n window.open(url);\n toggleSafeLinkModal({ url: undefined });\n }, [toggleSafeLinkModal, url]);\n\n const handleDismiss = useCallback(() => {\n toggleSafeLinkModal({ url: undefined });\n }, [toggleSafeLinkModal]);\n\n const renderingUrl = useCurrentOrPrev(url);\n\n return (\n \n );\n};\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['toggleSafeLinkModal']),\n)(SafeLinkModal));\n","import React, {\n FC, memo, useState, useEffect, useMemo, useCallback,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport {\n formatMonthAndYear, formatHumanDate, formatTime,\n} from '../../util/dateFormat';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './CalendarModal.scss';\n\nexport type OwnProps = {\n selectedAt?: number;\n maxAt?: number;\n isFutureMode?: boolean;\n isPastMode?: boolean;\n isOpen: boolean;\n withTimePicker?: boolean;\n submitButtonLabel?: string;\n secondButtonLabel?: string;\n onClose: () => void;\n onSubmit: (date: Date) => void;\n onSecondButtonClick?: NoneToVoidFunction;\n};\n\nconst WEEKDAY_LETTERS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];\n\nconst CalendarModal: FC = ({\n selectedAt,\n maxAt,\n isFutureMode,\n isPastMode,\n isOpen,\n withTimePicker,\n submitButtonLabel,\n secondButtonLabel,\n onClose,\n onSubmit,\n onSecondButtonClick,\n}) => {\n const lang = useLang();\n const now = new Date();\n const defaultSelectedDate = useMemo(() => (selectedAt ? new Date(selectedAt) : new Date()), [selectedAt]);\n const maxDate = maxAt ? new Date(maxAt) : undefined;\n\n const [selectedDate, setSelectedDate] = useState(defaultSelectedDate);\n const [selectedHours, setSelectedHours] = useState(\n formatInputTime(defaultSelectedDate.getHours()),\n );\n const [selectedMinutes, setSelectedMinutes] = useState(\n formatInputTime(defaultSelectedDate.getMinutes()),\n );\n\n const currentYear = selectedDate.getFullYear();\n const currentMonth = selectedDate.getMonth();\n const currentDate = selectedDate.getDate();\n\n useEffect(() => {\n if (isOpen) {\n setSelectedDate(defaultSelectedDate);\n }\n }, [isOpen, defaultSelectedDate]);\n\n const shouldDisableNextMonth = (isPastMode && currentYear >= now.getFullYear() && currentMonth >= now.getMonth())\n || (maxDate && currentYear >= maxDate.getFullYear() && currentMonth >= maxDate.getMonth());\n const shouldDisablePrevMonth = isFutureMode && currentYear <= now.getFullYear() && currentMonth <= now.getMonth();\n\n const calendarGrid = useMemo(() => (\n buildCalendarGrid(currentYear, currentMonth)\n ), [currentMonth, currentYear]);\n\n function handlePrevMonth() {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setMonth(dateCopy.getMonth() - 1);\n\n return dateCopy;\n });\n }\n\n function handleNextMonth() {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setMonth(dateCopy.getMonth() + 1);\n\n return dateCopy;\n });\n }\n\n function handleDateSelect(date: number) {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setDate(date);\n\n return dateCopy;\n });\n }\n\n function handleSubmit() {\n onSubmit(selectedDate);\n }\n\n const handleChangeHours = useCallback((e: React.ChangeEvent) => {\n const value = e.target.value.replace(/[^\\d]+/g, '');\n if (!value.length) {\n setSelectedHours('');\n e.target.value = '';\n return;\n }\n\n const hours = Math.max(0, Math.min(Number(value), 23));\n\n const date = new Date(selectedDate.getTime());\n date.setHours(hours);\n setSelectedDate(date);\n\n const hoursStr = formatInputTime(hours);\n setSelectedHours(hoursStr);\n e.target.value = hoursStr;\n }, [selectedDate]);\n\n const handleChangeMinutes = useCallback((e: React.ChangeEvent) => {\n const value = e.target.value.replace(/[^\\d]+/g, '');\n if (!value.length) {\n setSelectedMinutes('');\n e.target.value = '';\n return;\n }\n\n const minutes = Math.max(0, Math.min(Number(value), 59));\n\n const date = new Date(selectedDate.getTime());\n date.setMinutes(minutes);\n setSelectedDate(date);\n\n const minutesStr = formatInputTime(minutes);\n setSelectedMinutes(minutesStr);\n e.target.value = minutesStr;\n }, [selectedDate]);\n\n function renderTimePicker() {\n return (\n
\n \n :\n \n
\n );\n }\n\n return (\n \n
\n
\n \n \n \n\n

\n {formatMonthAndYear(lang, selectedDate, IS_MOBILE_SCREEN)}\n

\n\n \n \n \n\n \n \n \n
\n
\n\n
\n
\n {WEEKDAY_LETTERS.map((letter) => (\n
\n {letter}\n
\n ))}\n {calendarGrid.map((gridDate) => (\n handleDateSelect(gridDate)}\n className={buildClassName(\n 'day-button',\n isDisabledDay(\n currentYear, currentMonth, gridDate, isFutureMode ? now : undefined, isPastMode ? now : maxDate,\n )\n ? 'disabled'\n : `${gridDate ? 'clickable' : ''}`,\n gridDate === currentDate && 'selected',\n )}\n >\n {!!gridDate && (\n {gridDate}\n )}\n
\n ))}\n
\n \n\n {withTimePicker && renderTimePicker()}\n\n
\n \n {secondButtonLabel && (\n \n )}\n
\n \n );\n};\n\nfunction buildCalendarGrid(year: number, month: number) {\n const grid: number[] = [];\n\n const date = new Date();\n date.setFullYear(year);\n date.setMonth(month);\n date.setDate(1);\n\n const monthStartDay = date.getDay();\n // Fill empty cells\n for (let i = 1; i < monthStartDay; i++) {\n grid.push(0);\n }\n\n while (date.getMonth() === month) {\n const gridDate = date.getDate();\n grid.push(gridDate);\n date.setDate(gridDate + 1);\n }\n\n return grid;\n}\n\nfunction isDisabledDay(year: number, month: number, day: number, minDate?: Date, maxDate?: Date) {\n const selectedDay = new Date(year, month, day, 0, 0, 0, 0);\n const fixedMinDate = minDate && new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate(), 0, 0, 0, 0);\n const fixedMaxDate = maxDate && new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 0, 0, 0, 0);\n\n if (fixedMaxDate && selectedDay > fixedMaxDate) {\n return true;\n } else if (fixedMinDate && selectedDay < fixedMinDate) {\n return true;\n }\n\n return false;\n}\n\nfunction formatInputTime(value: string | number) {\n return String(value).padStart(2, '0');\n}\n\nfunction formatSubmitLabel(lang: LangFn, date: Date) {\n const day = formatHumanDate(lang, date, true);\n\n if (day === 'Today') {\n return lang('Conversation.ScheduleMessage.SendToday', formatTime(date));\n }\n\n return lang('Conversation.ScheduleMessage.SendOn', day).replace('%@', formatTime(date));\n}\n\nexport default memo(CalendarModal);\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../api/types';\nimport { IAlbum } from '../../types';\n\nimport { GlobalActions } from '../../global/types';\n\nimport {\n selectAllowedMessageActions,\n selectChat,\n selectCurrentMessageList,\n selectUser,\n} from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n isSchedule: boolean;\n message: ApiMessage;\n album?: IAlbum;\n onClose: () => void;\n};\n\ntype StateProps = {\n canDeleteForAll?: boolean;\n contactName?: string;\n willDeleteForCurrentUserOnly?: boolean;\n willDeleteForAll?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst DeleteMessageModal: FC = ({\n isOpen,\n isSchedule,\n message,\n album,\n canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n onClose,\n deleteMessages,\n deleteScheduledMessages,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n const messageIds = album && album.messages\n ? album.messages.map(({ id }) => id)\n : [message.id];\n deleteMessages({ messageIds, shouldDeleteForAll: true });\n onClose();\n }, [deleteMessages, message.id, onClose, album]);\n\n const handleDeleteMessageForSelf = useCallback(() => {\n const messageIds = album && album.messages\n ? album.messages.map(({ id }) => id)\n : [message.id];\n if (isSchedule) {\n deleteScheduledMessages({ messageIds });\n } else {\n deleteMessages({\n messageIds,\n shouldDeleteForAll: false,\n });\n }\n onClose();\n }, [album, message.id, isSchedule, onClose, deleteScheduledMessages, deleteMessages]);\n\n const lang = useLang();\n\n return (\n \n

{lang('AreYouSureDeleteSingleMessage')}

\n {willDeleteForCurrentUserOnly && (\n

{lang('lng_delete_for_me_chat_hint')}

\n )}\n {willDeleteForAll && (\n

{lang('lng_delete_for_everyone_hint', 1, 'i')}

\n )}\n {canDeleteForAll && (\n \n )}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { message, isSchedule }): StateProps => {\n const { threadId } = selectCurrentMessageList(global) || {};\n const { canDeleteForAll } = (threadId && selectAllowedMessageActions(global, message, threadId)) || {};\n const chat = selectChat(global, message.chatId);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n const willDeleteForCurrentUserOnly = chat && isChatBasicGroup(chat) && !canDeleteForAll;\n const willDeleteForAll = chat && isChatSuperGroup(chat);\n\n return {\n canDeleteForAll: !isSchedule && canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'deleteMessages', 'deleteScheduledMessages',\n ]),\n)(DeleteMessageModal));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { selectChat, selectIsChatWithSelf, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n isChatChannel,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n chatId: number;\n messageId: number;\n onClose: () => void;\n};\n\ntype StateProps = {\n isChannel: boolean;\n isPrivateChat: boolean;\n isChatWithSelf: boolean;\n isGroup: boolean;\n isSuperGroup: boolean;\n canPinForAll: boolean;\n contactName?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst PinMessageModal: FC = ({\n isOpen,\n messageId,\n chatId,\n isChannel,\n isGroup,\n isSuperGroup,\n canPinForAll,\n contactName,\n onClose,\n pinMessage,\n}) => {\n const handlePinMessageForAll = useCallback(() => {\n pinMessage({\n chatId, messageId, isUnpin: false,\n });\n onClose();\n }, [pinMessage, chatId, messageId, onClose]);\n\n const handlePinMessage = useCallback(() => {\n pinMessage({\n chatId, messageId, isUnpin: false, isOneSide: true, isSilent: true,\n });\n onClose();\n }, [chatId, messageId, onClose, pinMessage]);\n\n const lang = useLang();\n\n function renderMessage() {\n if (isChannel) {\n return lang('PinMessageAlertChannel');\n }\n\n if (isGroup || isSuperGroup) {\n return lang('PinMessageAlert');\n }\n\n return lang('PinMessageAlertChat');\n }\n\n return (\n \n

{renderMessage()}

\n \n {canPinForAll && (\n \n )}\n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const isPrivateChat = isChatPrivate(chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const chat = selectChat(global, chatId);\n const isChannel = !!chat && isChatChannel(chat);\n const isGroup = !!chat && isChatBasicGroup(chat);\n const isSuperGroup = !!chat && isChatSuperGroup(chat);\n const canPinForAll = (isPrivateChat && !isChatWithSelf) || isSuperGroup || isGroup;\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n return {\n isPrivateChat,\n isChatWithSelf,\n isChannel,\n isGroup,\n isSuperGroup,\n canPinForAll,\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['pinMessage']),\n)(PinMessageModal));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n chatId?: number;\n pinnedMessagesCount?: number;\n onClose: () => void;\n onUnpin: () => void;\n};\n\nconst UnpinAllMessagesModal: FC = ({\n isOpen,\n pinnedMessagesCount = 0,\n onClose,\n onUnpin,\n}) => {\n const lang = useLang();\n\n return (\n \n

{lang('Chat.UnpinAllMessagesConfirmation', pinnedMessagesCount, 'i')}

\n \n \n \n );\n};\n\nexport default memo(UnpinAllMessagesModal);\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { selectCanDeleteSelectedMessages, selectCurrentChat, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n isSchedule: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n selectedMessageIds?: number[];\n canDeleteForAll?: boolean;\n contactName?: string;\n willDeleteForCurrentUserOnly?: boolean;\n willDeleteForAll?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst DeleteSelectedMessagesModal: FC = ({\n isOpen,\n isSchedule,\n selectedMessageIds,\n canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n onClose,\n deleteMessages,\n deleteScheduledMessages,\n exitMessageSelectMode,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n deleteMessages({ messageIds: selectedMessageIds, shouldDeleteForAll: true });\n exitMessageSelectMode();\n onClose();\n }, [deleteMessages, exitMessageSelectMode, selectedMessageIds, onClose]);\n\n const handleDeleteMessageForSelf = useCallback(() => {\n if (isSchedule) {\n deleteScheduledMessages({ messageIds: selectedMessageIds });\n } else {\n deleteMessages({ messageIds: selectedMessageIds, shouldDeleteForAll: false });\n }\n\n exitMessageSelectMode();\n onClose();\n }, [\n isSchedule, exitMessageSelectMode, onClose, deleteScheduledMessages, selectedMessageIds, deleteMessages,\n ]);\n\n const lang = useLang();\n\n if (!selectedMessageIds) {\n return undefined;\n }\n\n return (\n \n

{lang('AreYouSureDeleteFewMessages')}

\n {willDeleteForCurrentUserOnly && (\n

This will delete them just for you, not for other participants in the chat.

\n )}\n {willDeleteForAll && (\n

This will delete them for everyone in this chat.

\n )}\n {canDeleteForAll && (\n \n )}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { isSchedule }): StateProps => {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { canDeleteForAll } = selectCanDeleteSelectedMessages(global);\n const chat = selectCurrentChat(global);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n const willDeleteForCurrentUserOnly = chat && isChatBasicGroup(chat) && !canDeleteForAll;\n const willDeleteForAll = chat && isChatSuperGroup(chat);\n\n return {\n selectedMessageIds,\n canDeleteForAll: !isSchedule && canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'deleteMessages',\n 'deleteScheduledMessages',\n 'exitMessageSelectMode',\n ]),\n)(DeleteSelectedMessagesModal));\n","import React, { FC, memo, useEffect } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\n\nimport {\n selectCanDeleteSelectedMessages,\n selectCurrentMessageList,\n selectSelectedMessagesCount,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useFlag from '../../hooks/useFlag';\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport buildClassName from '../../util/buildClassName';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport MenuItem from '../ui/MenuItem';\n\nimport DeleteSelectedMessagesModal from './DeleteSelectedMessagesModal';\n\nimport './MessageSelectToolbar.scss';\n\nexport type OwnProps = {\n isActive?: boolean;\n canPost?: boolean;\n messageListType?: MessageListType;\n};\n\ntype StateProps = {\n isSchedule: boolean;\n selectedMessagesCount?: number;\n canDeleteMessages?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageSelectToolbar: FC = ({\n canPost,\n isActive,\n messageListType,\n isSchedule,\n selectedMessagesCount,\n canDeleteMessages,\n exitMessageSelectMode,\n openForwardMenuForSelectedMessages,\n}) => {\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n useEffect(() => {\n return isActive && !isDeleteModalOpen\n ? captureKeyboardListeners({\n onBackspace: openDeleteModal,\n onDelete: openDeleteModal,\n onEsc: exitMessageSelectMode,\n })\n : undefined;\n }, [isActive, isDeleteModalOpen, openDeleteModal, exitMessageSelectMode]);\n\n const prevSelectedMessagesCount = usePrevious(selectedMessagesCount || undefined, true);\n const renderingSelectedMessagesCount = isActive ? selectedMessagesCount : prevSelectedMessagesCount;\n\n const lang = useLang();\n\n const formattedMessagesCount = lang('VoiceOver.Chat.MessagesSelected', renderingSelectedMessagesCount);\n\n const className = buildClassName(\n 'MessageSelectToolbar',\n canPost && 'with-composer',\n isActive && 'shown',\n );\n\n return (\n
\n
\n \n \n \n \n {formattedMessagesCount}\n \n\n {!!selectedMessagesCount && (\n
\n {messageListType !== 'scheduled' && (\n \n \n {lang('Forward')}\n \n \n )}\n \n \n {lang('Delete')}\n \n \n
\n )}\n
\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { type: messageListType } = selectCurrentMessageList(global) || {};\n const { canDelete } = selectCanDeleteSelectedMessages(global);\n\n return {\n isSchedule: messageListType === 'scheduled',\n selectedMessagesCount: selectSelectedMessagesCount(global),\n canDeleteMessages: canDelete,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['exitMessageSelectMode', 'openForwardMenuForSelectedMessages']),\n)(MessageSelectToolbar));\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nexport default (\n onSelect: NoneToVoidFunction,\n) => {\n // eslint-disable-next-line no-null/no-null\n const buttonRef = useRef(null);\n\n const handleKeyDown = useCallback((e: KeyboardEvent) => {\n if (e.key !== 'Enter') return;\n const isFocused = buttonRef.current === document.activeElement;\n\n if (isFocused) {\n onSelect();\n }\n }, [onSelect]);\n\n useEffect(() => {\n window.addEventListener('keydown', handleKeyDown, false);\n\n return () => window.removeEventListener('keydown', handleKeyDown);\n }, [handleKeyDown]);\n\n return buttonRef;\n};\n","import React, {\n FC, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport useChatContextActions from '../../../hooks/useChatContextActions';\nimport useFlag from '../../../hooks/useFlag';\nimport { isChatPrivate, getPrivateChatUserId } from '../../../modules/helpers';\nimport { selectChat, selectUser, selectIsChatPinned } from '../../../modules/selectors';\nimport useSelectWithEnter from '../../../hooks/useSelectWithEnter';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../common/GroupChatInfo';\nimport DeleteChatModal from '../../common/DeleteChatModal';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n withUsername?: boolean;\n onClick: (id: number) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n isPinned?: boolean;\n};\n\nconst LeftSearchResultChat: FC = ({\n chatId,\n chat,\n privateChatUser,\n isPinned,\n withUsername,\n onClick,\n}) => {\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n const contextActions = useChatContextActions({\n chat,\n privateChatUser,\n isPinned,\n handleDelete: openDeleteModal,\n });\n\n const handleClick = () => {\n onClick(chatId);\n };\n\n const buttonRef = useSelectWithEnter(handleClick);\n\n if (!chat) {\n return undefined;\n }\n\n return (\n \n {isChatPrivate(chatId) ? (\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 privateChatUserId = chat && getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n const isPinned = selectIsChatPinned(global, chatId);\n\n return {\n chat,\n privateChatUser,\n isPinned,\n };\n },\n)(LeftSearchResultChat));\n","import React, {\n FC, useEffect, useCallback, useRef, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser } from '../../../api/types';\n\nimport { getUserFirstOrLastName } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport { throttle } from '../../../util/schedulers';\nimport { pick } from '../../../util/iteratees';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport LeftSearchResultChat from './LeftSearchResultChat';\n\nimport './RecentContacts.scss';\n\ntype OwnProps = {\n onReset: () => void;\n};\n\ntype StateProps = {\n topUserIds?: number[];\n usersById: Record;\n recentlyFoundChatIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SEARCH_CLOSE_TIMEOUT_MS = 250;\nconst NBSP = '\\u00A0';\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst RecentContacts: FC = ({\n topUserIds, usersById, recentlyFoundChatIds,\n onReset, loadTopUsers, loadContactList, openChat,\n addRecentlyFoundChatId, clearRecentlyFoundChats,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const topUsersRef = useRef(null);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadTopUsers();\n // Loading full contact list for quick local search before user enters the query\n loadContactList();\n });\n }, [loadTopUsers, loadContactList]);\n\n useHorizontalScroll(topUsersRef, !topUserIds);\n\n const handleClick = useCallback(\n (id: number) => {\n openChat({ id });\n onReset();\n setTimeout(() => {\n addRecentlyFoundChatId({ id });\n }, SEARCH_CLOSE_TIMEOUT_MS);\n },\n [openChat, addRecentlyFoundChatId, onReset],\n );\n\n const lang = useLang();\n\n return (\n
\n {topUserIds && (\n
\n
\n {topUserIds.map((userId) => (\n
handleClick(userId)} dir={lang.isRtl ? 'rtl' : undefined}>\n \n
{renderText(getUserFirstOrLastName(usersById[userId]) || NBSP)}
\n
\n ))}\n
\n
\n )}\n {recentlyFoundChatIds && (\n
\n

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

\n {recentlyFoundChatIds.map((id) => (\n \n ))}\n
\n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { userIds: topUserIds } = global.topPeers;\n const usersById = global.users.byId;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n return {\n topUserIds,\n usersById,\n recentlyFoundChatIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadTopUsers',\n 'loadContactList',\n 'openChat',\n 'addRecentlyFoundChatId',\n 'clearRecentlyFoundChats',\n ]),\n)(RecentContacts));\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiChat, ApiUser, ApiMessage, ApiMessageOutgoingStatus,\n} from '../../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n getChatTitle,\n getPrivateChatUserId,\n getMessageMediaHash,\n getMessageSummaryText,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n getMessageRoundVideo,\n} from '../../../modules/helpers';\nimport { selectChat, selectUser } from '../../../modules/selectors';\nimport renderText from '../../common/helpers/renderText';\nimport { pick } from '../../../util/iteratees';\nimport useMedia from '../../../hooks/useMedia';\nimport { formatPastTimeShort } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\nimport useSelectWithEnter from '../../../hooks/useSelectWithEnter';\n\nimport Avatar from '../../common/Avatar';\nimport VerifiedIcon from '../../common/VerifiedIcon';\nimport ListItem from '../../ui/ListItem';\nimport Link from '../../ui/Link';\n\nimport './ChatMessage.scss';\n\ntype OwnProps = {\n searchQuery?: string;\n message: ApiMessage;\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n lastMessageOutgoingStatus?: ApiMessageOutgoingStatus;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatMessage: FC = ({\n message,\n searchQuery,\n chatId,\n chat,\n privateChatUser,\n focusMessage,\n lastSyncTime,\n}) => {\n const mediaThumbnail = getMessageMediaThumbDataUri(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'micro'));\n const isRoundVideo = Boolean(getMessageRoundVideo(message));\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId, messageId: message.id });\n }, [chatId, focusMessage, message.id]);\n\n const lang = useLang();\n\n const buttonRef = useSelectWithEnter(handleClick);\n\n if (!chat) {\n return undefined;\n }\n\n return (\n \n \n
\n
\n
\n

{renderText(getChatTitle(lang, chat, privateChatUser))}

\n {chat.isVerified && }\n
\n
\n \n {formatPastTimeShort(lang, message.date * 1000)}\n \n
\n\n
\n
\n
\n {renderMessageSummary(lang, message, mediaBlobUrl || mediaThumbnail, searchQuery, isRoundVideo)}\n
\n
\n
\n \n );\n};\n\nfunction renderMessageSummary(\n lang: LangFn, message: ApiMessage, blobUrl?: string, searchQuery?: string, isRoundVideo?: boolean,\n) {\n if (!blobUrl) {\n return renderText(getMessageSummaryText(lang, message));\n }\n\n return (\n \n \"\"\n {getMessageVideo(message) && }\n {renderText(getMessageSummaryText(lang, message, true), ['emoji', 'highlight'], { highlight: searchQuery })}\n \n );\n}\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const privateChatUserId = getPrivateChatUserId(chat);\n\n return {\n chat,\n ...(privateChatUserId && { privateChatUser: selectUser(global, privateChatUserId) }),\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n ]),\n)(ChatMessage));\n","import React, { FC, memo, useMemo } from '../../../lib/teact/teact';\nimport { formatDateToString } from '../../../util/dateFormat';\n\nimport './DateSuggest.scss';\n\nconst SUGGESTION_COUNT = 8;\n\nexport type OwnProps = {\n searchDate: string;\n onSelect: (value: Date) => void;\n};\n\nconst DateSuggest: FC = ({\n searchDate, onSelect,\n}) => {\n const suggestions = useMemo(() => getSuggestionsFromDate(searchDate), [searchDate]);\n return (\n
\n {suggestions.map(({ date, text }) => {\n return (\n onSelect(date)}\n className=\"date-item\"\n key={text}\n >\n \n {text}\n \n );\n })}\n
\n );\n};\n\nfunction getSuggestionsFromDate(searchDate: string) {\n const hasYear = searchDate.match(/^\\d{2,4}-\\d{2}-\\d{2}$/g);\n if (hasYear) {\n const date = new Date(searchDate);\n return [{ date, text: formatDateToString(date) }];\n }\n\n const suggestion = [];\n const currentDate = new Date();\n const currentYear = currentDate.getFullYear();\n const latestYear = currentDate.getTime() > (new Date(`${currentYear}-${searchDate}`)).getTime()\n ? currentYear\n : currentYear - 1;\n\n for (let i = 0; i < SUGGESTION_COUNT; i++) {\n const date = new Date(`${latestYear - i}-${searchDate}`);\n suggestion.push({ date, text: formatDateToString(date) });\n }\n\n return suggestion;\n}\n\nexport default memo(DateSuggest);\n","import React, {\n FC, memo, useCallback, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUser, ApiChat, ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport searchWords from '../../../util/searchWords';\nimport { unique, pick } from '../../../util/iteratees';\nimport { getUserFullName, getMessageSummaryText, sortChatIds } from '../../../modules/helpers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport LeftSearchResultChat from './LeftSearchResultChat';\nimport RecentContacts from './RecentContacts';\nimport ChatMessage from './ChatMessage';\nimport DateSuggest from './DateSuggest';\nimport Link from '../../ui/Link';\nimport NothingFound from '../../common/NothingFound';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\n\nexport type OwnProps = {\n searchQuery?: string;\n dateSearchQuery?: string;\n searchDate?: number;\n onReset: () => void;\n onSearchDateSelect: (value: Date) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n localContactIds?: number[];\n localChatIds?: number[];\n localUserIds?: number[];\n globalChatIds?: number[];\n globalUserIds?: number[];\n foundIds?: string[];\n globalMessagesByChatId?: Record }>;\n chatsById: Record;\n usersById: Record;\n fetchingStatus?: { chats?: boolean; messages?: boolean };\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst MIN_QUERY_LENGTH_FOR_GLOBAL_SEARCH = 4;\nconst LESS_LIST_ITEMS_AMOUNT = 3;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst ChatResults: FC = ({\n searchQuery, searchDate, dateSearchQuery, currentUserId,\n localContactIds, localChatIds, localUserIds, globalChatIds, globalUserIds,\n foundIds, globalMessagesByChatId, chatsById, usersById, fetchingStatus, lastSyncTime,\n onReset, onSearchDateSelect, openChat, addRecentlyFoundChatId, searchMessagesGlobal, setGlobalSearchChatId,\n}) => {\n const lang = useLang();\n\n const [shouldShowMoreLocal, setShouldShowMoreLocal] = useState(false);\n const [shouldShowMoreGlobal, setShouldShowMoreGlobal] = useState(false);\n\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: 'text',\n query: searchQuery,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery]);\n\n const handleChatClick = useCallback(\n (id: number) => {\n openChat({ id });\n\n if (id !== currentUserId) {\n addRecentlyFoundChatId({ id });\n }\n\n if (!IS_MOBILE_SCREEN) {\n onReset();\n }\n },\n [currentUserId, openChat, addRecentlyFoundChatId, onReset],\n );\n\n const handlePickerItemClick = useCallback((id: number) => {\n setGlobalSearchChatId({ id });\n }, [setGlobalSearchChatId]);\n\n const localResults = useMemo(() => {\n if (!searchQuery || (searchQuery.startsWith('@') && searchQuery.length < 2)) {\n return MEMO_EMPTY_ARRAY;\n }\n\n const foundContactIds = localContactIds\n ? localContactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const fullName = getUserFullName(user);\n return (fullName && searchWords(fullName, searchQuery)) || searchWords(user.username, searchQuery);\n })\n : [];\n\n return [\n ...(currentUserId && searchWords(lang('SavedMessages'), searchQuery) ? [currentUserId] : []),\n ...sortChatIds(unique([\n ...foundContactIds,\n ...(localChatIds || []),\n ...(localUserIds || []),\n ]), chatsById),\n ];\n }, [searchQuery, localContactIds, currentUserId, lang, localChatIds, localUserIds, chatsById, usersById]);\n\n const globalResults = useMemo(() => {\n if (!searchQuery || searchQuery.length < MIN_QUERY_LENGTH_FOR_GLOBAL_SEARCH || !globalChatIds || !globalUserIds) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return sortChatIds(unique([...globalChatIds, ...globalUserIds]), chatsById, true);\n }, [chatsById, globalChatIds, globalUserIds, searchQuery]);\n\n const foundMessages = useMemo(() => {\n if ((!searchQuery && !searchDate) || !foundIds || foundIds.length === 0) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds\n .map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return (\n globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]\n );\n })\n .filter(Boolean as any)\n .sort((a, b) => b.date - a.date);\n }, [foundIds, globalMessagesByChatId, searchQuery, searchDate]);\n\n const handleClickShowMoreLocal = useCallback(() => {\n setShouldShowMoreLocal(!shouldShowMoreLocal);\n }, [shouldShowMoreLocal]);\n\n const handleClickShowMoreGlobal = useCallback(() => {\n setShouldShowMoreGlobal(!shouldShowMoreGlobal);\n }, [shouldShowMoreGlobal]);\n\n function renderFoundMessage(message: ApiMessage) {\n const text = getMessageSummaryText(lang, message);\n const chat = chatsById[message.chatId];\n\n if (!text || !chat) {\n return undefined;\n }\n\n return (\n \n );\n }\n\n const nothingFound = fetchingStatus && !fetchingStatus.chats && !fetchingStatus.messages\n && !localResults.length && !globalResults.length && !foundMessages.length;\n\n if (!searchQuery && !searchDate) {\n return ;\n }\n\n return (\n \n {dateSearchQuery && (\n
\n \n
\n )}\n {nothingFound && (\n \n )}\n {!!localResults.length && (\n
\n {localResults.map((id) => (\n \n ))}\n
\n )}\n {!!localResults.length && (\n
\n

\n {localResults.length > LESS_LIST_ITEMS_AMOUNT && (\n \n {lang(shouldShowMoreLocal ? 'ChatList.Search.ShowLess' : 'ChatList.Search.ShowMore')}\n \n )}\n {lang('DialogList.SearchSectionDialogs')}\n

\n {localResults.map((id, index) => {\n if (!shouldShowMoreLocal && index >= LESS_LIST_ITEMS_AMOUNT) {\n return undefined;\n }\n\n return (\n \n );\n })}\n
\n )}\n {!!globalResults.length && (\n
\n

\n {globalResults.length > LESS_LIST_ITEMS_AMOUNT && (\n \n {lang(shouldShowMoreGlobal ? 'ChatList.Search.ShowLess' : 'ChatList.Search.ShowMore')}\n \n )}\n {lang('DialogList.SearchSectionGlobal')}\n

\n {globalResults.map((id, index) => {\n if (!shouldShowMoreGlobal && index >= LESS_LIST_ITEMS_AMOUNT) {\n return undefined;\n }\n\n return (\n \n );\n })}\n
\n )}\n {!!foundMessages.length && (\n
\n

{lang('SearchMessages')}

\n {foundMessages.map(renderFoundMessage)}\n
\n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { byId: chatsById } = global.chats;\n const { byId: usersById } = global.users;\n\n const { userIds: localContactIds } = global.contactList || {};\n\n if (!localContactIds) {\n return {\n chatsById,\n usersById,\n };\n }\n\n const { currentUserId, messages, lastSyncTime } = global;\n const {\n fetchingStatus, globalResults, localResults, resultsByType,\n } = global.globalSearch;\n const { chatIds: globalChatIds, userIds: globalUserIds } = globalResults || {};\n const { chatIds: localChatIds, userIds: localUserIds } = localResults || {};\n const { byChatId: globalMessagesByChatId } = messages;\n const { foundIds } = (resultsByType && resultsByType.text) || {};\n\n return {\n currentUserId,\n localContactIds,\n localChatIds,\n localUserIds,\n globalChatIds,\n globalUserIds,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n usersById,\n fetchingStatus,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'addRecentlyFoundChatId',\n 'searchMessagesGlobal',\n 'setGlobalSearchChatId',\n ]),\n)(ChatResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { getMessageSummaryText } from '../../../modules/helpers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport ChatMessage from './ChatMessage';\nimport NothingFound from '../../common/NothingFound';\nimport DateSuggest from './DateSuggest';\n\nexport type OwnProps = {\n searchQuery?: string;\n dateSearchQuery?: string;\n onReset: () => void;\n onSearchDateSelect: (value: Date) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n foundIds?: string[];\n globalMessagesByChatId?: Record }>;\n chatsById: Record;\n fetchingStatus?: { chats?: boolean; messages?: boolean };\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst ChatMessageResults: FC = ({\n searchQuery,\n currentUserId,\n dateSearchQuery,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n fetchingStatus,\n lastSyncTime,\n searchMessagesGlobal,\n onSearchDateSelect,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: 'text',\n query: searchQuery,\n chatId: currentUserId,\n });\n });\n }\n }, [currentUserId, lastSyncTime, searchMessagesGlobal, searchQuery]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || foundIds.length === 0) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds\n .map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return (\n globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]\n );\n })\n .filter(Boolean as any)\n .sort((a, b) => b.date - a.date);\n }, [foundIds, globalMessagesByChatId]);\n\n function renderFoundMessage(message: ApiMessage) {\n const text = getMessageSummaryText(lang, message);\n const chat = chatsById[message.chatId];\n\n if (!text || !chat) {\n return undefined;\n }\n\n return (\n \n );\n }\n\n const nothingFound = fetchingStatus && !fetchingStatus.chats && !fetchingStatus.messages && !foundMessages.length;\n\n return (\n
\n \n {dateSearchQuery && (\n
\n \n
\n )}\n {nothingFound && (\n \n )}\n {!!foundMessages.length && foundMessages.map(renderFoundMessage)}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { byId: chatsById } = global.chats;\n const { currentUserId, messages: { byChatId: globalMessagesByChatId }, lastSyncTime } = global;\n const { fetchingStatus, resultsByType } = global.globalSearch;\n\n const { foundIds } = (resultsByType && resultsByType.text) || {};\n\n return {\n currentUserId,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n fetchingStatus,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['searchMessagesGlobal']),\n)(ChatMessageResults));\n","import { GlobalState } from '../../../../global/types';\nimport {\n ApiChat, ApiGlobalMessageSearchType, ApiMessage, ApiUser,\n} from '../../../../api/types';\n\nexport type StateProps = {\n isLoading?: boolean;\n chatsById: Record;\n usersById: Record;\n globalMessagesByChatId?: Record }>;\n foundIds?: string[];\n lastSyncTime?: number;\n searchChatId?: number;\n};\n\nexport function createMapStateToProps(type: ApiGlobalMessageSearchType) {\n return (global: GlobalState, props: any) => {\n const { byId: chatsById } = global.chats;\n const { byId: usersById } = global.users;\n const {\n fetchingStatus, resultsByType, chatId,\n } = global.globalSearch;\n\n // One component is used for two different types of results.\n // The differences between them are only in the isVoice property.\n // The rest of the search results use their own personal components.\n const currentType = type !== 'audio' ? type : (props && props.isVoice ? 'voice' : 'audio');\n\n const { byChatId: globalMessagesByChatId } = global.messages;\n const { foundIds } = (resultsByType && resultsByType[currentType]) || {};\n\n return {\n isLoading: foundIds === undefined\n || (fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false),\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n searchChatId: chatId,\n lastSyncTime: global.lastSyncTime,\n };\n };\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection, MediaViewerOrigin } from '../../../types';\n\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Media from '../../common/Media';\nimport ChatMessage from './ChatMessage';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst CURRENT_TYPE = 'media';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst MediaResults: FC = ({\n searchQuery,\n searchChatId,\n isLoading,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n openMediaViewer,\n}) => {\n const lang = useLang();\n\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleSelectMedia = useCallback((messageId: number, chatId: number) => {\n openMediaViewer({\n chatId,\n messageId,\n origin: MediaViewerOrigin.SearchResult,\n });\n }, [openMediaViewer]);\n\n function renderGallery() {\n return (\n
\n {foundMessages.map((message) => (\n \n ))}\n
\n );\n }\n\n function renderSearchResult() {\n return foundMessages.map((message) => (\n \n ));\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n const isMediaGrid = canRenderContents && foundIds && foundIds.length > 0 && !searchQuery;\n const isMessageList = canRenderContents && foundIds && foundIds.length > 0 && searchQuery;\n\n const classNames = buildClassName(\n 'search-content custom-scroll',\n isMessageList && 'chat-list',\n );\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {isMediaGrid && renderGallery()}\n {isMessageList && renderSearchResult()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'openMediaViewer',\n ]),\n)(MediaResults));\n","import { ApiChat, ApiMessage, ApiUser } from '../../../../api/types';\nimport {\n getChatTitle,\n getSenderTitle,\n isChatPrivate,\n isChatGroup,\n} from '../../../../modules/helpers';\nimport { LangFn } from '../../../../hooks/useLang';\n\nexport function getSenderName(\n lang: LangFn, message: ApiMessage, chatsById: Record, usersById: Record,\n) {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n const sender = isChatPrivate(senderId) ? usersById[senderId] : chatsById[senderId];\n\n let senderName = getSenderTitle(lang, sender);\n\n const chat = chatsById[message.chatId];\n if (chat) {\n if (isChatPrivate(senderId) && (sender as ApiUser).isSelf) {\n senderName = `${lang('FromYou')} → ${getChatTitle(lang, chat)}`;\n } else if (isChatGroup(chat)) {\n senderName += ` → ${getChatTitle(lang, chat)}`;\n }\n }\n\n return senderName;\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport WebLink from '../../common/WebLink';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst CURRENT_TYPE = 'links';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst LinkResults: FC = ({\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n \n {shouldDrawDateDivider && (\n

\n {formatMonthAndYear(lang, new Date(message.date * 1000))}\n

\n )}\n \n \n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n ]),\n)(LinkResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport { getMessageDocument } from '../../../modules/helpers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport Document from '../../common/Document';\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst CURRENT_TYPE = 'documents';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst FileResults: FC = ({\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n const message = globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n\n return message && getMessageDocument(message) ? message : undefined;\n }).filter(Boolean) as ApiMessage[];\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n \n {shouldDrawDateDivider && (\n

{formatMonthAndYear(lang, new Date(message.date * 1000))}

\n )}\n \n \n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n ]),\n)(FileResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Audio from '../../common/Audio';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n isVoice?: boolean;\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst AudioResults: FC = ({\n isVoice,\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n openAudioPlayer,\n}) => {\n const lang = useLang();\n const currentType = isVoice ? 'voice' : 'audio';\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: currentType,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [currentType, lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n const handlePlayAudio = useCallback((messageId: number, chatId: number) => {\n openAudioPlayer({ chatId, messageId });\n }, [openAudioPlayer]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n \n {shouldDrawDateDivider && (\n

\n {formatMonthAndYear(lang, new Date(message.date * 1000))}\n

\n )}\n \n \n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps('audio'),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n 'openAudioPlayer',\n ]),\n)(AudioResults));\n","import React, {\n FC, memo, useCallback, useState, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { GlobalSearchContent } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { parseDateString } from '../../../util/dateFormat';\nimport useKeyboardListNavigation from '../../../hooks/useKeyboardListNavigation';\nimport useLang from '../../../hooks/useLang';\n\nimport TabList from '../../ui/TabList';\nimport Transition from '../../ui/Transition';\nimport ChatResults from './ChatResults';\nimport UserChatResults from './ChatMessageResults';\nimport MediaResults from './MediaResults';\nimport LinkResults from './LinkResults';\nimport FileResults from './FileResults';\nimport AudioResults from './AudioResults';\n\nimport './LeftSearch.scss';\n\nexport type OwnProps = {\n searchQuery?: string;\n searchDate?: number;\n isActive: boolean;\n onReset: () => void;\n};\n\ntype StateProps = {\n currentContent?: GlobalSearchContent;\n chatId?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst TABS = [\n { type: GlobalSearchContent.ChatList, title: 'SearchAllChatsShort' },\n { type: GlobalSearchContent.Media, title: 'SharedMediaTab2' },\n { type: GlobalSearchContent.Links, title: 'SharedLinksTab2' },\n { type: GlobalSearchContent.Files, title: 'SharedFilesTab2' },\n { type: GlobalSearchContent.Music, title: 'SharedMusicTab2' },\n { type: GlobalSearchContent.Voice, title: 'SharedVoiceTab2' },\n];\n\nconst CHAT_TABS = [\n { type: GlobalSearchContent.ChatList, title: 'All Messages' },\n ...TABS.slice(1),\n];\n\nconst TRANSITION_RENDER_COUNT = Object.keys(GlobalSearchContent).length / 2;\n\nconst LeftSearch: FC = ({\n searchQuery,\n searchDate,\n isActive,\n currentContent = GlobalSearchContent.ChatList,\n chatId,\n setGlobalSearchContent,\n setGlobalSearchDate,\n onReset,\n}) => {\n const lang = useLang();\n const [activeTab, setActiveTab] = useState(0);\n const dateSearchQuery = useMemo(() => parseDateString(searchQuery), [searchQuery]);\n\n const handleSwitchTab = useCallback((index: number) => {\n const tab = TABS[index];\n setGlobalSearchContent({ content: tab.type });\n setActiveTab(index);\n }, [setGlobalSearchContent]);\n\n const handleSearchDateSelect = useCallback((value: Date) => {\n setGlobalSearchDate({ date: value.getTime() / 1000 });\n }, [setGlobalSearchDate]);\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, isActive, undefined, '.ListItem-button', true);\n\n return (\n
\n \n \n {() => {\n switch (currentContent) {\n case GlobalSearchContent.ChatList:\n if (chatId) {\n return (\n \n );\n }\n return (\n \n );\n case GlobalSearchContent.Media:\n return ;\n case GlobalSearchContent.Links:\n return ;\n case GlobalSearchContent.Files:\n return ;\n case GlobalSearchContent.Music:\n return (\n \n );\n case GlobalSearchContent.Voice:\n return (\n \n );\n default:\n return undefined;\n }\n }}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentContent, chatId } = global.globalSearch;\n\n return { currentContent, chatId };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setGlobalSearchContent', 'setGlobalSearchDate']),\n)(LeftSearch));\n","import { useState, useCallback, useRef } from '../lib/teact/teact';\n\nexport type ReducerAction = { type: Actions; payload?: any };\nexport type StateReducer = (state: State, action: ReducerAction) => State;\nexport type Dispatch = (action: ReducerAction) => void;\n\nexport default function useReducer(\n reducer: StateReducer,\n initialState: State,\n) {\n const reducerRef = useRef(reducer);\n const [state, setState] = useState(initialState);\n\n const dispatch = useCallback((action: ReducerAction) => {\n setState((currentState) => reducerRef.current(currentState, action));\n }, []);\n\n return [\n state,\n dispatch,\n ] as [State, Dispatch];\n}\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\nimport { ApiChatFolder } from '../../api/types';\nimport { pick, omit } from '../../util/iteratees';\n\nexport type FolderChatType = {\n icon: string;\n title: string;\n key: keyof Pick;\n};\n\nexport const INCLUDED_CHAT_TYPES: FolderChatType[] = [\n { icon: 'user', title: 'FilterContacts', key: 'contacts' },\n { icon: 'non-contacts', title: 'FilterNonContacts', key: 'nonContacts' },\n { icon: 'group', title: 'FilterGroups', key: 'groups' },\n { icon: 'channel', title: 'FilterChannels', key: 'channels' },\n { icon: 'bots', title: 'FilterBots', key: 'bots' },\n];\n\nexport const EXCLUDED_CHAT_TYPES: FolderChatType[] = [\n { icon: 'mute', title: 'FilterMuted', key: 'excludeMuted' },\n { icon: 'archive', title: 'FilterArchived', key: 'excludeArchived' },\n { icon: 'readchats', title: 'FilterRead', key: 'excludeRead' },\n];\n\nconst INCLUDE_FILTER_FIELDS: Array = [\n 'includedChatIds', 'bots', 'channels', 'groups', 'contacts', 'nonContacts',\n];\nconst EXCLUDE_FILTER_FIELDS: Array = [\n 'excludedChatIds', 'excludeArchived', 'excludeMuted', 'excludeRead',\n];\n\nexport function selectChatFilters(state: FoldersState, mode: 'included' | 'excluded', selectTemp?: boolean) {\n let selectedChatIds: number[] = [];\n let selectedChatTypes: FolderChatType['key'][] = [];\n\n if (mode === 'included') {\n const {\n includedChatIds,\n ...includeFilters\n } = selectTemp\n ? state.includeFilters || {}\n : pick(\n state.folder,\n INCLUDE_FILTER_FIELDS,\n );\n\n selectedChatIds = includedChatIds || [];\n selectedChatTypes = (Object.keys(includeFilters) as Array)\n .filter((key) => Boolean(includeFilters[key]));\n } else {\n const {\n excludedChatIds,\n ...excludeFilters\n } = selectTemp\n ? state.excludeFilters || {}\n : pick(\n state.folder,\n EXCLUDE_FILTER_FIELDS,\n );\n\n selectedChatIds = excludedChatIds || [];\n selectedChatTypes = (Object.keys(excludeFilters) as Array)\n .filter((key) => Boolean(excludeFilters[key]));\n }\n\n return {\n selectedChatIds,\n selectedChatTypes,\n };\n}\n\nfunction getSuggestedFolderName(includeFilters?: FolderIncludeFilters) {\n if (includeFilters) {\n const {\n includedChatIds,\n ...filters\n } = includeFilters;\n\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (includedChatIds && includedChatIds.length)\n ) {\n return '';\n }\n\n if (filters.bots) {\n return 'Bots';\n } else if (filters.groups) {\n return 'Groups';\n } else if (filters.channels) {\n return 'Channels';\n } else if (filters.contacts) {\n return 'Contacts';\n } else if (filters.nonContacts) {\n return 'Non-Contacts';\n }\n }\n\n return '';\n}\n\ntype FolderIncludeFilters = Pick;\ntype FolderExcludeFilters = Pick;\n\nexport type FoldersState = {\n mode: 'create' | 'edit';\n isLoading?: boolean;\n isTouched?: boolean;\n error?: string;\n folderId?: number;\n chatFilter: string;\n folder: Omit;\n includeFilters?: FolderIncludeFilters;\n excludeFilters?: FolderExcludeFilters;\n};\nexport type FoldersActions = (\n 'setTitle' | 'saveFilters' | 'editFolder' | 'reset' | 'setChatFilter' | 'setIsLoading' | 'setError' |\n 'editIncludeFilters' | 'editExcludeFilters' | 'setIncludeFilters' | 'setExcludeFilters'\n);\nexport type FolderEditDispatch = Dispatch;\n\nconst INITIAL_STATE: FoldersState = {\n mode: 'create',\n chatFilter: '',\n folder: {\n title: '',\n includedChatIds: [],\n excludedChatIds: [],\n },\n};\n\nconst foldersReducer: StateReducer = (\n state,\n action,\n) => {\n switch (action.type) {\n case 'setTitle':\n return {\n ...state,\n folder: {\n ...state.folder,\n title: action.payload,\n },\n isTouched: true,\n };\n case 'editIncludeFilters':\n return {\n ...state,\n includeFilters: pick(\n state.folder,\n INCLUDE_FILTER_FIELDS,\n ),\n };\n case 'editExcludeFilters':\n return {\n ...state,\n excludeFilters: pick(\n state.folder,\n EXCLUDE_FILTER_FIELDS,\n ),\n };\n case 'setIncludeFilters':\n return {\n ...state,\n includeFilters: action.payload,\n chatFilter: '',\n };\n case 'setExcludeFilters':\n return {\n ...state,\n excludeFilters: action.payload,\n chatFilter: '',\n };\n case 'saveFilters':\n if (state.includeFilters) {\n return {\n ...state,\n folder: {\n ...omit(state.folder, INCLUDE_FILTER_FIELDS),\n title: state.folder.title ? state.folder.title : getSuggestedFolderName(state.includeFilters),\n ...state.includeFilters,\n },\n includeFilters: undefined,\n chatFilter: '',\n isTouched: true,\n };\n } else if (state.excludeFilters) {\n return {\n ...state,\n folder: {\n ...omit(state.folder, EXCLUDE_FILTER_FIELDS),\n ...state.excludeFilters,\n },\n excludeFilters: undefined,\n chatFilter: '',\n isTouched: true,\n };\n } else {\n return state;\n }\n case 'editFolder': {\n const { id: folderId, description, ...folder } = action.payload;\n\n return {\n mode: 'edit',\n folderId,\n folder,\n chatFilter: '',\n };\n }\n case 'setChatFilter': {\n return {\n ...state,\n chatFilter: action.payload,\n };\n }\n case 'setIsLoading': {\n return {\n ...state,\n isLoading: action.payload,\n };\n }\n case 'setError': {\n return {\n ...state,\n error: action.payload,\n };\n }\n case 'reset':\n return INITIAL_STATE;\n default:\n return state;\n }\n};\n\nexport default () => {\n return useReducer(foldersReducer, INITIAL_STATE);\n};\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\n\nexport type TwoFaActions = (\n 'setCurrentPassword' | 'setPassword' | 'setHint' | 'setEmail' | 'reset'\n);\nexport type TwoFaDispatch = Dispatch;\n\nexport type TwoFaState = {\n currentPassword: string;\n password: string;\n hint: string;\n email: string;\n};\n\nconst INITIAL_STATE: TwoFaState = {\n currentPassword: '',\n password: '',\n hint: '',\n email: '',\n};\n\nconst twoFaReducer: StateReducer = (\n state,\n action,\n) => {\n switch (action.type) {\n case 'setCurrentPassword':\n return {\n ...state,\n currentPassword: action.payload,\n };\n\n case 'setPassword':\n return {\n ...state,\n password: action.payload,\n };\n\n case 'setHint':\n return {\n ...state,\n hint: action.payload,\n };\n\n case 'setEmail':\n return {\n ...state,\n email: action.payload,\n };\n\n case 'reset':\n return INITIAL_STATE;\n\n default:\n return state;\n }\n};\n\nexport default () => {\n return useReducer(twoFaReducer, INITIAL_STATE);\n};\n","import React, {\n FC, useCallback, useMemo, memo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype OwnProps = {\n currentScreen: SettingsScreens;\n editedFolderId?: number;\n onReset: () => void;\n onSaveFilter: () => void;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsHeader: FC = ({\n currentScreen,\n editedFolderId,\n onReset,\n onSaveFilter,\n signOut,\n deleteChatFolder,\n}) => {\n const [isSignOutDialogOpen, setIsSignOutDialogOpen] = useState(false);\n const [isDeleteFolderDialogOpen, setIsDeleteFolderDialogOpen] = useState(false);\n\n const openSignOutConfirmation = useCallback(() => {\n setIsSignOutDialogOpen(true);\n }, []);\n\n const closeSignOutConfirmation = useCallback(() => {\n setIsSignOutDialogOpen(false);\n }, []);\n\n const openDeleteFolderConfirmation = useCallback(() => {\n setIsDeleteFolderDialogOpen(true);\n }, []);\n\n const closeDeleteFolderConfirmation = useCallback(() => {\n setIsDeleteFolderDialogOpen(false);\n }, []);\n\n const handleSignOutMessage = useCallback(() => {\n closeSignOutConfirmation();\n signOut();\n }, [closeSignOutConfirmation, signOut]);\n\n const handleDeleteFolderMessage = useCallback(() => {\n closeDeleteFolderConfirmation();\n deleteChatFolder({ id: editedFolderId });\n onReset();\n }, [editedFolderId, closeDeleteFolderConfirmation, deleteChatFolder, onReset]);\n\n const SettingsMenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n \n \n \n );\n }, []);\n\n const lang = useLang();\n\n function renderHeaderContent() {\n switch (currentScreen) {\n case SettingsScreens.EditProfile:\n return

{lang('lng_settings_information')}

;\n case SettingsScreens.General:\n return

{lang('General')}

;\n case SettingsScreens.Notifications:\n return

{lang('Notifications')}

;\n case SettingsScreens.Privacy:\n return

{lang('PrivacySettings')}

;\n case SettingsScreens.Language:\n return

{lang('Language')}

;\n\n case SettingsScreens.GeneralChatBackground:\n return

{lang('ChatBackground')}

;\n case SettingsScreens.GeneralChatBackgroundColor:\n return

{lang('SetColor')}

;\n\n case SettingsScreens.PrivacyPhoneNumber:\n return

{lang('PrivacyPhone')}

;\n case SettingsScreens.PrivacyLastSeen:\n return

{lang('PrivacyLastSeen')}

;\n case SettingsScreens.PrivacyProfilePhoto:\n return

{lang('Privacy.ProfilePhoto')}

;\n case SettingsScreens.PrivacyForwarding:\n return

{lang('PrivacyForwards')}

;\n case SettingsScreens.PrivacyGroupChats:\n return

{lang('AutodownloadGroupChats')}

;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return

{lang('AlwaysShareWith')}

;\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return

{lang('NeverShareWith')}

;\n\n case SettingsScreens.PrivacyActiveSessions:\n return

{lang('SessionsTitle')}

;\n case SettingsScreens.PrivacyBlockedUsers:\n return

{lang('BlockedUsers')}

;\n\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n return

{lang('TwoStepVerification')}

;\n case SettingsScreens.TwoFaNewPassword:\n case SettingsScreens.TwoFaChangePasswordNew:\n case SettingsScreens.TwoFaChangePasswordConfirm:\n return

{lang('EnterPassword')}

;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return

{lang('PleaseReEnterPassword')}

;\n case SettingsScreens.TwoFaNewPasswordHint:\n case SettingsScreens.TwoFaChangePasswordHint:\n return

{lang('PasswordHint')}

;\n case SettingsScreens.TwoFaNewPasswordEmail:\n case SettingsScreens.TwoFaRecoveryEmail:\n return

{lang('RecoveryEmailTitle')}

;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return

Recovery Email Code

;\n case SettingsScreens.TwoFaCongratulations:\n return

{lang('TwoStepVerificationPasswordSet')}

;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n return

{lang('PleaseEnterCurrentPassword')}

;\n\n case SettingsScreens.Folders:\n return

{lang('Filters')}

;\n case SettingsScreens.FoldersCreateFolder:\n return

{lang('FilterNew')}

;\n case SettingsScreens.FoldersEditFolder:\n return (\n
\n

{lang('FilterEdit')}

\n\n {editedFolderId && (\n \n \n Delete Folder\n \n \n )}\n
\n );\n case SettingsScreens.FoldersIncludedChats:\n case SettingsScreens.FoldersExcludedChats:\n return (\n
\n {currentScreen === SettingsScreens.FoldersIncludedChats ? (\n

{lang('FilterInclude')}

\n ) : (\n

{lang('FilterExclude')}

\n )}\n\n \n \n \n
\n );\n\n default:\n return (\n
\n

{lang('SETTINGS')}

\n\n \n {lang('LogOutTitle')}\n \n
\n );\n }\n }\n\n return (\n
\n \n \n \n {renderHeaderContent()}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['signOut', 'deleteChatFolder']),\n)(SettingsHeader));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { SettingsScreens } from '../../../types';\nimport { ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { getUserFullName } from '../../../modules/helpers';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Avatar from '../../common/Avatar';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n currentUser?: ApiUser;\n};\n\nconst SettingsMain: FC = ({\n onScreenSelect,\n currentUser,\n}) => {\n const lang = useLang();\n\n return (\n
\n
\n {currentUser && (\n
\n \n

{getUserFullName(currentUser)}

\n

{formatPhoneNumberWithCode(currentUser.phoneNumber)}

\n
\n )}\n onScreenSelect(SettingsScreens.EditProfile)}\n >\n {lang('lng_settings_information')}\n \n onScreenSelect(SettingsScreens.Folders)}\n >\n {lang('Filters')}\n \n onScreenSelect(SettingsScreens.General)}\n >\n {lang('Telegram.GeneralSettingsViewController')}\n \n onScreenSelect(SettingsScreens.Notifications)}\n >\n {lang('Notifications')}\n \n onScreenSelect(SettingsScreens.Privacy)}\n >\n {lang('PrivacySettings')}\n \n onScreenSelect(SettingsScreens.Language)}\n >\n {lang('Language')}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentUserId } = global;\n\n return {\n currentUser: currentUserId ? selectUser(global, currentUserId) : undefined,\n };\n },\n)(SettingsMain));\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\nimport './FloatingActionButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n className?: string;\n color?: ButtonProps['color'];\n ariaLabel?: ButtonProps['ariaLabel'];\n disabled?: boolean;\n onClick: () => void;\n children: any;\n};\n\nconst FloatingActionButton: FC = ({\n isShown,\n className,\n color = 'primary',\n ariaLabel,\n disabled,\n onClick,\n children,\n}) => {\n const buttonClassName = buildClassName(\n 'FloatingActionButton',\n isShown && 'revealed',\n className,\n );\n\n return (\n \n {children}\n \n );\n};\n\nexport default FloatingActionButton;\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useCallback, memo, useEffect, useMemo,\n} from '../../lib/teact/teact';\n\nimport { debounce } from '../../util/schedulers';\nimport useLang from '../../hooks/useLang';\n\nimport InputText from '../ui/InputText';\n\ntype OwnProps = {\n currentUsername?: string;\n asLink?: boolean;\n isLoading?: boolean;\n isUsernameAvailable?: boolean;\n checkUsername: AnyToVoidFunction;\n onChange: (value: string | false) => void;\n};\n\nconst MIN_USERNAME_LENGTH = 5;\nconst MAX_USERNAME_LENGTH = 32;\nconst LINK_PREFIX = 'https://t.me/';\nconst LINK_PREFIX_REGEX = /https:\\/\\/t\\.me\\/?/i;\nconst USERNAME_REGEX = /^([a-zA-Z0-9_]+)$/;\n\nconst runDebouncedForCheckUsername = debounce((cb) => cb(), 250, false);\n\nfunction isUsernameValid(username: string) {\n return username.length >= MIN_USERNAME_LENGTH\n && username.length <= MAX_USERNAME_LENGTH\n && USERNAME_REGEX.test(username);\n}\n\nconst SettingsEditProfile: FC = ({\n currentUsername,\n asLink,\n isLoading,\n isUsernameAvailable,\n checkUsername,\n onChange,\n}) => {\n const [username, setUsername] = useState(currentUsername || '');\n\n const lang = useLang();\n const langPrefix = asLink ? 'SetUrl' : 'Username';\n const label = asLink ? lang('SetUrlPlaceholder') : lang('Username');\n\n const [usernameSuccess, usernameError] = useMemo(() => {\n if (!username.length) {\n return [];\n }\n\n if (username.length < MIN_USERNAME_LENGTH) {\n return [undefined, `${label} is too short`];\n }\n if (username.length > MAX_USERNAME_LENGTH) {\n return [undefined, `${label} is too long`];\n }\n if (!USERNAME_REGEX.test(username)) {\n return [undefined, `${label} contains invalid characters`];\n }\n\n if (isUsernameAvailable === undefined) {\n return [];\n }\n\n // Variable `isUsernameAvailable` is initialized with `undefined`, so a strict false check is required\n return [\n isUsernameAvailable ? lang(`${langPrefix}Available`, 'Username') : undefined,\n isUsernameAvailable === false ? lang(`${langPrefix}InUse`) : undefined,\n ];\n }, [username, isUsernameAvailable, lang, langPrefix, label]);\n\n useEffect(() => {\n setUsername(currentUsername || '');\n }, [asLink, currentUsername]);\n\n const handleUsernameChange = useCallback((e: ChangeEvent) => {\n const newUsername = e.target.value.trim().replace(LINK_PREFIX_REGEX, '');\n setUsername(newUsername);\n e.target.value = `${asLink ? LINK_PREFIX : ''}${newUsername}`;\n\n const isValid = isUsernameValid(newUsername);\n\n if (isValid) {\n runDebouncedForCheckUsername(() => {\n checkUsername({ username: newUsername });\n });\n }\n\n if (onChange) {\n onChange(isValid ? newUsername : false);\n }\n }, [asLink, checkUsername, onChange]);\n\n return (\n \n );\n};\n\nexport default memo(SettingsEditProfile);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useCallback, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { ProfileEditProgress } from '../../../types';\n\nimport { throttle } from '../../../util/schedulers';\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\nimport { getChatAvatarHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport InputText from '../../ui/InputText';\nimport renderText from '../../common/helpers/renderText';\nimport UsernameInput from '../../common/UsernameInput';\n\ntype StateProps = {\n currentAvatarHash?: string;\n currentFirstName?: string;\n currentLastName?: string;\n currentBio?: string;\n currentUsername?: string;\n progress?: ProfileEditProgress;\n isUsernameAvailable?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst MAX_BIO_LENGTH = 70;\n\nconst ERROR_FIRST_NAME_MISSING = 'Please provide your first name';\nconst ERROR_BIO_TOO_LONG = 'Bio can\\' be longer than 70 characters';\n\nconst SettingsEditProfile: FC = ({\n currentAvatarHash,\n currentFirstName,\n currentLastName,\n currentBio,\n currentUsername,\n progress,\n isUsernameAvailable,\n loadCurrentUser,\n updateProfile,\n checkUsername,\n}) => {\n const [isUsernameTouched, setIsUsernameTouched] = useState(false);\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [error, setError] = useState();\n\n const [photo, setPhoto] = useState();\n const [firstName, setFirstName] = useState(currentFirstName || '');\n const [lastName, setLastName] = useState(currentLastName || '');\n const [bio, setBio] = useState(currentBio || '');\n const [username, setUsername] = useState(currentUsername || '');\n\n const currentAvatarBlobUrl = useMedia(currentAvatarHash, false, ApiMediaFormat.BlobUrl);\n\n const isLoading = progress === ProfileEditProgress.InProgress;\n const isUsernameError = username === false;\n\n const isSaveButtonShown = useMemo(() => {\n if (isUsernameError) {\n return false;\n }\n\n return Boolean(photo) || isProfileFieldsTouched || isUsernameAvailable === true;\n }, [photo, isProfileFieldsTouched, isUsernameError, isUsernameAvailable]);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadCurrentUser();\n });\n }, [loadCurrentUser]);\n\n useEffect(() => {\n setPhoto(undefined);\n }, [currentAvatarBlobUrl]);\n\n useEffect(() => {\n setFirstName(currentFirstName || '');\n setLastName(currentLastName || '');\n setBio(currentBio || '');\n }, [currentFirstName, currentLastName, currentBio]);\n\n useEffect(() => {\n setUsername(currentUsername || '');\n }, [currentUsername]);\n\n useEffect(() => {\n if (progress === ProfileEditProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setIsUsernameTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const handlePhotoChange = useCallback((newPhoto: File) => {\n setPhoto(newPhoto);\n }, []);\n\n const handleFirstNameChange = useCallback((e: ChangeEvent) => {\n setFirstName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleLastNameChange = useCallback((e: ChangeEvent) => {\n setLastName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleBioChange = useCallback((e: ChangeEvent) => {\n setBio(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUsernameChange = useCallback((value: string | false) => {\n setUsername(value);\n setIsUsernameTouched(true);\n }, []);\n\n const handleProfileSave = useCallback(() => {\n const trimmedFirstName = firstName.trim();\n const trimmedLastName = lastName.trim();\n const trimmedBio = bio.trim();\n\n if (!trimmedFirstName.length) {\n setError(ERROR_FIRST_NAME_MISSING);\n return;\n }\n\n if (trimmedBio.length > MAX_BIO_LENGTH) {\n setError(ERROR_BIO_TOO_LONG);\n return;\n }\n\n updateProfile({\n photo,\n ...(isProfileFieldsTouched && {\n firstName: trimmedFirstName,\n lastName: trimmedLastName,\n bio: trimmedBio,\n }),\n ...(isUsernameTouched && {\n username,\n }),\n });\n }, [\n photo,\n firstName, lastName, bio, isProfileFieldsTouched,\n username, isUsernameTouched,\n updateProfile,\n ]);\n\n const lang = useLang();\n\n return (\n
\n
\n
\n \n \n \n \n\n

\n {renderText(lang('lng_settings_about_bio'), ['br', 'simple_markdown'])}\n

\n
\n\n
\n

{lang('Username')}

\n\n \n\n

\n {renderText(lang('UsernameHelp'), ['br', 'simple_markdown'])}\n

\n {username && (\n

\n {lang('lng_username_link')}
\n https://t.me/{username}\n

\n )}\n
\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentUserId } = global;\n const { progress, isUsernameAvailable } = global.profileEdit || {};\n const currentUser = currentUserId ? selectUser(global, currentUserId) : undefined;\n\n if (!currentUser) {\n return {\n progress,\n isUsernameAvailable,\n };\n }\n\n const {\n firstName: currentFirstName,\n lastName: currentLastName,\n username: currentUsername,\n fullInfo,\n } = currentUser;\n const { bio: currentBio } = fullInfo || {};\n const currentAvatarHash = getChatAvatarHash(currentUser);\n\n return {\n currentAvatarHash,\n currentFirstName,\n currentLastName,\n currentBio,\n currentUsername,\n progress,\n isUsernameAvailable,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadCurrentUser',\n 'updateProfile',\n 'checkUsername',\n ]),\n)(SettingsEditProfile));\n","import React, {\n FC, memo, useMemo, useCallback, useState, useEffect,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\nimport { ApiChatFolder, ApiChat, ApiUser } from '../../../../api/types';\nimport { NotifyException, NotifySettings } from '../../../../types';\n\nimport { STICKER_SIZE_FOLDER_SETTINGS } from '../../../../config';\nimport { pick } from '../../../../util/iteratees';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../../modules/selectors';\nimport { throttle } from '../../../../util/schedulers';\nimport getAnimationData from '../../../common/helpers/animatedAssets';\nimport { getFolderDescriptionText } from '../../../../modules/helpers';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport Button from '../../../ui/Button';\nimport Loading from '../../../ui/Loading';\nimport AnimatedSticker from '../../../common/AnimatedSticker';\n\ntype OwnProps = {\n onCreateFolder: () => void;\n onEditFolder: (folder: ApiChatFolder) => void;\n};\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n orderedFolderIds?: number[];\n foldersById: Record;\n recommendedChatFolders?: ApiChatFolder[];\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottledForLoadRecommended = throttle((cb) => cb(), 60000, true);\n\nconst MAX_ALLOWED_FOLDERS = 10;\n\nconst SettingsFoldersMain: FC = ({\n onCreateFolder,\n onEditFolder,\n chatsById,\n usersById,\n orderedFolderIds,\n foldersById,\n recommendedChatFolders,\n notifySettings,\n notifyExceptions,\n loadRecommendedChatFolders,\n addChatFolder,\n showError,\n}) => {\n const [animationData, setAnimationData] = useState>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('FoldersAll').then(setAnimationData);\n }\n }, [animationData]);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottledForLoadRecommended(() => {\n loadRecommendedChatFolders();\n });\n }, [loadRecommendedChatFolders]);\n\n const handleCreateFolder = useCallback(() => {\n if (Object.keys(foldersById).length >= MAX_ALLOWED_FOLDERS) {\n showError({\n error: {\n message: 'DIALOG_FILTERS_TOO_MUCH',\n },\n });\n\n return;\n }\n\n onCreateFolder();\n }, [foldersById, showError, onCreateFolder]);\n\n const lang = useLang();\n\n const userFolders = useMemo(() => {\n if (!orderedFolderIds) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n\n return orderedFolderIds.map((id) => {\n const folder = foldersById[id];\n\n return {\n id: folder.id,\n title: folder.title,\n subtitle: getFolderDescriptionText(\n lang, chatsById, usersById, folder, chatIds, notifySettings, notifyExceptions,\n ),\n };\n });\n }, [orderedFolderIds, chatsById, foldersById, usersById, notifySettings, notifyExceptions, lang]);\n\n const handleCreateFolderFromRecommended = useCallback((folder: ApiChatFolder) => {\n if (Object.keys(foldersById).length >= MAX_ALLOWED_FOLDERS) {\n showError({\n error: {\n message: 'DIALOG_FILTERS_TOO_MUCH',\n },\n });\n\n return;\n }\n\n addChatFolder({ folder });\n }, [foldersById, addChatFolder, showError]);\n\n return (\n
\n
\n
\n {animationData && (\n \n )}\n
\n\n

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

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

{lang('Filters')}

\n\n {userFolders && userFolders.length ? userFolders.map((folder) => (\n onEditFolder(foldersById[folder.id])}\n >\n {folder.title}\n {folder.subtitle}\n \n )) : userFolders && !userFolders.length ? (\n

\n You have no folders yet.\n

\n ) : }\n
\n\n {(recommendedChatFolders && !!recommendedChatFolders.length) && (\n
\n

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

\n\n {recommendedChatFolders.map((folder) => (\n handleCreateFolderFromRecommended(folder)}\n >\n
\n
\n {folder.title}\n {folder.description}\n
\n\n \n {lang('Add')}\n \n
\n \n ))}\n
\n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n } = global;\n\n const {\n orderedIds: orderedFolderIds,\n byId: foldersById,\n recommended: recommendedChatFolders,\n } = global.chatFolders;\n\n return {\n chatsById,\n usersById,\n orderedFolderIds,\n foldersById,\n recommendedChatFolders,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadRecommendedChatFolders', 'addChatFolder', 'showError']),\n)(SettingsFoldersMain));\n","import React, { FC } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\n\nimport './ShowMoreButton.scss';\n\ntype OwnProps = {\n count: number;\n itemName: string;\n itemPluralName?: string;\n isLoading?: boolean;\n onClick: () => void;\n};\n\nconst ShowMoreButton: FC = ({\n count,\n itemName,\n itemPluralName,\n isLoading,\n onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n \n Show {count} more {count > 1 ? itemPluralName || `${itemName}s` : itemName}\n \n );\n};\n\nexport default ShowMoreButton;\n","import React, {\n FC, memo, useCallback, useState, useEffect, useMemo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\n\nimport { STICKER_SIZE_FOLDER_SETTINGS } from '../../../../config';\nimport { pick, findIntersectionWithSet } from '../../../../util/iteratees';\nimport { isChatPrivate } from '../../../../modules/helpers';\nimport getAnimationData from '../../../common/helpers/animatedAssets';\nimport {\n FoldersState,\n FolderEditDispatch,\n INCLUDED_CHAT_TYPES,\n EXCLUDED_CHAT_TYPES,\n selectChatFilters,\n} from '../../../../hooks/reducers/useFoldersReducer';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport AnimatedSticker from '../../../common/AnimatedSticker';\nimport InputText from '../../../ui/InputText';\nimport PrivateChatInfo from '../../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../../common/GroupChatInfo';\nimport FloatingActionButton from '../../../ui/FloatingActionButton';\nimport Spinner from '../../../ui/Spinner';\nimport ShowMoreButton from '../../../ui/ShowMoreButton';\n\ntype OwnProps = {\n state: FoldersState;\n dispatch: FolderEditDispatch;\n onAddIncludedChats: () => void;\n onAddExcludedChats: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n loadedActiveChatIds?: number[];\n loadedArchivedChatIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SUBMIT_TIMEOUT = 500;\n\nconst INITIAL_CHATS_LIMIT = 5;\n\nconst ERROR_NO_TITLE = 'Please provide a title for this folder.';\nconst ERROR_NO_CHATS = 'Please select at least one chat for this folder.';\n\nconst SettingsFoldersEdit: FC = ({\n state,\n dispatch,\n onAddIncludedChats,\n onAddExcludedChats,\n onReset,\n loadedActiveChatIds,\n loadedArchivedChatIds,\n editChatFolder,\n addChatFolder,\n loadMoreChats,\n}) => {\n const [animationData, setAnimationData] = useState>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n\n const [isIncludedChatsListExpanded, setIsIncludedChatsListExpanded] = useState(false);\n const [isExcludedChatsListExpanded, setIsExcludedChatsListExpanded] = useState(false);\n\n const {\n selectedChatIds: includedChatIds,\n selectedChatTypes: includedChatTypes,\n } = selectChatFilters(state, 'included');\n const {\n selectedChatIds: excludedChatIds,\n selectedChatTypes: excludedChatTypes,\n } = selectChatFilters(state, 'excluded');\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('FoldersNew').then(setAnimationData);\n }\n }, [animationData]);\n\n useEffect(() => {\n setIsIncludedChatsListExpanded(false);\n setIsExcludedChatsListExpanded(false);\n }, [state.folderId]);\n\n const [visibleIncludedChatIds, visibleExcludedChatIds] = useMemo(() => {\n const allLoadedChatsSet = new Set([\n ...loadedActiveChatIds || [],\n ...loadedArchivedChatIds || [],\n ]);\n\n const loadedIncludedChatIds = findIntersectionWithSet(includedChatIds, allLoadedChatsSet);\n const loadedExcludedChatIds = findIntersectionWithSet(excludedChatIds, allLoadedChatsSet);\n\n return [\n isIncludedChatsListExpanded\n ? loadedIncludedChatIds\n : loadedIncludedChatIds.slice(0, INITIAL_CHATS_LIMIT - includedChatTypes.length),\n isExcludedChatsListExpanded\n ? loadedExcludedChatIds\n : loadedExcludedChatIds.slice(0, INITIAL_CHATS_LIMIT - excludedChatTypes.length),\n ];\n }, [\n excludedChatIds, includedChatIds, includedChatTypes, excludedChatTypes,\n isExcludedChatsListExpanded, isIncludedChatsListExpanded,\n loadedActiveChatIds, loadedArchivedChatIds,\n ]);\n\n useEffect(() => {\n if (\n visibleIncludedChatIds.length < includedChatIds.length\n || visibleExcludedChatIds.length < excludedChatIds.length\n ) {\n loadMoreChats({ listType: 'active' });\n }\n }, [\n loadMoreChats,\n excludedChatIds.length,\n includedChatIds.length,\n visibleExcludedChatIds.length,\n visibleIncludedChatIds.length,\n ]);\n\n const lang = useLang();\n\n function handleChange(event: React.ChangeEvent) {\n const { currentTarget } = event;\n dispatch({ type: 'setTitle', payload: currentTarget.value.trim() });\n }\n\n function handleSubmit() {\n const { title } = state.folder;\n\n if (!title) {\n dispatch({ type: 'setError', payload: ERROR_NO_TITLE });\n return;\n }\n\n if (!includedChatIds.length && !Object.keys(includedChatTypes).length) {\n dispatch({ type: 'setError', payload: ERROR_NO_CHATS });\n return;\n }\n\n dispatch({ type: 'setIsLoading', payload: true });\n if (state.mode === 'edit') {\n editChatFolder({ id: state.folderId, folderUpdate: state.folder });\n } else {\n addChatFolder({ folder: state.folder });\n }\n\n setTimeout(() => {\n onReset();\n }, SUBMIT_TIMEOUT);\n }\n\n function renderChatType(key: string, mode: 'included' | 'excluded') {\n const chatType = mode === 'included'\n ? INCLUDED_CHAT_TYPES.find(({ key: typeKey }) => typeKey === key)\n : EXCLUDED_CHAT_TYPES.find(({ key: typeKey }) => typeKey === key);\n\n if (!chatType) {\n return undefined;\n }\n\n return (\n \n {lang(chatType.title)}\n \n );\n }\n\n function renderChats(mode: 'included' | 'excluded') {\n const selectedChatTypes = mode === 'included' ? includedChatTypes : excludedChatTypes;\n const visibleChatIds = mode === 'included' ? visibleIncludedChatIds : visibleExcludedChatIds;\n\n const isExpanded = mode === 'included' ? isIncludedChatsListExpanded : isExcludedChatsListExpanded;\n const allChatIds = mode === 'included' ? includedChatIds : excludedChatIds;\n const leftChatsCount = allChatIds.length - selectedChatTypes.length - visibleChatIds.length;\n const clickHandler = mode === 'included'\n ? () => setIsIncludedChatsListExpanded(true)\n : () => setIsExcludedChatsListExpanded(true);\n\n return (\n <>\n {selectedChatTypes.map((key) => renderChatType(key, mode))}\n {visibleChatIds.map((id) => (\n \n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n ))}\n {(!isExpanded && leftChatsCount > 0) && (\n \n )}\n \n );\n }\n\n return (\n
\n
\n
\n
\n {animationData && (\n \n )}\n
\n\n {state.mode === 'create' && (\n

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

\n )}\n\n \n
\n\n
\n {state.error && state.error === ERROR_NO_CHATS && (\n

\n {state.error}\n

\n )}\n\n

{lang('FilterInclude')}

\n\n \n {lang('FilterAddChats')}\n \n\n {renderChats('included')}\n
\n\n
\n

{lang('FilterExclude')}

\n\n \n {lang('FilterAddChats')}\n \n\n {renderChats('excluded')}\n
\n
\n\n \n {state.isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { listIds } = global.chats;\n\n return {\n loadedActiveChatIds: listIds.active,\n loadedArchivedChatIds: listIds.archived,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['editChatFolder', 'addChatFolder', 'loadMoreChats']),\n)(SettingsFoldersEdit));\n","import React, {\n FC, useCallback, useRef, useEffect, memo,\n} from '../../../../lib/teact/teact';\n\nimport { isChatPrivate } from '../../../../modules/helpers';\nimport {\n INCLUDED_CHAT_TYPES,\n EXCLUDED_CHAT_TYPES,\n FolderChatType,\n} from '../../../../hooks/reducers/useFoldersReducer';\nimport useInfiniteScroll from '../../../../hooks/useInfiniteScroll';\nimport useLang from '../../../../hooks/useLang';\n\nimport Checkbox from '../../../ui/Checkbox';\nimport InputText from '../../../ui/InputText';\nimport ListItem from '../../../ui/ListItem';\nimport PrivateChatInfo from '../../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../../common/GroupChatInfo';\nimport PickerSelectedItem from '../../../common/PickerSelectedItem';\nimport InfiniteScroll from '../../../ui/InfiniteScroll';\nimport Loading from '../../../ui/Loading';\n\nimport '../../../common/Picker.scss';\nimport './SettingsFoldersChatsPicker.scss';\n\ntype OwnProps = {\n mode: 'included' | 'excluded';\n chatIds: number[];\n selectedIds: number[];\n selectedChatTypes: string[];\n filterValue?: string;\n onSelectedIdsChange: (ids: number[]) => void;\n onSelectedChatTypesChange: (types: string[]) => void;\n onFilterChange: (value: string) => void;\n onLoadMore: () => void;\n};\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\n\nconst MAX_CHATS = 100;\nconst MAX_FULL_ITEMS = 10;\nconst ALWAYS_FULL_ITEMS_COUNT = 5;\n\nconst SettingsFoldersChatsPicker: FC = ({\n mode,\n chatIds,\n selectedIds,\n selectedChatTypes,\n filterValue,\n onSelectedIdsChange,\n onSelectedChatTypesChange,\n onFilterChange,\n onLoadMore,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const chatTypes = mode === 'included' ? INCLUDED_CHAT_TYPES : EXCLUDED_CHAT_TYPES;\n const shouldMinimize = selectedIds.length + selectedChatTypes.length > MAX_FULL_ITEMS;\n const hasMaxChats = selectedIds.length >= MAX_CHATS;\n\n useEffect(() => {\n setTimeout(() => {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n });\n }, FOCUS_DELAY_MS);\n }, []);\n\n const handleItemClick = useCallback((id: number) => {\n const newSelectedIds = [...selectedIds];\n if (newSelectedIds.includes(id)) {\n newSelectedIds.splice(newSelectedIds.indexOf(id), 1);\n } else {\n newSelectedIds.push(id);\n }\n onSelectedIdsChange(newSelectedIds);\n }, [selectedIds, onSelectedIdsChange]);\n\n const handleChatTypeClick = useCallback((key: FolderChatType['key']) => {\n const newSelectedChatTypes = [...selectedChatTypes];\n if (newSelectedChatTypes.includes(key)) {\n newSelectedChatTypes.splice(newSelectedChatTypes.indexOf(key), 1);\n } else {\n newSelectedChatTypes.push(key);\n }\n onSelectedChatTypesChange(newSelectedChatTypes);\n }, [selectedChatTypes, onSelectedChatTypesChange]);\n\n const handleFilterChange = useCallback((e: React.ChangeEvent) => {\n const { value } = e.currentTarget;\n onFilterChange(value);\n }, [onFilterChange]);\n\n const lang = useLang();\n\n function renderSelectedChatType(key: string) {\n const selectedType = chatTypes.find(({ key: typeKey }) => key === typeKey);\n if (!selectedType) {\n return undefined;\n }\n\n return (\n \n );\n }\n\n function renderChatType(type: FolderChatType) {\n return (\n handleChatTypeClick(type.key)}\n ripple\n >\n \n

{lang(type.title)}

\n \n \n );\n }\n\n function renderItem(id: number) {\n const isSelected = selectedIds.includes(id);\n\n return (\n handleItemClick(id)}\n ripple\n disabled={!isSelected && hasMaxChats}\n >\n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n \n );\n }\n\n const [viewportIds, getMore] = useInfiniteScroll(onLoadMore, chatIds, Boolean(filterValue));\n\n return (\n
\n
\n {selectedChatTypes.map(renderSelectedChatType)}\n {selectedIds.map((id, i) => (\n \n ))}\n {!hasMaxChats ? (\n \n ) : (\n

\n {`Sorry, you can't add more than ${MAX_CHATS} chats.`}\n

\n )}\n
\n \n {(!viewportIds || !viewportIds.length || viewportIds.includes(chatIds[0])) && (\n <>\n

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

\n {chatTypes.map(renderChatType)}\n
\n

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

\n \n )}\n\n {viewportIds && viewportIds.length ? (\n viewportIds.map(renderItem)\n ) : viewportIds && !viewportIds.length ? (\n

Sorry, nothing found.

\n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(SettingsFoldersChatsPicker);\n","import React, {\n FC, memo, useMemo, useCallback,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\nimport { ApiChat } from '../../../../api/types';\n\nimport useLang from '../../../../hooks/useLang';\nimport { pick } from '../../../../util/iteratees';\nimport searchWords from '../../../../util/searchWords';\nimport { prepareChatList, getChatTitle } from '../../../../modules/helpers';\nimport {\n FoldersState,\n FolderEditDispatch,\n selectChatFilters,\n} from '../../../../hooks/reducers/useFoldersReducer';\n\nimport SettingsFoldersChatsPicker from './SettingsFoldersChatsPicker';\n\nimport Loading from '../../../ui/Loading';\n\ntype OwnProps = {\n mode: 'included' | 'excluded';\n state: FoldersState;\n dispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n chatsById: Record;\n listIds?: number[];\n orderedPinnedIds?: number[];\n archivedListIds?: number[];\n archivedPinnedIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsFoldersChatFilters: FC = ({\n mode,\n state,\n dispatch,\n chatsById,\n listIds,\n orderedPinnedIds,\n archivedListIds,\n archivedPinnedIds,\n loadMoreChats,\n}) => {\n const { chatFilter } = state;\n const { selectedChatIds, selectedChatTypes } = selectChatFilters(state, mode, true);\n\n const lang = useLang();\n const chats = useMemo(() => {\n const activeChatArrays = listIds\n ? prepareChatList(chatsById, listIds, orderedPinnedIds, 'all')\n : undefined;\n const archivedChatArrays = archivedListIds\n ? prepareChatList(chatsById, archivedListIds, archivedPinnedIds, 'archived')\n : undefined;\n\n if (!activeChatArrays && !archivedChatArrays) {\n return undefined;\n }\n\n return [\n ...(activeChatArrays\n ? [...activeChatArrays.pinnedChats, ...activeChatArrays.otherChats]\n : []\n ),\n ...(archivedChatArrays ? archivedChatArrays.otherChats : []),\n ];\n }, [chatsById, listIds, orderedPinnedIds, archivedListIds, archivedPinnedIds]);\n\n const displayedIds = useMemo(() => {\n if (!chats) {\n return undefined;\n }\n\n return chats\n .filter((chat) => (\n !chatFilter\n || searchWords(getChatTitle(lang, chat), chatFilter)\n || selectedChatIds.includes(chat.id)\n ))\n .map(({ id }) => id);\n }, [chats, chatFilter, lang, selectedChatIds]);\n\n const handleFilterChange = useCallback((newFilter: string) => {\n dispatch({\n type: 'setChatFilter',\n payload: newFilter,\n });\n }, [dispatch]);\n\n const handleSelectedIdsChange = useCallback((ids: number[]) => {\n if (mode === 'included') {\n dispatch({\n type: 'setIncludeFilters',\n payload: { ...state.includeFilters, includedChatIds: ids },\n });\n } else {\n dispatch({\n type: 'setExcludeFilters',\n payload: { ...state.excludeFilters, excludedChatIds: ids },\n });\n }\n }, [mode, state, dispatch]);\n\n const handleSelectedChatTypesChange = useCallback((keys: string[]) => {\n const newFilters: Record = {};\n keys.forEach((key) => {\n newFilters[key] = true;\n });\n\n if (mode === 'included') {\n dispatch({\n type: 'setIncludeFilters',\n payload: {\n includedChatIds: selectedChatIds,\n ...newFilters,\n },\n });\n } else {\n dispatch({\n type: 'setExcludeFilters',\n payload: {\n excludedChatIds: selectedChatIds,\n ...newFilters,\n },\n });\n }\n }, [mode, selectedChatIds, dispatch]);\n\n if (!displayedIds) {\n return ;\n }\n\n return (\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n orderedPinnedIds,\n },\n } = global;\n\n return {\n chatsById,\n listIds: listIds.active,\n orderedPinnedIds: orderedPinnedIds.active,\n archivedPinnedIds: orderedPinnedIds.archived,\n archivedListIds: listIds.archived,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMoreChats']),\n)(SettingsFoldersChatFilters));\n","import React, { FC, memo, useCallback } from '../../../../lib/teact/teact';\n\nimport { ApiChatFolder } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { FoldersState, FolderEditDispatch } from '../../../../hooks/reducers/useFoldersReducer';\n\nimport SettingsFoldersMain from './SettingsFoldersMain';\nimport SettingsFoldersEdit from './SettingsFoldersEdit';\nimport SettingsFoldersChatFilters from './SettingsFoldersChatFilters';\n\nimport './SettingsFolders.scss';\n\nconst TRANSITION_DURATION = 200;\n\nexport type OwnProps = {\n currentScreen: SettingsScreens;\n state: FoldersState;\n dispatch: FolderEditDispatch;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\nconst SettingsFolders: FC = ({\n currentScreen,\n state,\n dispatch,\n onScreenSelect,\n onReset,\n}) => {\n const handleReset = useCallback(() => {\n if (\n currentScreen === SettingsScreens.FoldersCreateFolder\n || currentScreen === SettingsScreens.FoldersEditFolder\n ) {\n setTimeout(() => {\n dispatch({ type: 'reset' });\n }, TRANSITION_DURATION);\n }\n\n if (\n currentScreen === SettingsScreens.FoldersIncludedChats\n || currentScreen === SettingsScreens.FoldersExcludedChats\n ) {\n if (state.mode === 'create') {\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n } else {\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }\n return;\n }\n\n onReset();\n }, [\n state.mode, dispatch,\n currentScreen, onReset, onScreenSelect,\n ]);\n\n const handleCreateFolder = useCallback(() => {\n dispatch({ type: 'reset' });\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n }, [onScreenSelect, dispatch]);\n\n const handleEditFolder = useCallback((folder: ApiChatFolder) => {\n dispatch({ type: 'editFolder', payload: folder });\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }, [dispatch, onScreenSelect]);\n\n const handleAddIncludedChats = useCallback(() => {\n dispatch({ type: 'editIncludeFilters' });\n onScreenSelect(SettingsScreens.FoldersIncludedChats);\n }, [dispatch, onScreenSelect]);\n\n const handleAddExcludedChats = useCallback(() => {\n dispatch({ type: 'editExcludeFilters' });\n onScreenSelect(SettingsScreens.FoldersExcludedChats);\n }, [dispatch, onScreenSelect]);\n\n switch (currentScreen) {\n case SettingsScreens.Folders:\n return (\n \n );\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n return (\n \n );\n case SettingsScreens.FoldersIncludedChats:\n return (\n \n );\n case SettingsScreens.FoldersExcludedChats:\n return (\n \n );\n\n default:\n return undefined;\n }\n};\n\nexport default memo(SettingsFolders);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, useMemo, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './RangeSlider.scss';\n\ntype OwnProps = {\n options?: string[];\n range?: { min: number; max: number; step?: number };\n label?: string;\n value: number;\n disabled?: boolean;\n onChange: (value: number) => void;\n};\n\nconst RangeSlider: FC = ({\n options,\n range,\n label,\n value,\n disabled,\n onChange,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n onChange(Number(event.currentTarget.value));\n }, [onChange]);\n\n const className = buildClassName(\n 'RangeSlider',\n disabled && 'disabled',\n );\n\n const trackWidth = useMemo(() => {\n if (options) {\n return (value / (options.length - 1)) * 100;\n } else if (range) {\n const possibleValuesLength = (range.max - range.min) / (range.step || 1);\n return ((value - range.min) / possibleValuesLength) * 100;\n }\n return 0;\n }, [value, options, range]);\n\n const [min, max, step] = useMemo(() => {\n if (options) {\n return [0, options.length - 1, 1];\n } else if (range) {\n return [range.min, range.max, range.step || 1];\n }\n\n return [0, 0, 0];\n }, [range, options]);\n\n return (\n
\n {label && (\n
\n {label}\n {range && (\n {value}\n )}\n
\n )}\n
\n \n \n {options && (\n
\n {options.map((option, index) => (\n onChange(index)}\n >\n {option}\n
\n ))}\n
\n )}\n
\n
\n );\n};\n\nexport default memo(RangeSlider);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiStickerSet } from '../../../api/types';\n\nimport { STICKER_SIZE_PICKER_HEADER } from '../../../config';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport { getFirstLetters } from '../../../util/textFormat';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\n\ntype OwnProps = {\n size?: number;\n stickerSet: ApiStickerSet;\n observeIntersection: ObserveFn;\n};\n\nconst StickerSetCoverAnimated: FC = ({\n size = STICKER_SIZE_PICKER_HEADER,\n stickerSet,\n observeIntersection,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaHash = `stickerSet${stickerSet.id}`;\n const lottieData = useMedia(mediaHash, !isIntersecting, ApiMediaFormat.Lottie);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(lottieData, 'slow');\n\n return (\n
\n {!shouldRenderFullMedia && getFirstLetters(stickerSet.title, 2)}\n {shouldRenderFullMedia && lottieData && (\n \n )}\n
\n );\n};\n\nexport default memo(StickerSetCoverAnimated);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiStickerSet } from '../../../api/types';\n\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport { getFirstLetters } from '../../../util/textFormat';\n\ntype OwnProps = {\n stickerSet: ApiStickerSet;\n observeIntersection: ObserveFn;\n};\n\nconst StickerSetCover: FC = ({ stickerSet, observeIntersection }) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaData = useMedia(stickerSet.hasThumbnail && `stickerSet${stickerSet.id}`, !isIntersecting);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\n\n return (\n
\n {!shouldRenderFullMedia && getFirstLetters(stickerSet.title, 2)}\n {shouldRenderFullMedia && (\n \"\"\n )}\n
\n );\n};\n\nexport default memo(StickerSetCover);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiSticker } from '../../api/types';\n\nimport { useIsIntersecting, ObserveFn } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useFlag from '../../hooks/useFlag';\nimport buildClassName from '../../util/buildClassName';\n\nimport AnimatedSticker from './AnimatedSticker';\nimport Button from '../ui/Button';\n\nimport './StickerButton.scss';\n\ntype OwnProps = {\n sticker: ApiSticker;\n size: number;\n observeIntersection: ObserveFn;\n noAnimate?: boolean;\n title?: string;\n className?: string;\n onClick?: (arg: any) => void;\n clickArg?: any;\n onUnfaveClick?: (sticker: ApiSticker) => void;\n};\n\nconst StickerButton: FC = ({\n sticker, size, observeIntersection, noAnimate, title, className, onClick, clickArg, onUnfaveClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const localMediaHash = `sticker${sticker.id}`;\n const stickerSelector = `sticker-button-${sticker.id}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const thumbDataUri = sticker.thumbnail ? sticker.thumbnail.dataUri : undefined;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !isIntersecting, ApiMediaFormat.BlobUrl);\n\n const shouldPlay = isIntersecting && !noAnimate;\n const lottieData = useMedia(sticker.isAnimated && localMediaHash, !shouldPlay, ApiMediaFormat.Lottie);\n const [isAnimationLoaded, markLoaded, unmarkLoaded] = useFlag(Boolean(lottieData));\n const canAnimatedPlay = isAnimationLoaded && shouldPlay;\n\n const {\n shouldRenderThumb,\n shouldRenderFullMedia: shouldRenderPreview,\n transitionClassNames: previewTransitionClassNames,\n } = useTransitionForMedia(previewBlobUrl || canAnimatedPlay, 'slow');\n\n // To avoid flickering\n useEffect(() => {\n if (!shouldPlay) {\n unmarkLoaded();\n }\n }, [unmarkLoaded, shouldPlay]);\n\n function handleClick() {\n if (onClick) {\n onClick(clickArg);\n }\n }\n\n function handleUnfaveClick(e: ReactMouseEvent) {\n e.stopPropagation();\n e.preventDefault();\n\n onUnfaveClick!(sticker);\n }\n\n const fullClassName = buildClassName(\n 'StickerButton',\n sticker.isAnimated && 'animated',\n stickerSelector,\n className,\n );\n\n const style = shouldRenderThumb && thumbDataUri ? `background-image: url('${thumbDataUri}');` : '';\n\n return (\n \n {shouldRenderPreview && !canAnimatedPlay && (\n // eslint-disable-next-line jsx-a11y/alt-text\n \n )}\n {shouldPlay && lottieData && (\n \n )}\n {onUnfaveClick && (\n \n \n \n )}\n \n );\n};\n\nexport default memo(StickerButton);\n","import React, {\n FC, memo,\n} from '../../../lib/teact/teact';\nimport { ApiSticker, ApiStickerSet } from '../../../api/types';\n\nimport { STICKER_SIZE_GENERAL_SETTINGS } from '../../../config';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Button from '../../ui/Button';\nimport StickerSetCoverAnimated from '../../middle/composer/StickerSetCoverAnimated';\nimport StickerSetCover from '../../middle/composer/StickerSetCover';\nimport StickerButton from '../../common/StickerButton';\n\nimport './SettingsStickerSet.scss';\n\ntype OwnProps = {\n stickerSet?: ApiStickerSet;\n observeIntersection: ObserveFn;\n onClick: (value: ApiSticker) => void;\n};\n\nconst SettingsStickerSet: FC = ({\n stickerSet,\n observeIntersection,\n onClick,\n}) => {\n const lang = useLang();\n\n if (!stickerSet || !stickerSet.stickers) {\n return undefined;\n }\n\n const firstSticker = stickerSet.stickers && stickerSet.stickers[0];\n\n if (stickerSet.hasThumbnail || !firstSticker) {\n return (\n firstSticker && onClick(firstSticker)}\n >\n \n {stickerSet.isAnimated ? (\n \n ) : (\n \n )}\n \n
\n
{stickerSet.title}
\n
{lang('StickerPack.StickerCount', stickerSet.count, 'i')}
\n
\n \n );\n } else {\n return (\n onClick(firstSticker)}\n >\n \n
\n
{stickerSet.title}
\n
{lang('StickerPack.StickerCount', stickerSet.count, 'i')}
\n
\n \n );\n }\n};\n\nexport default memo(SettingsStickerSet);\n","import React, {\n FC, useCallback, memo, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ISettings } from '../../../types';\nimport { ApiSticker, ApiStickerSet } from '../../../api/types';\n\nimport { IS_MAC_OS, IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\n\nimport ListItem from '../../ui/ListItem';\nimport RangeSlider from '../../ui/RangeSlider';\nimport Checkbox from '../../ui/Checkbox';\nimport RadioGroup from '../../ui/RadioGroup';\nimport SettingsStickerSet from './SettingsStickerSet';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = ISettings['byKey'] & {\n stickerSetIds?: string[];\n stickerSetsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [\n 'Solid and Steady',\n 'Nice and Fast',\n 'Lots of Stuff',\n];\n\nconst SettingsGeneral: FC = ({\n onScreenSelect,\n stickerSetIds,\n stickerSetsById,\n messageTextSize,\n animationLevel,\n messageSendKeyCombo,\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n shouldAutoPlayGifs,\n shouldAutoPlayVideos,\n shouldSuggestStickers,\n shouldLoopStickers,\n setSettingOption,\n loadStickerSets,\n loadAddedStickers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const stickerSettingsRef = useRef(null);\n const { observe: observeIntersectionForCovers } = useIntersectionObserver({ rootRef: stickerSettingsRef });\n const [isModalOpen, openModal, closeModal] = useFlag();\n const [sticker, setSticker] = useState();\n\n const lang = useLang();\n\n const KEYBOARD_SEND_OPTIONS = !IS_TOUCH_ENV ? [\n { value: 'enter', label: lang('lng_settings_send_enter'), subLabel: 'New line by Shift + Enter' },\n {\n value: 'ctrl-enter',\n label: lang(IS_MAC_OS ? 'lng_settings_send_cmdenter' : 'lng_settings_send_ctrlenter'),\n subLabel: 'New line by Enter',\n },\n ] : undefined;\n\n useEffect(() => {\n loadStickerSets();\n }, [loadStickerSets]);\n\n useEffect(() => {\n if (stickerSetIds && stickerSetIds.length) {\n loadAddedStickers();\n }\n }, [stickerSetIds, loadAddedStickers]);\n\n const handleAnimationLevelChange = useCallback((newLevel: number) => {\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [setSettingOption]);\n\n const handleMessageTextSizeChange = useCallback((newSize: number) => {\n document.documentElement.style.setProperty('--message-text-size', `${newSize}px`);\n\n setSettingOption({ messageTextSize: newSize });\n }, [setSettingOption]);\n\n const handleStickerSetClick = useCallback((value: ApiSticker) => {\n setSticker(value);\n openModal();\n }, [openModal]);\n\n const stickerSets = stickerSetIds && stickerSetIds.map((id: string) => {\n return stickerSetsById && stickerSetsById[id] && stickerSetsById[id].installedDate ? stickerSetsById[id] : false;\n }).filter(Boolean);\n\n return (\n
\n
\n

{lang('SETTINGS')}

\n\n \n\n onScreenSelect(SettingsScreens.GeneralChatBackground)}\n >\n {lang('ChatBackground')}\n \n
\n\n
\n

\n Animation Level\n

\n

\n Choose the desired animations amount.\n

\n\n \n
\n\n {KEYBOARD_SEND_OPTIONS && (\n
\n

{lang('Keyboard')}

\n\n setSettingOption({ messageSendKeyCombo: value })}\n selected={messageSendKeyCombo}\n />\n
\n )}\n\n
\n

{lang('AutoDownloadMedia')}

\n\n setSettingOption({ shouldAutoDownloadMediaFromContacts: isChecked })}\n />\n setSettingOption({ shouldAutoDownloadMediaInPrivateChats: isChecked })}\n />\n setSettingOption({ shouldAutoDownloadMediaInGroups: isChecked })}\n />\n setSettingOption({ shouldAutoDownloadMediaInChannels: isChecked })}\n />\n
\n\n
\n

{lang('AutoplayMedia')}

\n\n setSettingOption({ shouldAutoPlayGifs: isChecked })}\n />\n setSettingOption({ shouldAutoPlayVideos: isChecked })}\n />\n
\n\n
\n

{lang('AccDescrStickers')}

\n\n setSettingOption({ shouldSuggestStickers: isChecked })}\n />\n setSettingOption({ shouldLoopStickers: isChecked })}\n />\n\n
\n {stickerSets && stickerSets.map((stickerSet: ApiStickerSet) => (\n \n ))}\n
\n {sticker && (\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n ...pick(global.settings.byKey,\n [\n 'messageTextSize',\n 'animationLevel',\n 'messageSendKeyCombo',\n 'shouldAutoDownloadMediaFromContacts',\n 'shouldAutoDownloadMediaInPrivateChats',\n 'shouldAutoDownloadMediaInGroups',\n 'shouldAutoDownloadMediaInChannels',\n 'shouldAutoPlayGifs',\n 'shouldAutoPlayVideos',\n 'shouldSuggestStickers',\n 'shouldLoopStickers',\n ]),\n stickerSetIds: global.stickers.added.setIds,\n stickerSetsById: global.stickers.setsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setSettingOption', 'loadStickerSets', 'loadAddedStickers',\n ]),\n)(SettingsGeneral));\n","let fileSelector: HTMLInputElement;\n\nexport function openSystemFilesDialog(accept = '*', callback: (e: Event) => void, noMultiple = false) {\n if (!fileSelector) {\n fileSelector = document.createElement('input');\n fileSelector.setAttribute('type', 'file');\n }\n\n fileSelector.setAttribute('accept', accept);\n\n if (noMultiple) {\n fileSelector.removeAttribute('multiple');\n } else {\n fileSelector.setAttribute('multiple', 'multiple');\n }\n\n // eslint-disable-next-line no-null/no-null\n fileSelector.onchange = null;\n fileSelector.value = '';\n fileSelector.onchange = callback;\n\n fileSelector.click();\n}\n","/* eslint-disable eqeqeq */\n/* eslint-disable prefer-template */\n/* eslint-disable prefer-const */\n/* eslint-disable prefer-destructuring */\n/* eslint-disable one-var */\n/* eslint-disable one-var-declaration-per-line */\n\nimport { preloadImage } from './files';\n\n/**\n * HEX > RGB\n * input: 'xxxxxx' (ex. 'ed15fa') case-insensitive\n * output: [r, g, b] ([0-255, 0-255, 0-255])\n */\nexport function hex2rgb(param: string): [number, number, number] {\n return [\n parseInt(param.substring(0, 2), 16),\n parseInt(param.substring(2, 4), 16),\n parseInt(param.substring(4, 6), 16),\n ];\n}\n\n/**\n * RGB > HEX\n * input: [r, g, b] ([0-255, 0-255, 0-255])\n * output: 'xxxxxx' (ex. 'ff0000')\n */\nexport function rgb2hex(param: [number, number, number]) {\n const p0 = param[0].toString(16);\n const p1 = param[1].toString(16);\n const p2 = param[2].toString(16);\n return (p0.length == 1 ? '0' + p0 : p0) + (p1.length == 1 ? '0' + p1 : p1) + (p2.length == 1 ? '0' + p2 : p2);\n}\n\n/**\n * Converts an RGB color value to HSV. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSV_color_space.\n * Assumes r, g, and b are contained in the set [0, 255] and\n * returns h, s, and v in the set [0, 1].\n *\n * @param Number r The red color value\n * @param Number g The green color value\n * @param Number b The blue color value\n * @return Array The HSV representation\n */\nexport function rgb2hsb([r, g, b]: [number, number, number]): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n\n let max = Math.max(r, g, b), min = Math.min(r, g, b);\n let h!: number, s: number, v: number = max;\n\n let d = max - min;\n s = max == 0 ? 0 : d / max;\n\n if (max == min) {\n h = 0; // achromatic\n } else {\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n\n h /= 6;\n }\n\n return [h, s, v];\n}\n\n/**\n * Converts an HSV color value to RGB. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSV_color_space.\n * Assumes h, s, and v are contained in the set [0, 1] and\n * returns r, g, and b in the set [0, 255].\n *\n * @param Number h The hue\n * @param Number s The saturation\n * @param Number v The value\n * @return Array The RGB representation\n */\nexport function hsb2rgb([h, s, v]: [number, number, number]): [number, number, number] {\n let r!: number, g!: number, b!: number;\n\n let i = Math.floor(h * 6);\n let f = h * 6 - i;\n let p = v * (1 - s);\n let q = v * (1 - f * s);\n let t = v * (1 - (1 - f) * s);\n\n switch (i % 6) {\n case 0:\n r = v;\n g = t;\n b = p;\n break;\n case 1:\n r = q;\n g = v;\n b = p;\n break;\n case 2:\n r = p;\n g = v;\n b = t;\n break;\n case 3:\n r = p;\n g = q;\n b = v;\n break;\n case 4:\n r = t;\n g = p;\n b = v;\n break;\n case 5:\n r = v;\n g = p;\n b = q;\n break;\n }\n\n return [\n Math.round(r * 255),\n Math.round(g * 255),\n Math.round(b * 255),\n ];\n}\n\nexport async function getAverageColor(url: string): Promise<[number, number, number]> {\n // Only visit every 5 pixels\n const blockSize = 5;\n const defaultRGB: [number, number, number] = [0, 0, 0];\n let data;\n let width;\n let height;\n let i = -4;\n let length;\n let rgb: [number, number, number] = [0, 0, 0];\n let count = 0;\n\n const canvas = document.createElement('canvas');\n const context = canvas.getContext && canvas.getContext('2d');\n if (!context) {\n return defaultRGB;\n }\n\n const image = await preloadImage(url);\n height = image.naturalHeight || image.offsetHeight || image.height;\n width = image.naturalWidth || image.offsetWidth || image.width;\n canvas.height = height;\n canvas.width = width;\n\n context.drawImage(image, 0, 0);\n\n try {\n data = context.getImageData(0, 0, width, height);\n } catch (e) {\n return defaultRGB;\n }\n\n length = data.data.length;\n\n // eslint-disable-next-line no-cond-assign\n while ((i += blockSize * 4) < length) {\n ++count;\n rgb[0] += data.data[i];\n rgb[1] += data.data[i + 1];\n rgb[2] += data.data[i + 2];\n }\n\n rgb[0] = Math.floor(rgb[0] / count);\n rgb[1] = Math.floor(rgb[1] / count);\n rgb[2] = Math.floor(rgb[2] / count);\n\n return rgb;\n}\n\n// eslint-disable-next-line max-len\n// Function was adapted from https://github.com/telegramdesktop/tdesktop/blob/35ff621b5b52f7e3553fb0f990ea13ade7101b8e/Telegram/SourceFiles/data/data_wall_paper.cpp#L518\nexport function getPatternColor(rgbColor: [number, number, number]) {\n let [hue, saturation, value] = rgb2hsb(rgbColor);\n\n saturation = Math.min(1, saturation + 0.05 + 0.1 * (1 - saturation));\n value = value > 0.5\n ? Math.max(0, value * 0.65)\n : Math.max(0, Math.min(1, 1 - value * 0.65));\n\n return `hsla(${hue * 360}, ${saturation * 100}%, ${value * 100}%, .4)`;\n}\n","import React, {\n FC, memo, useCallback, useEffect, useState, useRef,\n} from '../../../lib/teact/teact';\nimport { ApiWallpaper } from '../../../api/types';\nimport { ThemeKey, UPLOADING_WALLPAPER_SLUG } from '../../../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../../../config';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { fetchBlob } from '../../../util/files';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport useMedia from '../../../hooks/useMedia';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useCanvasBlur from '../../../hooks/useCanvasBlur';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './WallpaperTile.scss';\n\ntype OwnProps = {\n wallpaper: ApiWallpaper;\n theme: ThemeKey;\n isSelected: boolean;\n onClick: (slug: string) => void;\n};\n\nconst WallpaperTile: FC = ({\n wallpaper,\n theme,\n isSelected,\n onClick,\n}) => {\n const { slug, document } = wallpaper;\n const localMediaHash = `wallpaper${document.id!}`;\n const localBlobUrl = document.previewBlobUrl;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`);\n const thumbRef = useCanvasBlur(\n document.thumbnail && document.thumbnail.dataUri,\n Boolean(previewBlobUrl),\n true,\n );\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(previewBlobUrl || localBlobUrl, 'slow');\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(false);\n const {\n mediaData: fullMedia, downloadProgress,\n } = useMediaWithDownloadProgress(localMediaHash, !isDownloadAllowed);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const { shouldRender: shouldRenderSpinner, transitionClassNames: spinnerClassNames } = useShowTransition(\n (isDownloadAllowed && !fullMedia) || slug === UPLOADING_WALLPAPER_SLUG,\n undefined,\n wasDownloadDisabled,\n 'slow',\n );\n // To prevent triggering of the effect for useCallback\n const cacheKeyRef = useRef();\n cacheKeyRef.current = theme;\n\n const handleSelect = useCallback(() => {\n (async () => {\n const blob = await fetchBlob(fullMedia!);\n await cacheApi.save(CUSTOM_BG_CACHE_NAME, cacheKeyRef.current!, blob);\n onClick(slug);\n })();\n }, [fullMedia, onClick, slug]);\n\n useEffect(() => {\n if (fullMedia) {\n handleSelect();\n }\n }, [fullMedia, handleSelect]);\n\n const handleClick = useCallback(() => {\n if (fullMedia) {\n handleSelect();\n } else {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n }\n }, [fullMedia, handleSelect]);\n\n const className = buildClassName(\n 'WallpaperTile',\n isSelected && 'selected',\n );\n\n return (\n
\n
\n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n
\n
\n );\n};\n\nexport default memo(WallpaperTile);\n","import React, {\n FC, memo, useEffect, useCallback, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ThemeKey, UPLOADING_WALLPAPER_SLUG } from '../../../types';\nimport { ApiWallpaper } from '../../../api/types';\n\nimport { DARK_THEME_PATTERN_COLOR, DEFAULT_PATTERN_COLOR } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { throttle } from '../../../util/schedulers';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport { getAverageColor, getPatternColor, rgb2hex } from '../../../util/colors';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Loading from '../../ui/Loading';\nimport WallpaperTile from './WallpaperTile';\n\nimport './SettingsGeneralBackground.scss';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n background?: string;\n isBlurred?: boolean;\n loadedWallpapers?: ApiWallpaper[];\n theme: ThemeKey;\n};\n\ntype DispatchProps = Pick;\n\nconst SUPPORTED_TYPES = 'image/jpeg';\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst SettingsGeneralBackground: FC = ({\n onScreenSelect,\n background,\n isBlurred,\n loadedWallpapers,\n theme,\n loadWallpapers,\n uploadWallpaper,\n setThemeSettings,\n}) => {\n const themeRef = useRef();\n themeRef.current = theme;\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadWallpapers();\n });\n }, [loadWallpapers]);\n\n const handleFileSelect = useCallback((e: Event) => {\n const { files } = e.target as HTMLInputElement;\n\n if (files && files.length > 0) {\n uploadWallpaper(files[0]);\n }\n }, [uploadWallpaper]);\n\n const handleUploadWallpaper = useCallback(() => {\n openSystemFilesDialog(SUPPORTED_TYPES, handleFileSelect, true);\n }, [handleFileSelect]);\n\n const handleSetColor = useCallback(() => {\n onScreenSelect(SettingsScreens.GeneralChatBackgroundColor);\n }, [onScreenSelect]);\n\n const handleResetToDefault = useCallback(() => {\n setThemeSettings({\n theme,\n background: undefined,\n backgroundColor: undefined,\n isBlurred: true,\n patternColor: theme === 'dark' ? DARK_THEME_PATTERN_COLOR : DEFAULT_PATTERN_COLOR,\n });\n }, [setThemeSettings, theme]);\n\n const handleWallPaperSelect = useCallback((slug: string) => {\n setThemeSettings({ theme: themeRef.current, background: slug });\n const currentWallpaper = loadedWallpapers && loadedWallpapers.find((wallpaper) => wallpaper.slug === slug);\n if (currentWallpaper && currentWallpaper.document.thumbnail) {\n getAverageColor(currentWallpaper.document.thumbnail.dataUri)\n .then((color) => {\n const patternColor = getPatternColor(color);\n const rgbColor = `#${rgb2hex(color)}`;\n setThemeSettings({ theme: themeRef.current, backgroundColor: rgbColor, patternColor });\n });\n }\n }, [loadedWallpapers, setThemeSettings]);\n\n const handleWallPaperBlurChange = useCallback((e: React.ChangeEvent) => {\n setThemeSettings({ theme: themeRef.current, isBlurred: e.target.checked });\n }, [setThemeSettings]);\n\n const lang = useLang();\n\n const isUploading = loadedWallpapers && loadedWallpapers[0] && loadedWallpapers[0].slug === UPLOADING_WALLPAPER_SLUG;\n\n return (\n
\n
\n \n {lang('UploadImage')}\n \n\n \n {lang('SetColor')}\n \n\n \n {lang('ThemeResetToDefaults')}\n \n\n \n
\n\n {loadedWallpapers ? (\n
\n {loadedWallpapers.map((wallpaper) => (\n \n ))}\n
\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { background, isBlurred } = global.settings.themes[theme] || {};\n const { loadedWallpapers } = global.settings;\n\n return {\n background,\n isBlurred,\n loadedWallpapers,\n theme,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWallpapers', 'uploadWallpaper', 'setThemeSettings',\n ]),\n)(SettingsGeneralBackground));\n","import { ChangeEvent, MutableRefObject, RefObject } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ThemeKey } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport {\n getPatternColor, hex2rgb, hsb2rgb, rgb2hex, rgb2hsb,\n} from '../../../util/colors';\nimport { captureEvents, RealTouchEvent } from '../../../util/captureEvents';\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport InputText from '../../ui/InputText';\n\nimport './SettingsGeneralBackgroundColor.scss';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n backgroundColor?: string;\n theme: ThemeKey;\n};\n\ntype DispatchProps = Pick;\n\ninterface CanvasRects {\n colorRect: {\n offsetLeft: number;\n top: number;\n width: number;\n height: number;\n };\n hueRect: {\n offsetLeft: number;\n width: number;\n };\n}\n\nconst DEFAULT_HSB = rgb2hsb(hex2rgb('e6ebee'));\nconst PREDEFINED_COLORS = [\n '#e6ebee', '#b2cee1', '#008dd0', '#c6e7cb', '#c4e1a6', '#60b16e',\n '#ccd0af', '#a6a997', '#7a7072', '#fdd7af', '#fdb76e', '#dd8851',\n];\n\nconst SettingsGeneralBackground: FC = ({\n theme,\n backgroundColor,\n setThemeSettings,\n}) => {\n const themeRef = useRef();\n themeRef.current = theme;\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 colorPickerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const huePickerRef = useRef(null);\n const isFirstRunRef = useRef(true);\n\n const [hsb, setHsb] = useState(getInitialHsb(backgroundColor));\n // Cache for drag handlers\n const hsbRef = useRef(hsb);\n useEffect(() => {\n hsbRef.current = hsb;\n }, [hsb]);\n\n const [isDragging, markIsDragging, unmarkIsDragging] = useFlag();\n const [rgbInput, setRgbInput] = useState('');\n const [hexInput, setHexInput] = useState('');\n\n const rectsRef = useRef();\n const colorCtxRef = useRef();\n\n // Setup: cache rects, subscribe for drag events\n useEffect(() => {\n // We use `offsetLeft` instead of `left` to support screen transition\n const colorRect = {\n offsetLeft: colorPickerRef.current!.offsetLeft,\n ...pick(colorPickerRef.current!.getBoundingClientRect(), ['top', 'width', 'height']),\n };\n const hueRect = {\n offsetLeft: huePickerRef.current!.offsetLeft,\n ...pick(huePickerRef.current!.getBoundingClientRect(), ['width']),\n };\n\n rectsRef.current = { colorRect, hueRect };\n\n function handleColorDrag(e: MouseEvent | RealTouchEvent) {\n const colorPosition = [\n Math.min(Math.max(0, e.pageX! - colorRect.offsetLeft), colorRect.width - 1),\n Math.min(Math.max(0, e.pageY! - colorRect.top + containerRef.current!.scrollTop), colorRect.height - 1),\n ];\n\n const { huePosition } = hsb2positions(hsbRef.current, rectsRef.current!);\n\n setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!));\n markIsDragging();\n }\n\n captureEvents(colorPickerRef.current!, {\n onCapture: handleColorDrag,\n onDrag: handleColorDrag,\n onRelease: unmarkIsDragging,\n onClick: unmarkIsDragging,\n withCursor: true,\n });\n\n function handleHueDrag(e: MouseEvent | RealTouchEvent) {\n const { colorPosition } = hsb2positions(hsbRef.current, rectsRef.current!);\n const huePosition = Math.min(Math.max(0, e.pageX! - hueRect.offsetLeft), hueRect.width - 1);\n\n setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!));\n markIsDragging();\n }\n\n captureEvents(huePickerRef.current!, {\n onCapture: handleHueDrag,\n onDrag: handleHueDrag,\n onRelease: unmarkIsDragging,\n onClick: unmarkIsDragging,\n withCursor: true,\n });\n }, [markIsDragging, unmarkIsDragging]);\n\n const { colorPosition = [0, 0], huePosition = 0 } = rectsRef.current ? hsb2positions(hsb, rectsRef.current) : {};\n const hex = rgb2hex(hsb2rgb(hsb));\n const hue = hsb[0];\n const hueHex = rgb2hex(hsb2rgb([hue, 1, 1]));\n\n // Save value and update inputs when HSL changes\n useEffect(() => {\n const rgb = hsb2rgb(hsb);\n const color = `#${rgb2hex(rgb)}`;\n\n setRgbInput(rgb.join(', '));\n setHexInput(color);\n\n if (!isFirstRunRef.current) {\n const patternColor = getPatternColor(rgb);\n setThemeSettings({\n theme: themeRef.current,\n background: undefined,\n backgroundColor: color,\n patternColor,\n });\n }\n isFirstRunRef.current = false;\n }, [hsb, setThemeSettings]);\n\n // Redraw color picker when hue changes\n useEffect(() => {\n drawColor(colorPickerRef.current!.firstChild as HTMLCanvasElement, hue, colorCtxRef, rectsRef);\n }, [hue]);\n\n // Initially draw hue picker\n useEffect(() => {\n drawHue(huePickerRef.current!.firstChild as HTMLCanvasElement);\n }, []);\n\n const handleRgbChange = useCallback((e: ChangeEvent) => {\n const rgbValue = e.currentTarget.value.replace(/[^\\d, ]/g, '').slice(0, 13);\n\n if (rgbValue.match(/^\\d{1,3},\\s?\\d{1,3},\\s?\\d{1,3}$/)) {\n const rgb = rgbValue.split(',').map((channel) => Number(channel.trim())) as [number, number, number];\n setHsb(rgb2hsb(rgb));\n }\n\n e.currentTarget.value = rgbValue;\n }, []);\n\n const handleHexChange = useCallback((e: ChangeEvent) => {\n const hexValue = e.currentTarget.value.replace(/[^0-9a-fA-F]/g, '').slice(0, 6);\n\n if (hexValue.match(/^#?[0-9a-fA-F]{6}$/)) {\n setHsb(rgb2hsb(hex2rgb(hexValue.replace('#', ''))));\n }\n\n e.currentTarget.value = hexValue;\n }, []);\n\n const handlePredefinedColorClick = useCallback((e: React.MouseEvent) => {\n setHsb(rgb2hsb(hex2rgb(e.currentTarget.dataset.color!.replace('#', ''))));\n }, []);\n\n const className = buildClassName(\n 'SettingsGeneralBackgroundColor settings-content custom-scroll',\n isDragging && 'is-dragging',\n );\n\n return (\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n {PREDEFINED_COLORS.map((color) => (\n \n ))}\n
\n
\n );\n};\n\nfunction getInitialHsb(backgroundColor?: string) {\n return backgroundColor && backgroundColor.startsWith('#')\n ? rgb2hsb(hex2rgb(backgroundColor.replace('#', '')))\n : DEFAULT_HSB;\n}\n\nfunction hsb2positions(hsb: [number, number, number], rects: CanvasRects) {\n return {\n colorPosition: [\n Math.round((hsb[1]) * (rects.colorRect.width - 1)),\n Math.round((1 - hsb[2]) * (rects.colorRect.height - 1)),\n ],\n huePosition: Math.round(hsb[0] * (rects.hueRect.width - 1)),\n };\n}\n\nfunction positions2hsb(\n { colorPosition, huePosition }: { colorPosition: number[]; huePosition: number },\n rects: CanvasRects,\n): [number, number, number] {\n return [\n huePosition / (rects.hueRect.width - 1),\n colorPosition[0] / (rects.colorRect.width - 1),\n 1 - colorPosition[1] / (rects.colorRect.height - 1),\n ];\n}\n\nfunction drawColor(\n canvas: HTMLCanvasElement,\n hue: number,\n colorCtxRef: MutableRefObject,\n rectsRef: RefObject,\n) {\n let w: number;\n let h: number;\n let ctx: CanvasRenderingContext2D;\n\n if (!colorCtxRef.current || !rectsRef.current) {\n // First run\n w = canvas.offsetWidth;\n h = canvas.offsetHeight;\n ctx = canvas.getContext('2d')!;\n\n canvas.width = w;\n canvas.height = h;\n\n colorCtxRef.current = ctx;\n } else {\n w = rectsRef.current.colorRect.width;\n h = rectsRef.current.colorRect.height;\n ctx = colorCtxRef.current;\n }\n\n const imgData = ctx!.createImageData(w, h);\n const pixels = imgData.data;\n const col = hsb2rgb([hue, 1, 1]);\n\n let index = 0;\n\n for (let y = 0; y < h; y++) {\n const perY = 1 - y / (h - 1);\n const st = [255 * perY, 255 * perY, 255 * perY];\n const ed = [col[0] * perY, col[1] * perY, col[2] * perY];\n for (let x = 0; x < w; x++) {\n const perX = x / (w - 1);\n pixels[index++] = st[0] + (ed[0] - st[0]) * perX;\n pixels[index++] = st[1] + (ed[1] - st[1]) * perX;\n pixels[index++] = st[2] + (ed[2] - st[2]) * perX;\n pixels[index++] = 255;\n }\n }\n\n ctx!.putImageData(imgData, 0, 0);\n}\n\nfunction drawHue(canvas: HTMLCanvasElement) {\n const w = canvas.offsetWidth;\n const h = 1;\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext('2d')!;\n\n const imgData = ctx.createImageData(w, h);\n const pixels = imgData.data;\n\n let index = 0;\n\n for (let x = 0; x < w; x++) {\n const hue = x / (w - 1);\n const rgb = hsb2rgb([hue, 1, 1]);\n /* eslint-disable prefer-destructuring */\n pixels[index++] = rgb[0];\n pixels[index++] = rgb[1];\n pixels[index++] = rgb[2];\n /* eslint-enable prefer-destructuring */\n pixels[index++] = 255;\n }\n\n ctx.putImageData(imgData, 0, 0);\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { backgroundColor } = global.settings.themes[theme] || {};\n return {\n backgroundColor,\n theme,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setThemeSettings']),\n)(SettingsGeneralBackground));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport Checkbox from '../../ui/Checkbox';\n\ntype StateProps = {\n hasPrivateChatsNotifications: boolean;\n hasPrivateChatsMessagePreview: boolean;\n hasGroupNotifications: boolean;\n hasGroupMessagePreview: boolean;\n hasBroadcastNotifications: boolean;\n hasBroadcastMessagePreview: boolean;\n hasContactJoinedNotifications: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsNotifications: FC = ({\n hasPrivateChatsNotifications,\n hasPrivateChatsMessagePreview,\n hasGroupNotifications,\n hasGroupMessagePreview,\n hasBroadcastNotifications,\n hasBroadcastMessagePreview,\n hasContactJoinedNotifications,\n loadNotificationSettings,\n updateContactSignUpNotification,\n updateNotificationSettings,\n}) => {\n useEffect(() => {\n loadNotificationSettings();\n }, [loadNotificationSettings]);\n\n const handleSettingsChange = useCallback((\n e: ChangeEvent,\n peerType: 'contact' | 'group' | 'broadcast',\n setting: 'silent' | 'showPreviews',\n ) => {\n const currentIsSilent = peerType === 'contact'\n ? !hasPrivateChatsNotifications\n : !(peerType === 'group' ? hasGroupNotifications : hasBroadcastNotifications);\n const currentShouldShowPreviews = peerType === 'contact'\n ? hasPrivateChatsMessagePreview\n : (peerType === 'group' ? hasGroupMessagePreview : hasBroadcastMessagePreview);\n\n updateNotificationSettings({\n peerType,\n ...(setting === 'silent' && { isSilent: !e.target.checked, shouldShowPreviews: currentShouldShowPreviews }),\n ...(setting === 'showPreviews' && { shouldShowPreviews: e.target.checked, isSilent: currentIsSilent }),\n });\n }, [\n hasBroadcastMessagePreview, hasBroadcastNotifications,\n hasGroupMessagePreview, hasGroupNotifications,\n hasPrivateChatsMessagePreview, hasPrivateChatsNotifications,\n updateNotificationSettings,\n ]);\n\n const handleContactNotificationChange = useCallback((e: ChangeEvent) => {\n updateContactSignUpNotification({\n isSilent: !e.target.checked,\n });\n }, [updateContactSignUpNotification]);\n\n const lang = useLang();\n\n return (\n
\n
\n

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

\n\n { handleSettingsChange(e, 'contact', 'silent'); }}\n />\n { handleSettingsChange(e, 'contact', 'showPreviews'); }}\n />\n
\n\n
\n

{lang('FilterGroups')}

\n\n { handleSettingsChange(e, 'group', 'silent'); }}\n />\n { handleSettingsChange(e, 'group', 'showPreviews'); }}\n />\n
\n\n
\n

{lang('FilterChannels')}

\n\n { handleSettingsChange(e, 'broadcast', 'silent'); }}\n />\n { handleSettingsChange(e, 'broadcast', 'showPreviews'); }}\n />\n
\n\n
\n

{lang('PhoneOther')}

\n\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global): StateProps => {\n return {\n hasPrivateChatsNotifications: Boolean(global.settings.byKey.hasPrivateChatsNotifications),\n hasPrivateChatsMessagePreview: Boolean(global.settings.byKey.hasPrivateChatsMessagePreview),\n hasGroupNotifications: Boolean(global.settings.byKey.hasGroupNotifications),\n hasGroupMessagePreview: Boolean(global.settings.byKey.hasGroupMessagePreview),\n hasBroadcastNotifications: Boolean(global.settings.byKey.hasBroadcastNotifications),\n hasBroadcastMessagePreview: Boolean(global.settings.byKey.hasBroadcastMessagePreview),\n hasContactJoinedNotifications: Boolean(global.settings.byKey.hasContactJoinedNotifications),\n };\n},\n(setGlobal, actions): DispatchProps => pick(actions, [\n 'loadNotificationSettings',\n 'updateContactSignUpNotification',\n 'updateNotificationSettings',\n]))(SettingsNotifications));\n","import React, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { PrivacyVisibility, SettingsScreens } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n hasPassword?: boolean;\n blockedCount: number;\n sessionsCount: number;\n visibilityPrivacyPhoneNumber?: PrivacyVisibility;\n visibilityPrivacyLastSeen?: PrivacyVisibility;\n visibilityPrivacyProfilePhoto?: PrivacyVisibility;\n visibilityPrivacyForwarding?: PrivacyVisibility;\n visibilityPrivacyGroupChats?: PrivacyVisibility;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacy: FC = ({\n onScreenSelect,\n hasPassword,\n blockedCount,\n sessionsCount,\n visibilityPrivacyPhoneNumber,\n visibilityPrivacyLastSeen,\n visibilityPrivacyProfilePhoto,\n visibilityPrivacyForwarding,\n visibilityPrivacyGroupChats,\n loadPrivacySettings,\n loadBlockedContacts,\n loadAuthorizations,\n}) => {\n useEffect(() => {\n loadBlockedContacts();\n loadAuthorizations();\n loadPrivacySettings();\n }, [loadBlockedContacts, loadAuthorizations, loadPrivacySettings]);\n\n const lang = useLang();\n\n function getVisibilityValue(visibility?: PrivacyVisibility) {\n switch (visibility) {\n case 'everybody':\n return lang('P2PEverybody');\n\n case 'contacts':\n return lang('P2PContacts');\n\n case 'nobody':\n return lang('P2PNobody');\n }\n\n return undefined;\n }\n\n return (\n
\n
\n onScreenSelect(SettingsScreens.PrivacyBlockedUsers)}\n >\n
\n {lang('BlockedUsers')}\n {blockedCount > 0 && (\n \n {lang('Users', blockedCount)}\n \n )}\n
\n \n onScreenSelect(\n hasPassword ? SettingsScreens.TwoFaEnabled : SettingsScreens.TwoFaDisabled,\n )}\n >\n
\n {lang('TwoStepVerification')}\n \n {lang(hasPassword ? 'PasswordOn' : 'PasswordOff')}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyActiveSessions)}\n >\n
\n {lang('SessionsTitle')}\n {sessionsCount > 0 && (\n \n {sessionsCount === 1 ? '1 session' : `${sessionsCount} sessions`}\n \n )}\n
\n \n
\n\n
\n

{lang('PrivacyTitle')}

\n\n onScreenSelect(SettingsScreens.PrivacyPhoneNumber)}\n >\n
\n {lang('PrivacyPhoneTitle')}\n \n {getVisibilityValue(visibilityPrivacyPhoneNumber)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyLastSeen)}\n >\n
\n {lang('LastSeenTitle')}\n \n {getVisibilityValue(visibilityPrivacyLastSeen)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyProfilePhoto)}\n >\n
\n {lang('PrivacyProfilePhotoTitle')}\n \n {getVisibilityValue(visibilityPrivacyProfilePhoto)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyForwarding)}\n >\n
\n {lang('PrivacyForwardsTitle')}\n \n {getVisibilityValue(visibilityPrivacyForwarding)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyGroupChats)}\n >\n
\n {lang('WhoCanAddMe')}\n \n {getVisibilityValue(visibilityPrivacyGroupChats)}\n \n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n settings: {\n byKey: { hasPassword },\n privacy,\n },\n blocked,\n activeSessions,\n } = global;\n\n return {\n hasPassword,\n blockedCount: blocked.totalCount,\n sessionsCount: activeSessions.length,\n visibilityPrivacyPhoneNumber: privacy.phoneNumber && privacy.phoneNumber.visibility,\n visibilityPrivacyLastSeen: privacy.lastSeen && privacy.lastSeen.visibility,\n visibilityPrivacyProfilePhoto: privacy.profilePhoto && privacy.profilePhoto.visibility,\n visibilityPrivacyForwarding: privacy.forwards && privacy.forwards.visibility,\n visibilityPrivacyGroupChats: privacy.chatInvite && privacy.chatInvite.visibility,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadBlockedContacts', 'loadAuthorizations', 'loadPrivacySettings',\n ]),\n)(SettingsPrivacy));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ISettings } from '../../../types';\nimport { ApiLanguage } from '../../../api/types';\n\nimport { setLanguage } from '../../../util/langProvider';\nimport { pick } from '../../../util/iteratees';\n\nimport RadioGroup from '../../ui/RadioGroup';\nimport Loading from '../../ui/Loading';\nimport useFlag from '../../../hooks/useFlag';\n\ntype StateProps = Pick;\n\ntype DispatchProps = Pick;\n\nconst SettingsLanguage: FC = ({\n languages,\n language,\n loadLanguages,\n setSettingOption,\n}) => {\n const [selectedLanguage, setSelectedLanguage] = useState(language);\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n // TODO Throttle\n useEffect(() => {\n loadLanguages();\n }, [loadLanguages]);\n\n const handleChange = useCallback((langCode: string) => {\n setSelectedLanguage(langCode);\n markIsLoading();\n\n setLanguage(langCode, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: langCode });\n });\n }, [markIsLoading, unmarkIsLoading, setSettingOption]);\n\n const options = useMemo(() => {\n return languages ? buildOptions(languages) : undefined;\n }, [languages]);\n\n return (\n
\n {options ? (\n \n ) : (\n \n )}\n
\n );\n};\n\nfunction buildOptions(languages: ApiLanguage[]) {\n const currentLangCode = (window.navigator.language || 'en').toLowerCase();\n const shortLangCode = currentLangCode.substr(0, 2);\n\n return languages.map(({ langCode, nativeName, name }) => ({\n value: langCode,\n label: nativeName,\n subLabel: name,\n })).sort((a) => {\n return currentLangCode && (a.value === currentLangCode || a.value === shortLangCode) ? -1 : 0;\n });\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n languages: global.settings.byKey.languages,\n language: global.settings.byKey.language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadLanguages', 'setSettingOption',\n ]),\n)(SettingsLanguage));\n","import { ApiPrivacyKey, SettingsScreens } from '../../../../types';\n\nexport function getPrivacyKey(screen: SettingsScreens): ApiPrivacyKey | undefined {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n return 'phoneNumber';\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n return 'lastSeen';\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n return 'profilePhoto';\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n return 'forwards';\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return 'chatInvite';\n }\n\n return undefined;\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\nimport { ApiPrivacySettings, SettingsScreens } from '../../../types';\n\nimport useLang from '../../../hooks/useLang';\nimport { pick } from '../../../util/iteratees';\n\nimport ListItem from '../../ui/ListItem';\nimport RadioGroup from '../../ui/RadioGroup';\nimport { getPrivacyKey } from './helper/privacy';\n\ntype OwnProps = {\n screen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = Partial & {\n chatsById?: Record;\n usersById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyVisibility: FC = ({\n screen,\n onScreenSelect,\n visibility,\n allowUserIds,\n allowChatIds,\n blockUserIds,\n blockChatIds,\n chatsById,\n setPrivacyVisibility,\n}) => {\n const lang = useLang();\n\n const visibilityOptions = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyGroupChats:\n return [\n { value: 'everybody', label: lang('P2PEverybody') },\n { value: 'contacts', label: lang('P2PContacts') },\n ];\n\n default:\n return [\n { value: 'everybody', label: lang('P2PEverybody') },\n { value: 'contacts', label: lang('P2PContacts') },\n { value: 'nobody', label: lang('P2PNobody') },\n ];\n }\n }, [lang, screen]);\n\n const exceptionLists = {\n shouldShowDenied: visibility !== 'nobody',\n shouldShowAllowed: visibility !== 'everybody',\n };\n\n const privacyKey = getPrivacyKey(screen);\n\n const headerText = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return lang('PrivacyPhoneTitle');\n case SettingsScreens.PrivacyLastSeen:\n return lang('LastSeenTitle');\n case SettingsScreens.PrivacyProfilePhoto:\n return lang('PrivacyProfilePhotoTitle');\n case SettingsScreens.PrivacyForwarding:\n return lang('PrivacyForwardsTitle');\n case SettingsScreens.PrivacyGroupChats:\n return lang('WhoCanAddMe');\n default:\n return undefined;\n }\n }, [lang, screen]);\n\n const descriptionText = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyLastSeen:\n return lang('CustomHelp');\n default:\n return undefined;\n }\n }, [lang, screen]);\n\n const allowedContactsScreen = (() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return SettingsScreens.PrivacyPhoneNumberAllowedContacts;\n case SettingsScreens.PrivacyLastSeen:\n return SettingsScreens.PrivacyLastSeenAllowedContacts;\n case SettingsScreens.PrivacyProfilePhoto:\n return SettingsScreens.PrivacyProfilePhotoAllowedContacts;\n case SettingsScreens.PrivacyForwarding:\n return SettingsScreens.PrivacyForwardingAllowedContacts;\n default:\n return SettingsScreens.PrivacyGroupChatsAllowedContacts;\n }\n })();\n\n const deniedContactsScreen = (() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return SettingsScreens.PrivacyPhoneNumberDeniedContacts;\n case SettingsScreens.PrivacyLastSeen:\n return SettingsScreens.PrivacyLastSeenDeniedContacts;\n case SettingsScreens.PrivacyProfilePhoto:\n return SettingsScreens.PrivacyProfilePhotoDeniedContacts;\n case SettingsScreens.PrivacyForwarding:\n return SettingsScreens.PrivacyForwardingDeniedContacts;\n default:\n return SettingsScreens.PrivacyGroupChatsDeniedContacts;\n }\n })();\n\n const allowedCount = useMemo(() => {\n if (!allowUserIds || !allowChatIds || !chatsById) {\n return 0;\n }\n\n return allowChatIds.reduce((result, chatId) => {\n return result + (chatsById[chatId] ? chatsById[chatId].membersCount! : 0);\n }, allowUserIds.length);\n }, [allowChatIds, allowUserIds, chatsById]);\n\n const blockCount = useMemo(() => {\n if (!blockUserIds || !blockChatIds || !chatsById) {\n return 0;\n }\n\n return blockChatIds.reduce((result, chatId) => {\n return result + (chatsById[chatId] ? chatsById[chatId].membersCount! : 0);\n }, blockUserIds.length);\n }, [blockChatIds, blockUserIds, chatsById]);\n\n const handleVisibilityChange = useCallback((value) => {\n setPrivacyVisibility({\n privacyKey,\n visibility: value,\n });\n }, [privacyKey, setPrivacyVisibility]);\n\n return (\n
\n
\n

{headerText}

\n\n \n\n {descriptionText && (\n

{descriptionText}

\n )}\n
\n\n
\n

{lang('PrivacyExceptions')}

\n\n {exceptionLists.shouldShowAllowed && (\n { onScreenSelect(allowedContactsScreen); }}\n >\n
\n {allowedCount > 0 && +{allowedCount}}\n {lang('AlwaysShareWith')}\n {lang('EditAdminAddUsers')}\n
\n \n )}\n {exceptionLists.shouldShowDenied && (\n { onScreenSelect(deniedContactsScreen); }}\n >\n
\n {blockCount > 0 && −{blockCount}}\n {lang('NeverShareWith')}\n {lang('EditAdminAddUsers')}\n
\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { screen }): StateProps => {\n let privacySettings: ApiPrivacySettings | undefined;\n\n const {\n chats: { byId: chatsById },\n settings: { privacy },\n } = global;\n\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n privacySettings = privacy.phoneNumber;\n break;\n\n case SettingsScreens.PrivacyLastSeen:\n privacySettings = privacy.lastSeen;\n break;\n\n case SettingsScreens.PrivacyProfilePhoto:\n privacySettings = privacy.profilePhoto;\n break;\n\n case SettingsScreens.PrivacyForwarding:\n privacySettings = privacy.forwards;\n break;\n\n case SettingsScreens.PrivacyGroupChats:\n privacySettings = privacy.chatInvite;\n break;\n }\n\n if (!privacySettings) {\n return {};\n }\n\n return {\n ...privacySettings,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setPrivacyVisibility']),\n)(SettingsPrivacyVisibility));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiSession } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { formatPastTimeShort } from '../../../util/dateFormat';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype StateProps = {\n activeSessions: ApiSession[];\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyActiveSessions: FC = ({\n activeSessions,\n loadAuthorizations,\n terminateAuthorization,\n terminateAllAuthorizations,\n}) => {\n const [isConfirmTerminateAllDialogOpen, openConfirmTerminateAllDialog, closeConfirmTerminateAllDialog] = useFlag();\n useEffect(() => {\n loadAuthorizations();\n }, [loadAuthorizations]);\n\n const handleTerminateSessionClick = useCallback((hash: string) => {\n terminateAuthorization({ hash });\n }, [terminateAuthorization]);\n\n const handleTerminateAllSessions = useCallback(() => {\n closeConfirmTerminateAllDialog();\n terminateAllAuthorizations();\n }, [closeConfirmTerminateAllDialog, terminateAllAuthorizations]);\n\n const currentSession = useMemo(() => {\n return activeSessions.find((session) => session.isCurrent);\n }, [activeSessions]);\n\n const otherSessions = useMemo(() => {\n return activeSessions.filter((session) => !session.isCurrent);\n }, [activeSessions]);\n\n const lang = useLang();\n\n function renderCurrentSession(session: ApiSession) {\n return (\n
\n

\n {lang('AuthSessions.CurrentSession')}\n

\n\n \n
\n {session.appName}\n {getDeviceEnvironment(session)}\n {session.ip} - {getLocation(session)}\n
\n
\n\n \n {lang('TerminateAllSessions')}\n \n
\n );\n }\n\n function renderOtherSessions(sessions: ApiSession[]) {\n return (\n
\n

Other Sessions

\n\n {sessions.map(renderSession)}\n
\n );\n }\n\n function renderSession(session: ApiSession) {\n return (\n {\n handleTerminateSessionClick(session.hash);\n },\n }]}\n >\n
\n {formatPastTimeShort(lang, session.dateActive * 1000)}\n {session.appName}\n {getDeviceEnvironment(session)}\n {session.ip} - {getLocation(session)}\n
\n \n );\n }\n\n return (\n
\n {currentSession && renderCurrentSession(currentSession)}\n\n {otherSessions && renderOtherSessions(otherSessions)}\n\n {otherSessions && (\n \n )};\n
\n );\n};\n\nfunction getLocation(session: ApiSession) {\n return [session.region, session.country].filter(Boolean).join(', ');\n}\n\nfunction getDeviceEnvironment(session: ApiSession) {\n return `${session.deviceModel}${session.deviceModel ? ', ' : ''} ${session.platform} ${session.systemVersion}`;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n activeSessions: global.activeSessions,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadAuthorizations', 'terminateAuthorization', 'terminateAllAuthorizations',\n ]),\n)(SettingsPrivacyActiveSessions));\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { CHAT_HEIGHT_PX } from '../../../config';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport { pick } from '../../../util/iteratees';\nimport {\n getChatTitle, getUserFullName, isChatPrivate,\n} from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport buildClassName from '../../../util/buildClassName';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Avatar from '../../common/Avatar';\nimport Loading from '../../ui/Loading';\n\ntype StateProps = {\n chatsByIds: Record;\n usersByIds: Record;\n blockedIds: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyBlockedUsers: FC = ({\n chatsByIds,\n usersByIds,\n blockedIds,\n unblockContact,\n}) => {\n const handleUnblockClick = useCallback((contactId: number) => {\n unblockContact({ contactId });\n }, [unblockContact]);\n\n const lang = useLang();\n\n function renderContact(contactId: number, i: number, viewportOffset: number) {\n const isPrivate = isChatPrivate(contactId);\n const user = isPrivate ? usersByIds[contactId] : undefined;\n const chat = !isPrivate ? chatsByIds[contactId] : undefined;\n\n const className = buildClassName(\n 'Chat chat-item-clickable blocked-list-item',\n isPrivate ? 'private' : 'group',\n );\n\n return (\n {\n handleUnblockClick(contactId);\n },\n }]}\n style={`top: ${(viewportOffset + i) * CHAT_HEIGHT_PX}px;`}\n >\n \n
\n

{renderText((isPrivate ? getUserFullName(user) : getChatTitle(lang, chat!)) || '')}

\n {user && user.phoneNumber && (\n
{formatPhoneNumberWithCode(user.phoneNumber)}
\n )}\n {user && !user.phoneNumber && user.username && (\n
@{user.username}
\n )}\n
\n \n );\n }\n\n return (\n
\n
\n
\n

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

\n
\n\n
\n {blockedIds && blockedIds.length ? (\n
\n {blockedIds!.map((contactId, i) => renderContact(contactId, i, 0))}\n
\n ) : blockedIds && !blockedIds.length ? (\n
\n List is empty\n
\n ) : (\n \n )}\n
\n
\n\n {\n }}\n className=\"not-implemented\"\n ariaLabel=\"Add a blocked user\"\n >\n \n \n
\n );\n};\n\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsByIds,\n },\n users: {\n byId: usersByIds,\n },\n blocked: {\n ids,\n },\n } = global;\n\n return {\n chatsByIds,\n usersByIds,\n blockedIds: ids,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['unblockContact']),\n)(SettingsPrivacyBlockedUsers));\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport renderText from '../../../common/helpers/renderText';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaEnabled: FC = ({ animatedEmoji, onScreenSelect }) => {\n const lang = useLang();\n\n return (\n
\n
\n \n\n

\n {renderText(lang('EnabledPasswordText'), ['br'])}\n

\n
\n\n
\n onScreenSelect(SettingsScreens.TwoFaChangePasswordCurrent)}\n >\n {lang('ChangePassword')}\n \n onScreenSelect(SettingsScreens.TwoFaTurnOff)}\n >\n {lang('TurnPasswordOff')}\n \n onScreenSelect(SettingsScreens.TwoFaRecoveryEmailCurrentPassword)}\n >\n {lang('SetRecoveryEmail')}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🔐'),\n };\n})(SettingsTwoFaEnabled));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../../../lib/teact/teact';\n\nimport useLang from '../../../../hooks/useLang';\n\nimport PasswordMonkey from '../../../common/PasswordMonkey';\nimport PasswordForm from '../../../common/PasswordForm';\n\ntype OwnProps = {\n error?: string;\n isLoading?: boolean;\n expectedPassword?: string;\n placeholder?: string;\n hint?: string;\n submitLabel?: string;\n clearError?: NoneToVoidFunction;\n onSubmit: (password: string) => void;\n};\n\nconst EQUAL_PASSWORD_ERROR = 'Passwords Should Be Equal';\n\nconst SettingsTwoFaPassword: FC = ({\n error,\n isLoading,\n expectedPassword,\n placeholder = 'Current Password',\n hint,\n submitLabel,\n clearError,\n onSubmit,\n}) => {\n const [validationError, setValidationError] = useState('');\n const [shouldShowPassword, setShouldShowPassword] = useState(false);\n\n const handleSubmit = useCallback((newPassword) => {\n if (expectedPassword && newPassword !== expectedPassword) {\n setValidationError(EQUAL_PASSWORD_ERROR);\n } else {\n onSubmit(newPassword);\n }\n }, [onSubmit, expectedPassword]);\n\n const handleClearError = useCallback(() => {\n if (clearError) {\n clearError();\n }\n setValidationError('');\n }, [clearError]);\n\n const lang = useLang();\n\n return (\n
\n
\n \n
\n\n
\n \n
\n
\n );\n};\n\nexport default memo(SettingsTwoFaPassword);\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\n\ntype OwnProps = {\n onStart: NoneToVoidFunction;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaStart: FC = ({ animatedEmoji, onStart }) => {\n const lang = useLang();\n\n return (\n
\n
\n \n\n

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

\n
\n\n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🔐'),\n };\n})(SettingsTwoFaStart));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../../util/environment';\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useFlag from '../../../../hooks/useFlag';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport Modal from '../../../ui/Modal';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport InputText from '../../../ui/InputText';\nimport renderText from '../../../common/helpers/renderText';\n\ntype OwnProps = {\n icon: 'hint' | 'email';\n type?: 'text' | 'email';\n isLoading?: boolean;\n error?: string;\n placeholder: string;\n shouldConfirm?: boolean;\n clearError?: NoneToVoidFunction;\n onSubmit: (value?: string) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst SettingsTwoFaSkippableForm: FC = ({\n animatedEmoji,\n type = 'text',\n isLoading,\n error,\n placeholder,\n shouldConfirm,\n clearError,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [value, setValue] = useState('');\n const [isConfirmShown, markIsConfirmShown, unmarkIsConfirmShown] = useFlag(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n const handleInputChange = (e: React.ChangeEvent) => {\n if (error && clearError) {\n clearError();\n }\n\n setValue(e.target.value);\n };\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n\n if (!inputRef.current) {\n return;\n }\n\n onSubmit(value);\n };\n\n const handleSkip = () => {\n onSubmit();\n };\n\n const handleSkipConfirm = () => {\n unmarkIsConfirmShown();\n onSubmit();\n };\n\n const lang = useLang();\n\n return (\n
\n
\n \n
\n\n
\n
\n \n\n {value ? (\n \n ) : (\n \n {lang('YourEmailSkip')}\n \n )}\n \n {shouldConfirm && (\n \n {renderText(lang('YourEmailSkipWarningText'), ['br', 'simple_markdown'])}\n
\n \n {lang('YourEmailSkip')}\n \n \n {lang('Cancel')}\n \n
\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal((global, { icon }) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, icon === 'email' ? '💌' : '💡'),\n };\n})(SettingsTwoFaSkippableForm));\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaCongratulations: FC = ({ animatedEmoji, onScreenSelect }) => {\n const lang = useLang();\n\n const handleClick = () => {\n onScreenSelect(SettingsScreens.Privacy);\n };\n\n return (\n
\n
\n \n\n

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

\n
\n\n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🥳'),\n };\n})(SettingsTwoFaCongratulations));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../../util/environment';\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport InputText from '../../../ui/InputText';\nimport Loading from '../../../ui/Loading';\n\ntype OwnProps = {\n isLoading?: boolean;\n error?: string;\n clearError: NoneToVoidFunction;\n onSubmit: (hint: string) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n codeLength: number;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst SettingsTwoFaEmailCode: FC = ({\n animatedEmoji,\n codeLength,\n isLoading,\n error,\n clearError,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [value, setValue] = useState('');\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n const lang = useLang();\n\n const handleInputChange = (e: React.ChangeEvent) => {\n if (error && clearError) {\n clearError();\n }\n\n const newValue = e.target.value.slice(0, codeLength);\n\n if (newValue.length === codeLength) {\n onSubmit(newValue);\n }\n\n setValue(newValue);\n e.target.value = newValue;\n };\n\n return (\n
\n
\n \n
\n\n
\n \n {isLoading && }\n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '💌'),\n codeLength: global.twoFaSettings.waitingEmailCodeLength,\n };\n})(SettingsTwoFaEmailCode));\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../../../global/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { pick } from '../../../../util/iteratees';\nimport { TwoFaDispatch, TwoFaState } from '../../../../hooks/reducers/useTwoFaReducer';\nimport useLang from '../../../../hooks/useLang';\n\nimport SettingsTwoFaEnabled from './SettingsTwoFaEnabled';\nimport SettingsTwoFaPassword from './SettingsTwoFaPassword';\nimport SettingsTwoFaStart from './SettingsTwoFaStart';\nimport SettingsTwoFaSkippableForm from './SettingsTwoFaSkippableForm';\nimport SettingsTwoFaCongratulations from './SettingsTwoFaCongratulations';\nimport SettingsTwoFaEmailCode from './SettingsTwoFaEmailCode';\n\nexport type OwnProps = {\n state: TwoFaState;\n currentScreen: SettingsScreens;\n dispatch: TwoFaDispatch;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = GlobalState['twoFaSettings'];\n\ntype DispatchProps = Pick;\n\nconst SettingsTwoFa: FC = ({\n currentScreen,\n state,\n hint,\n isLoading,\n error,\n waitingEmailCodeLength,\n dispatch,\n onScreenSelect,\n updatePassword,\n checkPassword,\n clearTwoFaError,\n updateRecoveryEmail,\n provideTwoFaEmailCode,\n clearPassword,\n}) => {\n useEffect(() => {\n if (waitingEmailCodeLength) {\n if (currentScreen === SettingsScreens.TwoFaNewPasswordEmail) {\n onScreenSelect(SettingsScreens.TwoFaNewPasswordEmailCode);\n } else if (currentScreen === SettingsScreens.TwoFaRecoveryEmail) {\n onScreenSelect(SettingsScreens.TwoFaRecoveryEmailCode);\n }\n }\n }, [currentScreen, onScreenSelect, waitingEmailCodeLength]);\n\n const handleStartWizard = useCallback(() => {\n dispatch({ type: 'reset' });\n onScreenSelect(SettingsScreens.TwoFaNewPassword);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPassword = useCallback((value: string) => {\n dispatch({ type: 'setPassword', payload: value });\n onScreenSelect(SettingsScreens.TwoFaNewPasswordConfirm);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPasswordConfirm = useCallback(() => {\n onScreenSelect(SettingsScreens.TwoFaNewPasswordHint);\n }, [onScreenSelect]);\n\n const handleNewPasswordHint = useCallback((value?: string) => {\n dispatch({ type: 'setHint', payload: value });\n onScreenSelect(SettingsScreens.TwoFaNewPasswordEmail);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPasswordEmail = useCallback((value?: string) => {\n dispatch({ type: 'setEmail', payload: value });\n updatePassword({\n ...state,\n email: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updatePassword]);\n\n const handleChangePasswordCurrent = useCallback((value: string) => {\n dispatch({ type: 'setCurrentPassword', payload: value });\n checkPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaChangePasswordNew);\n },\n });\n }, [checkPassword, dispatch, onScreenSelect]);\n\n const handleChangePasswordNew = useCallback((value: string) => {\n dispatch({ type: 'setPassword', payload: value });\n onScreenSelect(SettingsScreens.TwoFaChangePasswordConfirm);\n }, [dispatch, onScreenSelect]);\n\n const handleChangePasswordConfirm = useCallback(() => {\n onScreenSelect(SettingsScreens.TwoFaChangePasswordHint);\n }, [onScreenSelect]);\n\n const handleChangePasswordHint = useCallback((value?: string) => {\n dispatch({ type: 'setHint', payload: value });\n updatePassword({\n ...state,\n hint: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updatePassword]);\n\n const handleTurnOff = useCallback((value: string) => {\n clearPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.Privacy);\n },\n });\n }, [clearPassword, onScreenSelect]);\n\n const handleRecoveryEmailCurrentPassword = useCallback((value: string) => {\n dispatch({ type: 'setCurrentPassword', payload: value });\n checkPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaRecoveryEmail);\n },\n });\n }, [checkPassword, dispatch, onScreenSelect]);\n\n const handleRecoveryEmail = useCallback((value?: string) => {\n dispatch({ type: 'setEmail', payload: value });\n updateRecoveryEmail({\n ...state,\n email: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updateRecoveryEmail]);\n\n const handleEmailCode = useCallback((code: string) => {\n provideTwoFaEmailCode({ code });\n }, [provideTwoFaEmailCode]);\n\n const lang = useLang();\n\n switch (currentScreen) {\n case SettingsScreens.TwoFaDisabled:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPassword:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordHint:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordEmail:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n return (\n \n );\n\n case SettingsScreens.TwoFaCongratulations:\n return (\n \n );\n\n case SettingsScreens.TwoFaEnabled:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordCurrent:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordNew:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordConfirm:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordHint:\n return (\n \n );\n\n case SettingsScreens.TwoFaTurnOff:\n return (\n \n );\n\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n return (\n \n );\n\n case SettingsScreens.TwoFaRecoveryEmail:\n return (\n \n );\n\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return (\n \n );\n\n default:\n return undefined;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => ({ ...global.twoFaSettings }),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'updatePassword', 'updateRecoveryEmail', 'clearPassword', 'provideTwoFaEmailCode',\n 'checkPassword', 'clearTwoFaError',\n ]),\n)(SettingsTwoFa));\n","import React, {\n FC, useCallback, useRef, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport { isChatPrivate } from '../../modules/helpers';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from './PrivateChatInfo';\nimport GroupChatInfo from './GroupChatInfo';\nimport PickerSelectedItem from './PickerSelectedItem';\nimport useInfiniteScroll from '../../hooks/useInfiniteScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\n\nimport './Picker.scss';\n\ntype OwnProps = {\n itemIds: number[];\n selectedIds: number[];\n filterValue?: string;\n filterPlaceholder?: string;\n notFoundText?: string;\n searchInputId?: string;\n isLoading?: boolean;\n onSelectedIdsChange: (ids: number[]) => void;\n onFilterChange: (value: string) => void;\n onLoadMore?: () => void;\n};\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\n\nconst MAX_FULL_ITEMS = 10;\nconst ALWAYS_FULL_ITEMS_COUNT = 5;\n\nconst Picker: FC = ({\n itemIds,\n selectedIds,\n filterValue,\n filterPlaceholder,\n notFoundText,\n searchInputId,\n isLoading,\n onSelectedIdsChange,\n onFilterChange,\n onLoadMore,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const shouldMinimize = selectedIds.length > MAX_FULL_ITEMS;\n\n useEffect(() => {\n setTimeout(() => {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n });\n }, FOCUS_DELAY_MS);\n }, []);\n\n const handleItemClick = useCallback((id: number) => {\n const newSelectedIds = [...selectedIds];\n if (newSelectedIds.includes(id)) {\n newSelectedIds.splice(newSelectedIds.indexOf(id), 1);\n } else {\n newSelectedIds.push(id);\n }\n onSelectedIdsChange(newSelectedIds);\n onFilterChange('');\n }, [selectedIds, onSelectedIdsChange, onFilterChange]);\n\n const handleFilterChange = useCallback((e: React.ChangeEvent) => {\n const { value } = e.currentTarget;\n onFilterChange(value);\n }, [onFilterChange]);\n\n const [viewportIds, getMore] = useInfiniteScroll(onLoadMore, itemIds, Boolean(filterValue));\n\n const lang = useLang();\n\n return (\n
\n
\n {selectedIds.map((id, i) => (\n \n ))}\n \n
\n\n {viewportIds && viewportIds.length ? (\n \n {viewportIds.map((id) => (\n handleItemClick(id)}\n ripple\n >\n \n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n ))}\n \n ) : !isLoading && viewportIds && !viewportIds.length ? (\n

{notFoundText || 'Sorry, nothing found.'}

\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(Picker);\n","import React, {\n FC, memo, useCallback, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ApiPrivacySettings, SettingsScreens } from '../../../types';\n\nimport useLang from '../../../hooks/useLang';\nimport { pick } from '../../../util/iteratees';\nimport searchWords from '../../../util/searchWords';\nimport { getPrivacyKey } from './helper/privacy';\nimport {\n getChatTitle, isChatGroup, isChatPrivate, prepareChatList,\n} from '../../../modules/helpers';\n\nimport Picker from '../../common/Picker';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\n\nexport type OwnProps = {\n isAllowList?: boolean;\n screen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n chatsById: Record;\n listIds?: number[];\n orderedPinnedIds?: number[];\n archivedListIds?: number[];\n archivedPinnedIds?: number[];\n settings?: ApiPrivacySettings;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyVisibilityExceptionList: FC = ({\n currentUserId,\n isAllowList,\n screen,\n settings,\n chatsById,\n listIds,\n orderedPinnedIds,\n archivedListIds,\n archivedPinnedIds,\n setPrivacySettings,\n onScreenSelect,\n}) => {\n const lang = useLang();\n\n const selectedContactIds = useMemo(() => {\n if (!settings) {\n return [];\n }\n\n if (isAllowList) {\n return [...settings.allowUserIds, ...settings.allowChatIds];\n } else {\n return [...settings.blockUserIds, ...settings.blockChatIds];\n }\n }, [isAllowList, settings]);\n const [searchQuery, setSearchQuery] = useState('');\n const [isSubmitShown, setIsSubmitShown] = useState(false);\n const [newSelectedContactIds, setNewSelectedContactIds] = useState(selectedContactIds);\n\n const chats = useMemo(() => {\n const activeChatArrays = listIds\n ? prepareChatList(chatsById, listIds, orderedPinnedIds, 'all')\n : undefined;\n const archivedChatArrays = archivedListIds\n ? prepareChatList(chatsById, archivedListIds, archivedPinnedIds, 'archived')\n : undefined;\n\n if (!activeChatArrays && !archivedChatArrays) {\n return undefined;\n }\n\n return [\n ...(activeChatArrays\n ? [\n ...activeChatArrays.pinnedChats,\n ...activeChatArrays.otherChats,\n ]\n : []\n ),\n ...(archivedChatArrays ? archivedChatArrays.otherChats : []),\n ];\n }, [chatsById, listIds, orderedPinnedIds, archivedListIds, archivedPinnedIds]);\n\n const displayedIds = useMemo(() => {\n if (!chats) {\n return undefined;\n }\n\n return chats\n .filter((chat) => (\n ((isChatPrivate(chat.id) && chat.id !== currentUserId) || isChatGroup(chat))\n && (\n !searchQuery\n || searchWords(getChatTitle(lang, chat), searchQuery)\n || selectedContactIds.includes(chat.id)\n )\n ))\n .map(({ id }) => id);\n }, [chats, currentUserId, lang, searchQuery, selectedContactIds]);\n\n const handleSelectedContactIdsChange = useCallback((value: number[]) => {\n setNewSelectedContactIds(value);\n setIsSubmitShown(true);\n }, []);\n\n const handleSubmit = useCallback(() => {\n setPrivacySettings({\n privacyKey: getPrivacyKey(screen),\n isAllowList: Boolean(isAllowList),\n contactsIds: newSelectedContactIds,\n });\n\n onScreenSelect(SettingsScreens.Privacy);\n }, [isAllowList, newSelectedContactIds, onScreenSelect, screen, setPrivacySettings]);\n\n return (\n
\n \n\n \n \n \n
\n );\n};\n\nfunction getCurrentPrivacySettings(global: GlobalState, screen: SettingsScreens) {\n const { privacy } = global.settings;\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n return privacy.phoneNumber;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n return privacy.lastSeen;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n return privacy.profilePhoto;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n return privacy.forwards;\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return privacy.chatInvite;\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n (global, { screen }): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n orderedPinnedIds,\n },\n currentUserId,\n } = global;\n\n return {\n currentUserId,\n chatsById,\n listIds: listIds.active,\n orderedPinnedIds: orderedPinnedIds.active,\n archivedPinnedIds: orderedPinnedIds.archived,\n archivedListIds: listIds.archived,\n settings: getCurrentPrivacySettings(global, screen),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setPrivacySettings']),\n)(SettingsPrivacyVisibilityExceptionList));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { SettingsScreens } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport useFoldersReducer from '../../../hooks/reducers/useFoldersReducer';\nimport useTwoFaReducer from '../../../hooks/reducers/useTwoFaReducer';\n\nimport Transition from '../../ui/Transition';\nimport SettingsHeader from './SettingsHeader';\nimport SettingsMain from './SettingsMain';\nimport SettingsEditProfile from './SettingsEditProfile';\nimport SettingsFolders from './folders/SettingsFolders';\nimport SettingsGeneral from './SettingsGeneral';\nimport SettingsGeneralBackground from './SettingsGeneralBackground';\nimport SettingsGeneralBackgroundColor from './SettingsGeneralBackgroundColor';\nimport SettingsNotifications from './SettingsNotifications';\nimport SettingsPrivacy from './SettingsPrivacy';\nimport SettingsLanguage from './SettingsLanguage';\nimport SettingsPrivacyVisibility from './SettingsPrivacyVisibility';\nimport SettingsPrivacyActiveSessions from './SettingsPrivacyActiveSessions';\nimport SettingsPrivacyBlockedUsers from './SettingsPrivacyBlockedUsers';\nimport SettingsTwoFa from './twoFa/SettingsTwoFa';\nimport SettingsPrivacyVisibilityExceptionList from './SettingsPrivacyVisibilityExceptionList';\n\nimport './Settings.scss';\n\nconst TRANSITION_RENDER_COUNT = Object.keys(SettingsScreens).length / 2;\nconst TRANSITION_DURATION = 200;\n\nexport type OwnProps = {\n currentScreen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\nconst Settings: FC = ({\n currentScreen,\n onScreenSelect,\n onReset,\n}) => {\n const [foldersState, foldersDispatch] = useFoldersReducer();\n const [twoFaState, twoFaDispatch] = useTwoFaReducer();\n\n const handleReset = useCallback(() => {\n if (\n currentScreen === SettingsScreens.FoldersCreateFolder\n || currentScreen === SettingsScreens.FoldersEditFolder\n ) {\n setTimeout(() => {\n foldersDispatch({ type: 'reset' });\n }, TRANSITION_DURATION);\n }\n\n if (\n currentScreen === SettingsScreens.FoldersIncludedChats\n || currentScreen === SettingsScreens.FoldersExcludedChats\n ) {\n if (foldersState.mode === 'create') {\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n } else {\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }\n return;\n }\n\n onReset();\n }, [\n foldersState.mode, foldersDispatch,\n currentScreen, onReset, onScreenSelect,\n ]);\n\n const handleSaveFilter = useCallback(() => {\n foldersDispatch({ type: 'saveFilters' });\n handleReset();\n }, [foldersDispatch, handleReset]);\n\n function renderCurrentSectionContent() {\n switch (currentScreen) {\n case SettingsScreens.Main:\n return (\n \n );\n case SettingsScreens.EditProfile:\n return (\n \n );\n case SettingsScreens.General:\n return (\n \n );\n case SettingsScreens.Notifications:\n return (\n \n );\n case SettingsScreens.Privacy:\n return (\n \n );\n case SettingsScreens.Language:\n return (\n \n );\n case SettingsScreens.GeneralChatBackground:\n return (\n \n );\n case SettingsScreens.GeneralChatBackgroundColor:\n return (\n \n );\n case SettingsScreens.PrivacyActiveSessions:\n return (\n \n );\n case SettingsScreens.PrivacyBlockedUsers:\n return (\n \n );\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n return (\n \n );\n\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return (\n \n );\n\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return (\n \n );\n\n case SettingsScreens.Folders:\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n case SettingsScreens.FoldersIncludedChats:\n case SettingsScreens.FoldersExcludedChats:\n return (\n \n );\n\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaNewPassword:\n case SettingsScreens.TwoFaNewPasswordConfirm:\n case SettingsScreens.TwoFaNewPasswordHint:\n case SettingsScreens.TwoFaNewPasswordEmail:\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n case SettingsScreens.TwoFaCongratulations:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaChangePasswordNew:\n case SettingsScreens.TwoFaChangePasswordConfirm:\n case SettingsScreens.TwoFaChangePasswordHint:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n case SettingsScreens.TwoFaRecoveryEmail:\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return (\n \n );\n\n default:\n return undefined;\n }\n }\n\n function renderCurrentSection() {\n return (\n <>\n \n {renderCurrentSectionContent()}\n \n );\n }\n\n return (\n \n {renderCurrentSection}\n \n );\n};\n\nexport default memo(Settings);\n","import React, {\n FC, useEffect, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser } from '../../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { throttle } from '../../../util/schedulers';\nimport searchWords from '../../../util/searchWords';\nimport { pick } from '../../../util/iteratees';\nimport { getUserFullName, sortUserIds } from '../../../modules/helpers';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport ListItem from '../../ui/ListItem';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n filter: string;\n};\n\ntype StateProps = {\n usersById: Record;\n contactIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst ContactList: FC = ({\n filter, usersById, contactIds, loadContactList, openChat,\n}) => {\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadContactList();\n });\n });\n\n const handleClick = useCallback(\n (id: number) => {\n openChat({ id });\n },\n [openChat],\n );\n\n const listIds = useMemo(() => {\n if (!contactIds) {\n return undefined;\n }\n\n const resultIds = filter ? contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, filter);\n }) : contactIds;\n\n return sortUserIds(resultIds, usersById);\n }, [filter, usersById, contactIds]);\n\n const [viewportIds, getMore] = useInfiniteScroll(undefined, listIds, Boolean(filter));\n\n return (\n \n {viewportIds && viewportIds.length ? (\n viewportIds.map((id) => (\n handleClick(id)}\n ripple={!IS_MOBILE_SCREEN}\n >\n \n \n ))\n ) : viewportIds && !viewportIds.length ? (\n

\n {filter.length ? 'No contacts matched your search.' : 'Contact list is empty.'}\n

\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { userIds: contactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n\n return {\n usersById,\n contactIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'openChat']),\n)(ContactList));\n","import React, {\n FC, useCallback, useEffect, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick, unique } from '../../../util/iteratees';\nimport { throttle } from '../../../util/schedulers';\nimport searchWords from '../../../util/searchWords';\nimport { getUserFullName, sortChatIds } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\n\nimport Picker from '../../common/Picker';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Button from '../../ui/Button';\n\nexport type OwnProps = {\n isChannel?: boolean;\n selectedMemberIds: number[];\n onSelectedMemberIdsChange: (ids: number[]) => void;\n onNextStep: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n usersById: Record;\n chatsById: Record;\n localContactIds?: number[];\n searchQuery?: string;\n isSearching?: boolean;\n localUserIds?: number[];\n globalUserIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst NewChatStep1: FC = ({\n isChannel,\n selectedMemberIds,\n onSelectedMemberIdsChange,\n onNextStep,\n onReset,\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching,\n localUserIds,\n globalUserIds,\n loadContactList,\n setGlobalSearchQuery,\n}) => {\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadContactList();\n });\n });\n\n const handleFilterChange = useCallback((query: string) => {\n setGlobalSearchQuery({ query });\n }, [setGlobalSearchQuery]);\n\n const displayedIds = useMemo(() => {\n const contactIds = localContactIds\n ? sortChatIds(localContactIds.filter((id) => id !== currentUserId), chatsById)\n : [];\n\n if (!searchQuery) {\n return contactIds;\n }\n\n const foundContactIds = contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, searchQuery);\n });\n\n return sortChatIds(\n unique([\n ...foundContactIds,\n ...(localUserIds || []),\n ...(globalUserIds || []),\n ]),\n chatsById,\n false,\n selectedMemberIds,\n );\n }, [\n localContactIds, searchQuery, localUserIds, globalUserIds, usersById, chatsById, selectedMemberIds, currentUserId,\n ]);\n\n const handleNextStep = useCallback(() => {\n if (selectedMemberIds.length || isChannel) {\n setGlobalSearchQuery({ query: '' });\n onNextStep();\n }\n }, [selectedMemberIds.length, isChannel, setGlobalSearchQuery, onNextStep]);\n\n const lang = useLang();\n\n return (\n
\n
\n \n \n \n

{lang('GroupAddMembers')}

\n
\n
\n \n\n \n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { userIds: localContactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n const { currentUserId } = global;\n\n const {\n query: searchQuery,\n fetchingStatus,\n globalResults,\n localResults,\n } = global.globalSearch;\n const { userIds: globalUserIds } = globalResults || {};\n const { userIds: localUserIds } = localResults || {};\n\n return {\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching: fetchingStatus && fetchingStatus.chats,\n globalUserIds,\n localUserIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'setGlobalSearchQuery']),\n)(NewChatStep1));\n","import React, {\n FC, useState, useCallback, useEffect, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ChatCreationProgress } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport InputText from '../../ui/InputText';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport Button from '../../ui/Button';\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\nexport type OwnProps = {\n isChannel?: boolean;\n memberIds: number[];\n onReset: (forceReturnToChatList?: boolean) => void;\n};\n\ntype StateProps = {\n creationProgress?: ChatCreationProgress;\n creationError?: string;\n};\n\ntype DispatchProps = Pick;\n\n// TODO @implement\nconst MAX_USERS_FOR_LEGACY_CHAT = 199; // Accounting for current user\n\nconst NewChatStep2: FC = ({\n isChannel,\n memberIds,\n onReset,\n creationProgress,\n creationError,\n createGroupChat,\n createChannel,\n}) => {\n const lang = useLang();\n\n const [title, setTitle] = useState('');\n const [about, setAbout] = useState('');\n const [photo, setPhoto] = useState();\n const [error, setError] = useState();\n\n const chatTitleEmptyError = 'Chat title can\\'t be empty';\n const channelTitleEmptyError = 'Channel title can\\'t be empty';\n const chatTooManyUsersError = 'Sorry, creating supergroups is not yet supported';\n\n const isLoading = creationProgress === ChatCreationProgress.InProgress;\n\n const handleTitleChange = useCallback((e: React.ChangeEvent) => {\n const { value } = e.currentTarget;\n const newValue = value.replace(/^\\s+/, '');\n\n setTitle(newValue);\n\n if (newValue !== value) {\n e.currentTarget.value = newValue;\n }\n }, []);\n\n const handleDescriptionChange = useCallback((e: React.ChangeEvent) => {\n setAbout(e.currentTarget.value);\n }, []);\n\n const handleCreateGroup = useCallback(() => {\n if (!title.length) {\n setError(chatTitleEmptyError);\n return;\n }\n\n if (memberIds.length > MAX_USERS_FOR_LEGACY_CHAT) {\n setError(chatTooManyUsersError);\n return;\n }\n\n createGroupChat({\n title,\n photo,\n memberIds,\n });\n }, [title, memberIds, createGroupChat, photo, chatTitleEmptyError, chatTooManyUsersError]);\n\n const handleCreateChannel = useCallback(() => {\n if (!title.length) {\n setError(channelTitleEmptyError);\n return;\n }\n\n createChannel({\n title,\n about,\n photo,\n memberIds,\n });\n }, [title, createChannel, about, photo, memberIds, channelTitleEmptyError]);\n\n useEffect(() => {\n if (creationProgress === ChatCreationProgress.Complete) {\n onReset(true);\n }\n }, [creationProgress, onReset]);\n\n const renderedError = creationError || (\n error !== chatTitleEmptyError && error !== channelTitleEmptyError\n ? error\n : undefined\n );\n\n return (\n
\n
\n onReset()}\n ariaLabel=\"Return to member selection\"\n >\n \n \n

{lang(isChannel ? 'NewChannel' : 'NewGroup')}

\n
\n
\n \n \n {isChannel && (\n <>\n \n

{lang('DescriptionInfo')}

\n \n )}\n\n {renderedError && (\n

{renderedError}

\n )}\n\n {memberIds.length > 0 && (\n <>\n

{lang('GroupInfo.ParticipantCount', memberIds.length, 'i')}

\n\n
\n {memberIds.map((id) => (\n \n \n \n ))}\n
\n \n )}\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n progress: creationProgress,\n error: creationError,\n } = global.chatCreation || {};\n\n return {\n creationProgress,\n creationError,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'createGroupChat', 'createChannel',\n ]),\n)(NewChatStep2));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport NewChatStep1 from './NewChatStep1';\nimport NewChatStep2 from './NewChatStep2';\n\nimport './NewChat.scss';\n\nexport type OwnProps = {\n isChannel?: boolean;\n content: LeftColumnContent;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\nconst RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\n\nconst NewChat: FC = ({\n isChannel = false,\n content,\n onContentChange,\n onReset,\n}) => {\n const [newChatMemberIds, setNewChatMemberIds] = useState([]);\n\n const handleNextStep = useCallback(() => {\n onContentChange(isChannel ? LeftColumnContent.NewChannelStep2 : LeftColumnContent.NewGroupStep2);\n }, [isChannel, onContentChange]);\n\n return (\n \n {() => {\n switch (content) {\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewGroupStep1:\n return (\n \n );\n case LeftColumnContent.NewChannelStep2:\n case LeftColumnContent.NewGroupStep2:\n return (\n \n );\n default:\n return undefined;\n }\n }}\n \n );\n};\n\nexport default memo(NewChat);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport ChatList from './main/ChatList';\n\nimport './ArchivedChats.scss';\n\nexport type OwnProps = {\n isActive: boolean;\n onReset: () => void;\n};\n\nconst ArchivedChats: FC = ({ isActive, onReset }) => {\n const lang = useLang();\n\n return (\n
\n
\n \n \n \n

{lang('ArchivedChats')}

\n
\n \n
\n );\n};\n\nexport default memo(ArchivedChats);\n","const IGNORED_KEYS: Record = {\n Down: true,\n ArrowDown: true,\n Up: true,\n ArrowUp: true,\n Left: true,\n ArrowLeft: true,\n Right: true,\n ArrowRight: true,\n ' ': true,\n PageUp: true,\n PageDown: true,\n End: true,\n Home: true,\n Tab: true,\n};\n\nconst preventDefault = (e: Event) => {\n e.preventDefault();\n};\n\nfunction preventDefaultForScrollKeys(e: KeyboardEvent) {\n if (IGNORED_KEYS[e.key]) {\n preventDefault(e);\n }\n}\n\nexport function disableScrolling() {\n // Disable scrolling in Chrome\n document.addEventListener('wheel', preventDefault, { passive: false });\n window.ontouchmove = preventDefault; // mobile\n document.onkeydown = preventDefaultForScrollKeys;\n}\n\nexport function enableScrolling() {\n document.removeEventListener('wheel', preventDefault); // Enable scrolling in Chrome\n // eslint-disable-next-line no-null/no-null\n window.ontouchmove = null;\n // eslint-disable-next-line no-null/no-null\n document.onkeydown = null;\n}\n","import { ApiMediaFormat, ApiMessage } from '../../../../api/types';\n\nimport * as mediaLoader from '../../../../util/mediaLoader';\nimport { getMessageMediaHash, getMessagePhoto, getMessageText } from '../../../../modules/helpers';\nimport { CLIPBOARD_ITEM_SUPPORTED, copyImageToClipboard, copyTextToClipboard } from '../../../../util/clipboard';\n\ntype ICopyOptions = {\n label: string;\n handler: () => void;\n}[];\n\nexport function getMessageCopyOptions(\n message: ApiMessage, afterEffect?: () => void, onCopyLink?: () => void,\n): ICopyOptions {\n const options: ICopyOptions = [];\n const text = getMessageText(message);\n const photo = getMessagePhoto(message);\n const mediaHash = getMessageMediaHash(message, 'inline')!;\n const canImageBeCopied = photo && mediaHash && CLIPBOARD_ITEM_SUPPORTED;\n const selection = window.getSelection();\n\n if (canImageBeCopied) {\n options.push({\n label: 'lng_context_copy_image',\n handler: () => {\n mediaLoader.fetch(mediaHash, ApiMediaFormat.BlobUrl).then(copyImageToClipboard);\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n if (text) {\n // Detect if the user has selection in the current message\n const hasSelection = Boolean((\n selection\n && selection.anchorNode\n && selection.anchorNode.parentNode\n && (selection.anchorNode.parentNode as HTMLElement).closest('.Message .content-inner')\n && selection.toString().replace(/(?:\\r\\n|\\r|\\n)/g, '') !== ''\n ));\n\n options.push({\n label: getCopyLabel(hasSelection, canImageBeCopied),\n handler: () => {\n const clipboardText = hasSelection && selection ? selection.toString() : text;\n copyTextToClipboard(clipboardText);\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n if (onCopyLink) {\n options.push({\n label: 'lng_context_copy_message_link',\n handler: () => {\n onCopyLink();\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n return options;\n}\n\nfunction getCopyLabel(hasSelection: boolean, canImageBeCopied: boolean): string {\n if (hasSelection) {\n return 'lng_context_copy_selected';\n }\n\n if (canImageBeCopied) {\n return 'lng_context_copy_text';\n }\n\n return 'Copy';\n}\n","import React, { FC, useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IAnchorPosition } from '../../../types';\n\nimport { getMessageCopyOptions } from './helpers/copyOptions';\nimport useContextMenuPosition from '../../../hooks/useContextMenuPosition';\nimport { dispatchHeavyAnimationEvent } from '../../../hooks/useHeavyAnimationCheck';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './MessageContextMenu.scss';\n\ntype OwnProps = {\n isOpen: boolean;\n anchor: IAnchorPosition;\n message: ApiMessage;\n canSendNow?: boolean;\n canReschedule?: boolean;\n canReply?: boolean;\n canPin?: boolean;\n canUnpin?: boolean;\n canDelete?: boolean;\n canEdit?: boolean;\n canForward?: boolean;\n canFaveSticker?: boolean;\n canUnfaveSticker?: boolean;\n canCopy?: boolean;\n canCopyLink?: boolean;\n canSelect?: boolean;\n onReply: () => void;\n onEdit: () => void;\n onPin: () => void;\n onUnpin: () => void;\n onForward: () => void;\n onDelete: () => void;\n onFaveSticker: () => void;\n onUnfaveSticker: () => void;\n onSelect: () => void;\n onSend: () => void;\n onReschedule: () => void;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onCopyLink?: () => void;\n};\n\nconst ANIMATION_DURATION = 200;\nconst SCROLLBAR_WIDTH = 10;\n\nconst MessageContextMenu: FC = ({\n isOpen,\n message,\n anchor,\n canSendNow,\n canReschedule,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n onReply,\n onEdit,\n onPin,\n onUnpin,\n onForward,\n onDelete,\n onFaveSticker,\n onUnfaveSticker,\n onSelect,\n onSend,\n onReschedule,\n onClose,\n onCloseAnimationEnd,\n onCopyLink,\n}) => {\n useEffect(() => {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }, [isOpen]);\n\n const copyOptions = getMessageCopyOptions(message, onClose, canCopyLink ? onCopyLink : undefined);\n\n const getTriggerElement = useCallback(() => {\n return document.querySelector(`.active > .MessageList div[data-message-id=\"${message.id}\"]`);\n }, [message.id]);\n\n const getRootElement = useCallback(\n () => document.querySelector('.active > .MessageList'),\n [],\n );\n\n const getMenuElement = useCallback(\n () => document.querySelector('.MessageContextMenu .bubble'),\n [],\n );\n\n const { positionX, positionY, style } = useContextMenuPosition(\n anchor,\n getTriggerElement,\n getRootElement,\n getMenuElement,\n SCROLLBAR_WIDTH,\n (document.querySelector('.MiddleHeader') as HTMLElement).offsetHeight,\n );\n\n const lang = useLang();\n\n return (\n \n {canSendNow && {lang('MessageScheduleSend')}}\n {canReschedule && (\n {lang('MessageScheduleEditTime')}\n )}\n {canReply && {lang('Reply')}}\n {canEdit && {lang('Edit')}}\n {canFaveSticker && (\n {lang('AddToFavorites')}\n )}\n {canUnfaveSticker && (\n {lang('Stickers.RemoveFromFavorites')}\n )}\n {canCopy && copyOptions.map((options) => (\n {lang(options.label)}\n ))}\n {canPin && {lang('DialogPin')}}\n {canUnpin && {lang('DialogUnpin')}}\n {canForward && {lang('Forward')}}\n {canSelect && {lang('Common.Select')}}\n {canDelete && {lang('Delete')}}\n \n );\n};\n\nexport default MessageContextMenu;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum, IAnchorPosition } from '../../../types';\nimport { selectAllowedMessageActions, selectCurrentMessageList } from '../../../modules/selectors';\nimport { disableScrolling, enableScrolling } from '../../../util/scrollLock';\nimport { pick } from '../../../util/iteratees';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal';\nimport PinMessageModal from '../../common/PinMessageModal';\nimport MessageContextMenu from './MessageContextMenu';\nimport CalendarModal from '../../common/CalendarModal';\nimport { getDayStartAt } from '../../../util/dateFormat';\n\nexport type OwnProps = {\n isOpen: boolean;\n message: ApiMessage;\n album?: IAlbum;\n anchor: IAnchorPosition;\n messageListType: MessageListType;\n onClose: () => void;\n onCloseAnimationEnd: () => void;\n};\n\ntype StateProps = {\n noOptions?: boolean;\n canSendNow?: boolean;\n canReschedule?: boolean;\n canReply?: boolean;\n canPin?: boolean;\n canUnpin?: boolean;\n canDelete?: boolean;\n canEdit?: boolean;\n canForward?: boolean;\n canFaveSticker?: boolean;\n canUnfaveSticker?: boolean;\n canCopy?: boolean;\n canCopyLink?: boolean;\n canSelect?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ContextMenuContainer: FC = ({\n isOpen,\n messageListType,\n message,\n album,\n anchor,\n onClose,\n onCloseAnimationEnd,\n noOptions,\n canSendNow,\n canReschedule,\n canReply,\n canPin,\n canUnpin,\n canDelete,\n canEdit,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n setReplyingToId,\n setEditingId,\n pinMessage,\n openForwardMenu,\n faveSticker,\n unfaveSticker,\n toggleMessageSelection,\n sendScheduledMessages,\n rescheduleMessage,\n loadMessageLink,\n}) => {\n const { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd, undefined, false);\n const [isMenuOpen, setIsMenuOpen] = useState(true);\n const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);\n const [isPinModalOpen, setIsPinModalOpen] = useState(false);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n\n const handleDelete = useCallback(() => {\n setIsMenuOpen(false);\n setIsDeleteModalOpen(true);\n }, []);\n\n const closeMenu = useCallback(() => {\n setIsMenuOpen(false);\n onClose();\n }, [onClose]);\n\n const closeDeleteModal = useCallback(() => {\n setIsDeleteModalOpen(false);\n onClose();\n }, [onClose]);\n\n const closePinModal = useCallback(() => {\n setIsPinModalOpen(false);\n onClose();\n }, [onClose]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n onClose();\n }, [closeCalendar, onClose]);\n\n const handleReply = useCallback(() => {\n setReplyingToId({ messageId: message.id });\n closeMenu();\n }, [setReplyingToId, message.id, closeMenu]);\n\n const handleEdit = useCallback(() => {\n setEditingId({ messageId: message.id });\n closeMenu();\n }, [setEditingId, message.id, closeMenu]);\n\n const handlePin = useCallback(() => {\n setIsMenuOpen(false);\n setIsPinModalOpen(true);\n }, []);\n\n const handleUnpin = useCallback(() => {\n pinMessage({ messageId: message.id, isUnpin: true });\n closeMenu();\n }, [pinMessage, message.id, closeMenu]);\n\n const handleForward = useCallback(() => {\n closeMenu();\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: message.chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: message.chatId, messageIds: [message.id] });\n }\n }, [openForwardMenu, message, closeMenu, album]);\n\n const handleFaveSticker = useCallback(() => {\n closeMenu();\n faveSticker({ sticker: message.content.sticker });\n }, [closeMenu, message.content.sticker, faveSticker]);\n\n const handleUnfaveSticker = useCallback(() => {\n closeMenu();\n unfaveSticker({ sticker: message.content.sticker });\n }, [closeMenu, message.content.sticker, unfaveSticker]);\n\n const handleSelectMessage = useCallback(() => {\n const params = album && album.messages\n ? {\n messageId: message.id,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: false,\n }\n : { messageId: message.id, withShift: false };\n\n toggleMessageSelection(params);\n closeMenu();\n }, [closeMenu, message.id, toggleMessageSelection, album]);\n\n const handleScheduledMessageSend = useCallback(() => {\n sendScheduledMessages({ chatId: message.chatId, id: message.id });\n closeMenu();\n }, [closeMenu, message.chatId, message.id, sendScheduledMessages]);\n\n const handleOpenCalendar = useCallback(() => {\n setIsMenuOpen(false);\n openCalendar();\n }, [openCalendar]);\n\n const handleRescheduleMessage = useCallback((date: Date) => {\n rescheduleMessage({\n chatId: message.chatId,\n messageId: message.id,\n scheduledAt: Math.round(date.getTime() / 1000),\n });\n }, [message.chatId, message.id, rescheduleMessage]);\n\n const handleCopyLink = useCallback(() => {\n loadMessageLink({\n messageId: message.id,\n chatId: message.chatId,\n });\n closeMenu();\n }, [closeMenu, loadMessageLink, message.chatId, message.id]);\n\n useEffect(() => {\n disableScrolling();\n\n return enableScrolling;\n }, []);\n\n if (noOptions) {\n closeMenu();\n\n return undefined;\n }\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n return (\n
\n \n \n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message, messageListType }): StateProps => {\n const { threadId } = selectCurrentMessageList(global) || {};\n const {\n noOptions,\n canReply,\n canPin,\n canUnpin,\n canDelete,\n canEdit,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n } = (threadId && selectAllowedMessageActions(global, message, threadId)) || {};\n const isPinned = messageListType === 'pinned';\n const isScheduled = messageListType === 'scheduled';\n\n return {\n noOptions,\n canSendNow: isScheduled,\n canReschedule: isScheduled,\n canReply: !isPinned && !isScheduled && canReply,\n canPin: !isScheduled && canPin,\n canUnpin: !isScheduled && canUnpin,\n canDelete,\n canEdit: !isPinned && canEdit,\n canForward: !isScheduled && canForward,\n canFaveSticker: !isScheduled && canFaveSticker,\n canUnfaveSticker: !isScheduled && canUnfaveSticker,\n canCopy,\n canCopyLink: !isScheduled && canCopyLink,\n canSelect,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'pinMessage',\n 'openForwardMenu',\n 'faveSticker',\n 'unfaveSticker',\n 'toggleMessageSelection',\n 'sendScheduledMessages',\n 'rescheduleMessage',\n 'loadMessageLink',\n ]),\n)(ContextMenuContainer));\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiSticker, ApiStickerSet } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { STICKER_SIZE_MODAL } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport { selectStickerSet } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\nimport Loading from '../ui/Loading';\nimport StickerButton from './StickerButton';\n\nimport './StickerSetModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n fromSticker: ApiSticker;\n onClose: () => void;\n};\n\ntype StateProps = {\n stickerSet?: ApiStickerSet;\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst StickerSetModal: FC = ({\n isOpen,\n fromSticker,\n stickerSet,\n onClose,\n loadStickers,\n toggleStickerSet,\n sendMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const lang = useLang();\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE, isDisabled: !isOpen });\n\n useEffect(() => {\n if (isOpen) {\n const { stickerSetId, stickerSetAccessHash } = fromSticker;\n loadStickers({ stickerSetId, stickerSetAccessHash });\n }\n }, [isOpen, fromSticker, loadStickers]);\n\n const handleSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n sendMessage({ sticker });\n onClose();\n }, [onClose, sendMessage]);\n\n const handleButtonClick = useCallback(() => {\n toggleStickerSet({ stickerSetId: fromSticker.stickerSetId });\n onClose();\n }, [fromSticker.stickerSetId, onClose, toggleStickerSet]);\n\n return (\n \n {stickerSet && stickerSet.stickers ? (\n <>\n
\n {stickerSet.stickers.map((sticker) => (\n \n ))}\n
\n
\n \n {lang(\n stickerSet.installedDate ? 'StickerPack.RemoveStickerCount' : 'StickerPack.AddStickerCount',\n stickerSet.count,\n 'i',\n )}\n \n
\n \n ) : (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { fromSticker }: OwnProps) => {\n return { stickerSet: selectStickerSet(global, fromSticker.stickerSetId) };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadStickers',\n 'toggleStickerSet',\n 'sendMessage',\n ]),\n)(StickerSetModal));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { disableScrolling, enableScrolling } from '../../util/scrollLock';\nimport { selectChat } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { isChatPrivate, getCanDeleteChat } from '../../modules/helpers';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useLang from '../../hooks/useLang';\n\nimport Portal from '../ui/Portal';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\nimport DeleteChatModal from '../common/DeleteChatModal';\n\nimport './HeaderMenuContainer.scss';\n\ntype DispatchProps = Pick;\n\nexport type OwnProps = {\n chatId: number;\n threadId: number;\n isOpen: boolean;\n anchor: IAnchorPosition;\n isChannel?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n onSubscribeChannel: () => void;\n onSearchClick: () => void;\n onClose: () => void;\n onCloseAnimationEnd: () => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isPrivate?: boolean;\n isMuted?: boolean;\n canDeleteChat?: boolean;\n};\n\nconst HeaderMenuContainer: FC = ({\n chatId,\n isOpen,\n anchor,\n isChannel,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n chat,\n isPrivate,\n isMuted,\n canDeleteChat,\n onSubscribeChannel,\n onSearchClick,\n onClose,\n onCloseAnimationEnd,\n updateChatMutedState,\n enterMessageSelectMode,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(true);\n const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);\n const { x, y } = anchor;\n\n useShowTransition(isOpen, onCloseAnimationEnd, undefined, false);\n\n const handleDelete = useCallback(() => {\n setIsMenuOpen(false);\n setIsDeleteModalOpen(true);\n }, []);\n\n const closeMenu = useCallback(() => {\n setIsMenuOpen(false);\n onClose();\n }, [onClose]);\n\n const closeDeleteModal = useCallback(() => {\n setIsDeleteModalOpen(false);\n onClose();\n }, [onClose]);\n\n const handleToggleMuteClick = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !isMuted });\n closeMenu();\n }, [chatId, closeMenu, isMuted, updateChatMutedState]);\n\n const handleSubscribe = useCallback(() => {\n onSubscribeChannel();\n closeMenu();\n }, [closeMenu, onSubscribeChannel]);\n\n const handleSearch = useCallback(() => {\n onSearchClick();\n closeMenu();\n }, [closeMenu, onSearchClick]);\n\n const handleSelectMessages = useCallback(() => {\n enterMessageSelectMode();\n closeMenu();\n }, [closeMenu, enterMessageSelectMode]);\n\n useEffect(() => {\n disableScrolling();\n\n return enableScrolling;\n }, []);\n\n const lang = useLang();\n\n return (\n \n
\n \n {IS_MOBILE_SCREEN && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {IS_MOBILE_SCREEN && canSearch && (\n \n {lang('Search')}\n \n )}\n {canMute && (\n \n {lang(isMuted ? 'ChatsUnmute' : 'ChatsMute')}\n \n )}\n {canSelect && (\n \n {lang('ReportSelectMessages')}\n \n )}\n {canLeave && (\n \n {lang(isPrivate\n ? 'Delete'\n : (canDeleteChat ? 'GroupInfo.DeleteAndExit' : (isChannel ? 'LeaveChannel' : 'Group.LeaveGroup')))}\n \n )}\n \n {chat && (\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n return {\n chat,\n isMuted: chat.isMuted,\n isPrivate: isChatPrivate(chat.id),\n canDeleteChat: getCanDeleteChat(chat),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'updateChatMutedState',\n 'enterMessageSelectMode',\n ]),\n)(HeaderMenuContainer));\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState, useLayoutEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { debounce } from '../../util/schedulers';\nimport { selectCurrentTextSearch, selectCurrentChat } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport SearchInput from '../ui/SearchInput';\nimport CalendarModal from '../common/CalendarModal';\n\nimport './MobileSearch.scss';\n\nexport type OwnProps = {\n isActive: boolean;\n};\n\ntype StateProps = {\n isActive?: boolean;\n chat?: ApiChat;\n query?: string;\n totalCount?: number;\n foundIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nconst MobileSearchFooter: FC = ({\n isActive,\n chat,\n query,\n totalCount,\n foundIds,\n setLocalTextSearchQuery,\n searchTextMessagesLocal,\n focusMessage,\n closeLocalTextSearch,\n searchMessagesByDate,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const [focusedIndex, setFocusedIndex] = useState(0);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n\n // Fix for iOS keyboard\n useEffect(() => {\n const { visualViewport } = window as any;\n if (!visualViewport) {\n return undefined;\n }\n\n const mainEl = document.getElementById('Main') as HTMLDivElement;\n const handleResize = () => {\n const { activeElement } = document;\n if (activeElement && (activeElement === inputRef.current)) {\n const { pageTop, height } = visualViewport;\n mainEl.style.transform = `translateY(${pageTop}px)`;\n mainEl.style.height = `${height}px`;\n document.documentElement.scrollTop = pageTop;\n } else {\n mainEl.style.transform = '';\n mainEl.style.height = '';\n }\n };\n\n visualViewport.addEventListener('resize', handleResize);\n\n return () => {\n visualViewport.removeEventListener('resize', handleResize);\n };\n }, []);\n\n // Focus message\n useEffect(() => {\n if (chat && foundIds && foundIds.length) {\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1] });\n setFocusedIndex(0);\n } else {\n setFocusedIndex(-1);\n }\n }, [chat, focusMessage, foundIds]);\n\n // Disable native up/down buttons on iOS\n useEffect(() => {\n Array.from(document.querySelectorAll('input')).forEach((input) => {\n input.disabled = Boolean(isActive && input !== inputRef.current);\n });\n\n Array.from(document.querySelectorAll('div[contenteditable]')).forEach((div) => {\n div.contentEditable = isActive ? 'false' : 'true';\n });\n }, [isActive]);\n\n // Blur on exit\n useEffect(() => {\n if (!isActive) {\n inputRef.current!.blur();\n }\n }, [isActive]);\n\n useLayoutEffect(() => {\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.blur();\n }, [isCalendarOpen]);\n\n const handleMessageSearchQueryChange = useCallback((newQuery: string) => {\n setLocalTextSearchQuery({ query: newQuery });\n\n if (newQuery.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleJumpToDate = useCallback((date: Date) => {\n searchMessagesByDate({ timestamp: date.valueOf() / 1000 });\n closeCalendar();\n }, [closeCalendar, searchMessagesByDate]);\n\n const handleUp = useCallback(() => {\n if (chat && foundIds) {\n const newFocusIndex = focusedIndex + 1;\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1 - newFocusIndex] });\n setFocusedIndex(newFocusIndex);\n }\n }, [chat, focusedIndex, focusMessage, foundIds]);\n\n const handleDown = useCallback(() => {\n if (chat && foundIds) {\n const newFocusIndex = focusedIndex - 1;\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1 - newFocusIndex] });\n setFocusedIndex(newFocusIndex);\n }\n }, [chat, focusedIndex, focusMessage, foundIds]);\n\n const lang = useLang();\n\n return (\n
\n
\n \n \n \n \n
\n
\n
\n {query ? (\n foundIds && foundIds.length ? (\n `${focusedIndex + 1} of ${totalCount}`\n ) : foundIds && !foundIds.length ? (\n 'No results'\n ) : (\n ''\n )\n ) : (\n \n \n \n )}\n
\n \n \n \n \n \n \n
\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return {};\n }\n\n const { query, results } = selectCurrentTextSearch(global) || {};\n const { totalCount, foundIds } = results || {};\n\n return {\n chat,\n query,\n totalCount,\n foundIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'searchTextMessagesLocal',\n 'focusMessage',\n 'closeLocalTextSearch',\n 'searchMessagesByDate',\n ]),\n)(MobileSearchFooter));\n","export default function findInViewport(\n container: HTMLElement,\n selectorOrElements: string | NodeListOf,\n margin = 0,\n isDense = false,\n shouldContainBottom = false,\n isHorizontal = false,\n) {\n const viewportY1 = container[isHorizontal ? 'scrollLeft' : 'scrollTop'];\n const viewportY2 = viewportY1 + container[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const allElements = typeof selectorOrElements === 'string'\n ? container.querySelectorAll(selectorOrElements)\n : selectorOrElements;\n const { length } = allElements;\n const visibleIndexes: number[] = [];\n let isFound = false;\n\n for (let i = 0; i < length; i++) {\n const element = allElements[i];\n const y1 = element[isHorizontal ? 'offsetLeft' : 'offsetTop'];\n const y2 = y1 + element[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const isVisible = shouldContainBottom\n ? y2 >= viewportY1 - margin && y2 <= viewportY2 + margin\n : y1 <= viewportY2 + margin && y2 >= viewportY1 - margin;\n\n if (isVisible) {\n visibleIndexes.push(i);\n isFound = true;\n } else if (isFound && !isDense) {\n break;\n }\n }\n\n return { allElements, visibleIndexes };\n}\n","function isFullyVisible(container: HTMLElement, element: HTMLElement, isHorizontal = false) {\n const viewportY1 = container[isHorizontal ? 'scrollLeft' : 'scrollTop'];\n const viewportY2 = viewportY1 + container[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const y1 = element[isHorizontal ? 'offsetLeft' : 'offsetTop'];\n const y2 = y1 + element[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n return y1 > viewportY1 && y2 < viewportY2;\n}\n\nexport default isFullyVisible;\n","import React, {\n FC, useCallback, useEffect, useState, useRef, memo,\n} from '../../../lib/teact/teact';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\n\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport findInViewport from '../../../util/findInViewport';\nimport isFullyVisible from '../../../util/isFullyVisible';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport cycleRestrict from '../../../util/cycleRestrict';\n\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\nimport './MentionTooltip.scss';\n\nconst VIEWPORT_MARGIN = 8;\nconst SCROLL_MARGIN = 10;\n\nfunction setItemVisible(index: number, containerRef: Record) {\n const container = containerRef.current!;\n if (!container || index < 0) {\n return;\n }\n const { visibleIndexes, allElements } = findInViewport(\n container,\n '.chat-item-clickable',\n VIEWPORT_MARGIN,\n true,\n true,\n );\n if (!allElements.length || !allElements[index]) {\n return;\n }\n const first = visibleIndexes[0];\n if (!visibleIndexes.includes(index)\n || (index === first && !isFullyVisible(container, allElements[first]))) {\n const position = index > visibleIndexes[visibleIndexes.length - 1] ? 'start' : 'end';\n fastSmoothScroll(container, allElements[index], position, SCROLL_MARGIN);\n }\n}\n\nexport type OwnProps = {\n isOpen: boolean;\n filter: string;\n onClose: () => void;\n onInsertUserName: (user: ApiUser, forceFocus?: boolean) => void;\n filteredChatMembers?: ApiChatMember[];\n usersById?: Record;\n};\n\nconst MentionTooltip: FC = ({\n isOpen,\n filter,\n onClose,\n onInsertUserName,\n usersById,\n filteredChatMembers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n\n const getSelectedIndex = useCallback((newIndex: number) => {\n if (!filteredChatMembers) {\n return -1;\n }\n const membersCount = filteredChatMembers!.length;\n return cycleRestrict(membersCount, newIndex);\n }, [filteredChatMembers]);\n\n const [selectedMentionIndex, setSelectedMentionIndex] = useState(-1);\n\n const handleArrowKey = useCallback((value: number, e: KeyboardEvent) => {\n e.preventDefault();\n setSelectedMentionIndex((index) => (getSelectedIndex(index + value)));\n }, [setSelectedMentionIndex, getSelectedIndex]);\n\n const handleUserSelect = useCallback((userId: number, forceFocus = false) => {\n const user = usersById && usersById[userId];\n if (!user) {\n return;\n }\n\n onInsertUserName(user, forceFocus);\n }, [usersById, onInsertUserName]);\n\n const handleSelectMention = useCallback((e: KeyboardEvent) => {\n if (filteredChatMembers && filteredChatMembers.length && selectedMentionIndex > -1) {\n const member = filteredChatMembers[selectedMentionIndex];\n if (member) {\n e.preventDefault();\n handleUserSelect(member.userId, true);\n }\n }\n }, [filteredChatMembers, selectedMentionIndex, handleUserSelect]);\n\n useEffect(() => (isOpen ? captureKeyboardListeners({\n onEsc: onClose,\n onUp: (e: KeyboardEvent) => handleArrowKey(-1, e),\n onDown: (e: KeyboardEvent) => handleArrowKey(1, e),\n onEnter: handleSelectMention,\n onTab: handleSelectMention,\n }) : undefined), [isOpen, onClose, handleArrowKey, handleSelectMention]);\n\n useEffect(() => {\n if (filteredChatMembers && !filteredChatMembers.length) {\n onClose();\n }\n }, [filteredChatMembers, onClose]);\n\n useEffect(() => {\n setSelectedMentionIndex(0);\n }, [filter]);\n\n useEffect(() => {\n setItemVisible(selectedMentionIndex, containerRef);\n }, [selectedMentionIndex]);\n\n const prevChatMembers = usePrevious(\n filteredChatMembers && filteredChatMembers.length\n ? filteredChatMembers\n : undefined,\n shouldRender,\n );\n const renderedChatMembers = filteredChatMembers && !filteredChatMembers.length\n ? prevChatMembers\n : filteredChatMembers;\n\n if (!shouldRender || (renderedChatMembers && !renderedChatMembers.length)) {\n return undefined;\n }\n\n const className = buildClassName(\n 'MentionTooltip composer-tooltip custom-scroll',\n transitionClassNames,\n );\n\n return (\n
\n {renderedChatMembers && renderedChatMembers.map(({ userId }, index) => (\n handleUserSelect(userId)}\n focus={selectedMentionIndex === index}\n >\n \n \n ))}\n
\n );\n};\n\nexport default memo(MentionTooltip);\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiAttachment, ApiChatMember, ApiUser } from '../../../api/types';\nimport { LangCode } from '../../../types';\n\nimport { CONTENT_TYPES_FOR_QUICK_UPLOAD, EDITABLE_INPUT_MODAL_ID } from '../../../config';\nimport { getFileExtension } from '../../common/helpers/documentInfo';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Modal from '../../ui/Modal';\nimport File from '../../common/File';\nimport MessageInput from './MessageInput';\nimport MentionTooltip from './MentionTooltip';\nimport EmojiTooltip from './EmojiTooltip.async';\n\nimport './AttachmentModal.scss';\n\nexport type OwnProps = {\n attachments: ApiAttachment[];\n caption: string;\n canSuggestMembers?: boolean;\n canSuggestEmoji?: boolean;\n currentUserId?: number;\n groupChatMembers?: ApiChatMember[];\n usersById?: Record;\n recentEmojis: string[];\n language: LangCode;\n addRecentEmoji: AnyToVoidFunction;\n loadEmojiKeywords: AnyToVoidFunction;\n onCaptionUpdate: (html: string) => void;\n onSend: () => void;\n onFileAppend: (files: File[], isQuick: boolean) => void;\n onClear: () => void;\n};\n\nconst DROP_LEAVE_TIMEOUT_MS = 150;\n\nconst AttachmentModal: FC = ({\n attachments,\n caption,\n canSuggestMembers,\n groupChatMembers,\n currentUserId,\n usersById,\n recentEmojis,\n language,\n onCaptionUpdate,\n addRecentEmoji,\n loadEmojiKeywords,\n onSend,\n onFileAppend,\n onClear,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const hideTimeoutRef = useRef(null);\n const prevAttachments = usePrevious(attachments);\n const renderingAttachments = attachments.length ? attachments : prevAttachments;\n const isOpen = Boolean(attachments.length);\n const [isHovered, markHovered, unmarkHovered] = useFlag();\n const isQuick = renderingAttachments && renderingAttachments.every((a) => a.quick);\n const lang = useLang();\n\n const {\n isMentionTooltipOpen, mentionFilter,\n closeMentionTooltip, insertMention,\n mentionFilteredMembers,\n } = useMentionTooltip(\n canSuggestMembers && isOpen,\n caption,\n onCaptionUpdate,\n EDITABLE_INPUT_MODAL_ID,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n isOpen,\n caption,\n recentEmojis,\n EDITABLE_INPUT_MODAL_ID,\n onCaptionUpdate,\n );\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClear) : undefined), [isOpen, onClear]);\n\n const sendAttachments = useCallback(() => {\n if (isOpen) {\n onSend();\n }\n }, [isOpen, onSend]);\n\n const handleDragLeave = (e: React.DragEvent) => {\n const { relatedTarget: toTarget, target: fromTarget } = e;\n\n // Esc button pressed during drag event\n if ((fromTarget as HTMLDivElement).matches('.drop-target') && !toTarget) {\n hideTimeoutRef.current = window.setTimeout(unmarkHovered, DROP_LEAVE_TIMEOUT_MS);\n }\n\n // Prevent DragLeave event from firing when the pointer moves inside the AttachmentModal drop target\n if (fromTarget && (fromTarget as HTMLElement).closest('.AttachmentModal.hovered')) {\n return;\n }\n\n if (toTarget) {\n e.stopPropagation();\n }\n\n unmarkHovered();\n };\n\n const handleFilesDrop = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n unmarkHovered();\n\n const { dataTransfer: { files } } = e;\n\n if (files && files.length) {\n const newFiles = isQuick\n ? Array.from(files).filter((file) => {\n return file.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(file.type);\n })\n : Array.from(files);\n\n onFileAppend(newFiles, false);\n }\n }, [isQuick, onFileAppend, unmarkHovered]);\n\n function handleDragOver(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n\n if (hideTimeoutRef.current) {\n window.clearTimeout(hideTimeoutRef.current);\n }\n }\n\n if (!renderingAttachments) {\n return undefined;\n }\n\n const areAllPhotos = renderingAttachments.every((a) => a.mimeType.startsWith('image/'));\n const areAllVideos = renderingAttachments.every((a) => a.mimeType.startsWith('video/'));\n\n let title = '';\n if (areAllPhotos) {\n title = lang('PreviewSender.SendPhoto', renderingAttachments.length, 'i');\n } else if (areAllVideos) {\n title = lang('PreviewSender.SendVideo', renderingAttachments.length, 'i');\n } else {\n title = lang('PreviewSender.SendFile', renderingAttachments.length, 'i');\n }\n\n function renderHeader() {\n if (!renderingAttachments) {\n return undefined;\n }\n\n return (\n
\n \n
{title}
\n \n {lang('Send')}\n \n
\n );\n }\n\n return (\n \n \n {isQuick ? (\n
\n {renderingAttachments.map((attachment) => (\n attachment.mimeType.startsWith('image/')\n ? \"\"\n :
\n ) : (\n
\n {renderingAttachments.map((attachment) => (\n \n ))}\n
\n )}\n\n
\n \n \n \n
\n \n \n );\n};\n\nexport default memo(AttachmentModal);\n","import { ChangeEvent, RefObject } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiNewPoll } from '../../../api/types';\n\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Modal from '../../ui/Modal';\nimport InputText from '../../ui/InputText';\nimport Checkbox from '../../ui/Checkbox';\nimport RadioGroup from '../../ui/RadioGroup';\n\nimport './PollModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onSend: (pollSummary: ApiNewPoll) => void;\n onClear: () => void;\n};\n\nconst MAX_LIST_HEIGHT = 320;\nconst MAX_OPTIONS_COUNT = 10;\nconst MAX_OPTION_LENGTH = 100;\nconst MAX_QUESTION_LENGTH = 255;\nconst MAX_SOLUTION_LENGTH = 200;\n\nconst PollModal: FC = ({ isOpen, onSend, onClear }) => {\n // eslint-disable-next-line no-null/no-null\n const questionInputRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const optionsListRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const solutionRef = useRef(null);\n\n const [question, setQuestion] = useState('');\n const [options, setOptions] = useState(['']);\n const [isAnonymous, setIsAnonymous] = useState(true);\n const [isMultipleAnswers, setIsMultipleAnswers] = useState(false);\n const [isQuizMode, setIsQuizMode] = useState(false);\n const [solution, setSolution] = useState();\n const [correctOption, setCorrectOption] = useState();\n const [hasErrors, setHasErrors] = useState(false);\n\n const lang = useLang();\n\n const focusInput = useCallback((ref: RefObject) => {\n if (isOpen && ref.current) {\n ref.current.focus();\n }\n }, [isOpen]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClear) : undefined), [isOpen, onClear]);\n useEffect(() => {\n if (!isOpen) {\n setQuestion('');\n setOptions(['']);\n setIsAnonymous(true);\n setIsMultipleAnswers(false);\n setIsQuizMode(false);\n setSolution('');\n setCorrectOption('');\n setHasErrors(false);\n }\n }, [isOpen]);\n\n useEffect(() => focusInput(questionInputRef), [focusInput, isOpen]);\n\n useLayoutEffect(() => {\n const solutionEl = solutionRef.current;\n\n if (solutionEl && solution !== solutionEl.innerHTML) {\n solutionEl.innerHTML = solution;\n }\n }, [solution]);\n\n const addNewOption = useCallback((newOptions: string[] = []) => {\n setOptions([...newOptions, '']);\n requestAnimationFrame(() => {\n const list = optionsListRef.current;\n if (!list) {\n return;\n }\n\n list.classList.toggle('overflown', list.scrollHeight > MAX_LIST_HEIGHT);\n list.scrollTo({ top: list.scrollHeight, behavior: 'smooth' });\n });\n }, []);\n\n const handleCreate = useCallback(() => {\n setHasErrors(false);\n if (!isOpen) {\n return;\n }\n\n const questionTrimmed = question.trim().substring(0, MAX_QUESTION_LENGTH);\n const optionsTrimmed = options.map((o) => o.trim().substring(0, MAX_OPTION_LENGTH)).filter((o) => o.length);\n\n if (!questionTrimmed || optionsTrimmed.length < 2) {\n setQuestion(questionTrimmed);\n if (optionsTrimmed.length) {\n if (optionsTrimmed.length < 2) {\n addNewOption(optionsTrimmed);\n } else {\n setOptions(optionsTrimmed);\n }\n } else {\n addNewOption();\n }\n setHasErrors(true);\n return;\n }\n\n if (isQuizMode && (!correctOption || !optionsTrimmed[Number(correctOption)])) {\n setHasErrors(true);\n return;\n }\n\n const answers = optionsTrimmed\n .map((text, index) => ({\n text: text.trim(),\n option: String(index),\n ...(String(index) === correctOption && { correct: true }),\n }));\n\n const payload: ApiNewPoll = {\n summary: {\n question: questionTrimmed,\n answers,\n ...(!isAnonymous && { isPublic: true }),\n ...(isMultipleAnswers && { multipleChoice: true }),\n ...(isQuizMode && { quiz: true }),\n },\n };\n\n if (isQuizMode) {\n const { text, entities } = (solution && parseMessageInput(solution.substring(0, MAX_SOLUTION_LENGTH))) || {};\n\n payload.quiz = {\n correctAnswers: [correctOption],\n ...(text && { solution: text }),\n ...(entities && { solutionEntities: entities }),\n };\n }\n\n onSend(payload);\n }, [\n isOpen,\n question,\n options,\n isQuizMode,\n correctOption,\n isAnonymous,\n isMultipleAnswers,\n onSend,\n addNewOption,\n solution,\n ]);\n\n const updateOption = useCallback((index: number, text: string) => {\n const newOptions = [...options];\n newOptions[index] = text;\n if (newOptions[newOptions.length - 1].trim().length && newOptions.length < MAX_OPTIONS_COUNT) {\n addNewOption(newOptions);\n } else {\n setOptions(newOptions);\n }\n }, [options, addNewOption]);\n\n const removeOption = useCallback((index: number) => {\n const newOptions = [...options];\n newOptions.splice(index, 1);\n setOptions(newOptions);\n requestAnimationFrame(() => {\n if (!optionsListRef.current) {\n return;\n }\n\n optionsListRef.current.classList.toggle('overflown', optionsListRef.current.scrollHeight > MAX_LIST_HEIGHT);\n });\n }, [options]);\n\n const handleCorrectOptionChange = useCallback((newValue: string) => {\n setCorrectOption(newValue);\n }, [setCorrectOption]);\n\n const handleIsAnonymousChange = useCallback((e: ChangeEvent) => {\n setIsAnonymous(e.target.checked);\n }, []);\n\n const handleMultipleAnswersChange = useCallback((e: ChangeEvent) => {\n setIsMultipleAnswers(e.target.checked);\n }, []);\n\n const handleQuizModeChange = useCallback((e: ChangeEvent) => {\n setIsQuizMode(e.target.checked);\n }, []);\n\n const handleKeyPress = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode === 13) {\n handleCreate();\n }\n }, [handleCreate]);\n\n const getQuestionError = useCallback(() => {\n if (hasErrors && !question.trim().length) {\n return lang('lng_polls_choose_question');\n }\n\n return undefined;\n }, [hasErrors, lang, question]);\n\n const getOptionsError = useCallback((index: number) => {\n const optionsTrimmed = options.map((o) => o.trim()).filter((o) => o.length);\n if (hasErrors && optionsTrimmed.length < 2 && !options[index].trim().length) {\n return lang('lng_polls_choose_answers');\n }\n return undefined;\n }, [hasErrors, lang, options]);\n\n function renderHeader() {\n return (\n
\n \n
{lang('NewPoll')}
\n \n {lang('Create')}\n \n
\n );\n }\n\n function renderOptions() {\n return options.map((option, index) => (\n
\n updateOption(index, e.currentTarget.value)}\n onKeyPress={handleKeyPress}\n />\n {index !== options.length - 1 && (\n removeOption(index)}\n >\n \n \n )}\n
\n ));\n }\n\n function renderRadioOptions() {\n return renderOptions()\n .map((label, index) => ({ value: String(index), label, hidden: index === options.length - 1 }));\n }\n\n function renderQuizNoOptionError() {\n const optionsTrimmed = options.map((o) => o.trim()).filter((o) => o.length);\n\n return isQuizMode && (!correctOption || !optionsTrimmed[Number(correctOption)]) && (\n

{lang('lng_polls_choose_correct')}

\n );\n }\n\n return (\n \n setQuestion(e.currentTarget.value)}\n onKeyPress={handleKeyPress}\n />\n
\n\n
\n

Options

\n\n {hasErrors && renderQuizNoOptionError()}\n {isQuizMode ? (\n \n ) : (\n renderOptions()\n )}\n\n
\n\n
\n\n
\n \n \n \n {isQuizMode && (\n <>\n

Solution

\n setSolution(e.currentTarget.innerHTML)}\n />\n
{lang('CreatePoll.ExplanationInfo')}
\n \n )}\n
\n \n );\n};\n\nexport default memo(PollModal);\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../util/environment';\n\nconst MENU_CLOSE_TIMEOUT = 250;\nlet closeTimeout: number | undefined;\n\nexport default function useMouseInside(\n isOpen: boolean, onClose: NoneToVoidFunction, menuCloseTimeout = MENU_CLOSE_TIMEOUT,\n) {\n const isMouseInside = useRef(false);\n\n useEffect(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n if (isOpen && !IS_TOUCH_ENV) {\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n onClose();\n }\n }, menuCloseTimeout * 2);\n }\n }, [isOpen, menuCloseTimeout, onClose]);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n }, []);\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 onClose();\n }\n }, menuCloseTimeout);\n }, [menuCloseTimeout, onClose]);\n\n return [handleMouseEnter, handleMouseLeave];\n}\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\n\nimport './EmojiButton.scss';\n\ntype OwnProps = {\n emoji: Emoji;\n focus?: boolean;\n onClick: (emoji: string, name: string) => void;\n};\n\nconst EmojiButton: FC = ({ emoji, focus, onClick }) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n // Preventing safari from losing focus on Composer MessageInput\n e.preventDefault();\n\n onClick(emoji.native, emoji.id);\n }, [emoji, onClick]);\n\n return (\n \n {IS_EMOJI_SUPPORTED\n ? {emoji.native}\n : \"\"}\n
\n );\n};\n\nexport default memo(EmojiButton);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport windowSize from '../../../util/windowSize';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\n\nimport EmojiButton from './EmojiButton';\n\nconst EMOJIS_PER_ROW_ON_DESKTOP = 9;\nconst EMOJI_MARGIN = 4;\nconst MOBILE_CONTAINER_PADDING = 8;\nconst EMOJI_SIZE = 40;\n\ntype OwnProps = {\n category: EmojiCategory;\n index: number;\n allEmojis: AllEmojis;\n observeIntersection: ObserveFn;\n shouldRender: boolean;\n onEmojiSelect: (emoji: string, name: string) => void;\n};\n\nconst EmojiCategory: FC = ({\n category, index, allEmojis, observeIntersection, shouldRender, onEmojiSelect,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n\n const { transitionClassNames } = useShowTransition(shouldRender, undefined, undefined, 'slow');\n\n const lang = useLang();\n\n const emojisPerRow = IS_MOBILE_SCREEN\n ? Math.floor((windowSize.get().width - MOBILE_CONTAINER_PADDING) / (EMOJI_SIZE + EMOJI_MARGIN))\n : EMOJIS_PER_ROW_ON_DESKTOP;\n const height = Math.ceil(category.emojis.length / emojisPerRow) * (EMOJI_SIZE + EMOJI_MARGIN);\n\n return (\n \n

\n {lang(category.id === 'recent' ? 'RecentStickers' : `Emoji${index}`)}\n

\n \n {shouldRender && category.emojis.map((name) => {\n const emoji = allEmojis[name];\n // Some emojis have multiple skins and are represented as an Object with emojis for all skins.\n // For now, we select only the first emoji with 'neutral' skin.\n const displayedEmoji = 'id' in emoji ? emoji : emoji[1];\n\n return (\n \n );\n })}\n
\n \n );\n};\n\nexport default memo(EmojiCategory);\n","import React, {\n FC, useState, useEffect, memo, useRef, useMemo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { MENU_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n EmojiModule,\n EmojiRawData,\n EmojiData,\n uncompressEmoji,\n} from '../../../util/emoji';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Loading from '../../ui/Loading';\nimport EmojiCategory from './EmojiCategory';\n\nimport './EmojiPicker.scss';\n\ntype OwnProps = {\n className?: string;\n onEmojiSelect: (emoji: string, name: string) => void;\n};\n\ntype StateProps = Pick;\ntype EmojiCategoryData = { id: string; name: string; emojis: string[] };\n\nconst ICONS_BY_CATEGORY: Record = {\n recent: 'icon-recent',\n people: 'icon-smile',\n nature: 'icon-animals',\n foods: 'icon-eats',\n activity: 'icon-sport',\n places: 'icon-car',\n objects: 'icon-lamp',\n symbols: 'icon-language',\n flags: 'icon-flag',\n};\n\nconst OPEN_ANIMATION_DELAY = 200;\n// Only a few categories are above this height.\nconst SMOOTH_SCROLL_DISTANCE = 800;\nconst FOCUS_MARGIN = 50;\nconst HEADER_BUTTON_WIDTH = 42; // px. Includes margins\nconst INTERSECTION_THROTTLE = 200;\n\nconst categoryIntersections: boolean[] = [];\n\nlet emojiDataPromise: Promise;\nlet emojiRawData: EmojiRawData;\nlet emojiData: EmojiData;\n\nconst EmojiPicker: FC = ({\n className, onEmojiSelect, recentEmojis,\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 headerRef = useRef(null);\n\n const [categories, setCategories] = useState();\n const [emojis, setEmojis] = useState();\n const [activeCategoryIndex, setActiveCategoryIndex] = useState(0);\n\n const { observe: observeIntersection } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE,\n }, (entries) => {\n entries.forEach((entry) => {\n const { id } = entry.target as HTMLDivElement;\n if (!id || !id.startsWith('emoji-category-')) {\n return;\n }\n\n const index = Number(id.replace('emoji-category-', ''));\n categoryIntersections[index] = entry.isIntersecting;\n });\n\n const intersectingWithIndexes = categoryIntersections\n .map((isIntersecting, index) => ({ index, isIntersecting }))\n .filter(({ isIntersecting }) => isIntersecting);\n\n if (!intersectingWithIndexes.length) {\n return;\n }\n\n setActiveCategoryIndex(intersectingWithIndexes[Math.floor(intersectingWithIndexes.length / 2)].index);\n });\n\n useHorizontalScroll(headerRef, !IS_MOBILE_SCREEN);\n\n // Scroll header when active set updates\n useEffect(() => {\n if (!categories) {\n return;\n }\n\n const header = headerRef.current;\n if (!header) {\n return;\n }\n\n const newLeft = activeCategoryIndex * HEADER_BUTTON_WIDTH - header.offsetWidth / 2 + HEADER_BUTTON_WIDTH / 2;\n\n fastSmoothScrollHorizontal(header, newLeft);\n }, [categories, activeCategoryIndex]);\n\n const lang = useLang();\n\n const allCategories = useMemo(() => {\n if (!categories) {\n return MEMO_EMPTY_ARRAY;\n }\n const themeCategories = [...categories];\n if (recentEmojis && recentEmojis.length) {\n themeCategories.unshift({\n id: 'recent',\n name: lang('RecentStickers'),\n emojis: recentEmojis,\n });\n }\n\n return themeCategories;\n }, [categories, lang, recentEmojis]);\n\n // Initialize data on first render.\n useEffect(() => {\n setTimeout(() => {\n const exec = () => {\n setCategories(emojiData.categories);\n\n setEmojis(emojiData.emojis as AllEmojis);\n };\n\n if (emojiData) {\n exec();\n } else {\n ensureEmojiData()\n .then(exec);\n }\n }, OPEN_ANIMATION_DELAY);\n }, []);\n\n const selectCategory = useCallback((index: number) => {\n setActiveCategoryIndex(index);\n const categoryEl = document.getElementById(`emoji-category-${index}`)!;\n fastSmoothScroll(containerRef.current!, categoryEl, 'start', FOCUS_MARGIN, SMOOTH_SCROLL_DISTANCE);\n }, []);\n\n const handleEmojiSelect = useCallback((emoji: string, name: string) => {\n onEmojiSelect(emoji, name);\n }, [onEmojiSelect]);\n\n const canRenderContents = useAsyncRendering([], MENU_TRANSITION_DURATION);\n\n function renderCategoryButton(category: EmojiCategoryData, index: number) {\n const icon = ICONS_BY_CATEGORY[category.id];\n\n return icon && (\n selectCategory(index)}\n ariaLabel={category.name}\n >\n \n \n );\n }\n\n const containerClassName = buildClassName('EmojiPicker', className);\n\n if (!emojis || !canRenderContents) {\n return (\n
\n \n
\n );\n }\n\n return (\n
\n
\n {allCategories.map(renderCategoryButton)}\n
\n
\n {allCategories.map((category, i) => (\n = i - 1 && activeCategoryIndex <= i + 1}\n onEmojiSelect={handleEmojiSelect}\n />\n ))}\n
\n
\n );\n};\n\nasync function ensureEmojiData() {\n if (!emojiDataPromise) {\n emojiDataPromise = import('emoji-data-ios/emoji-data.json') as unknown as Promise;\n emojiRawData = (await emojiDataPromise).default;\n\n emojiData = uncompressEmoji(emojiRawData);\n }\n\n return emojiDataPromise;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['recentEmojis']),\n)(EmojiPicker));\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiSticker } from '../../../api/types';\nimport { StickerSetOrRecent } from '../../../types';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\n\nimport { STICKER_SIZE_PICKER } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport windowSize from '../../../util/windowSize';\nimport StickerButton from '../../common/StickerButton';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n stickerSet: StickerSetOrRecent;\n loadAndPlay: boolean;\n index: number;\n observeIntersection: ObserveFn;\n shouldRender: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n onStickerUnfave: (sticker: ApiSticker) => void;\n};\n\nconst STICKERS_PER_ROW_ON_DESKTOP = 5;\nconst STICKER_MARGIN = IS_MOBILE_SCREEN ? 8 : 16;\nconst MOBILE_CONTAINER_PADDING = 8;\n\nconst StickerSet: FC = ({\n stickerSet,\n loadAndPlay,\n index,\n observeIntersection,\n shouldRender,\n onStickerSelect,\n onStickerUnfave,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n\n const { transitionClassNames } = useShowTransition(shouldRender, undefined, undefined, 'slow');\n\n const stickersPerRow = IS_MOBILE_SCREEN\n ? Math.floor((windowSize.get().width - MOBILE_CONTAINER_PADDING) / (STICKER_SIZE_PICKER + STICKER_MARGIN))\n : STICKERS_PER_ROW_ON_DESKTOP;\n const height = Math.ceil(stickerSet.count / stickersPerRow) * (STICKER_SIZE_PICKER + STICKER_MARGIN);\n\n return (\n \n

{stickerSet.title}

\n \n {shouldRender && stickerSet.stickers && stickerSet.stickers.map((sticker) => (\n \n ))}\n \n \n );\n};\n\nexport default memo(StickerSet);\n","import React, {\n FC, useState, useEffect, memo, useRef, useMemo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiStickerSet, ApiSticker } from '../../../api/types';\nimport { StickerSetOrRecent } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION, STICKER_SIZE_PICKER_HEADER } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Loading from '../../ui/Loading';\nimport Button from '../../ui/Button';\nimport StickerButton from '../../common/StickerButton';\nimport StickerSet from './StickerSet';\nimport StickerSetCover from './StickerSetCover';\nimport StickerSetCoverAnimated from './StickerSetCoverAnimated';\n\nimport './StickerPicker.scss';\n\ntype OwnProps = {\n className: string;\n loadAndPlay: boolean;\n canSendStickers: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n};\n\ntype StateProps = {\n recentStickers: ApiSticker[];\n favoriteStickers: ApiSticker[];\n stickerSetsById: Record;\n addedSetIds?: string[];\n shouldPlay?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SMOOTH_SCROLL_DISTANCE = 500;\nconst HEADER_BUTTON_WIDTH = 52; // px (including margin)\nconst STICKER_INTERSECTION_THROTTLE = 200;\n\nconst stickerSetIntersections: boolean[] = [];\n\nconst StickerPicker: FC = ({\n className,\n loadAndPlay,\n canSendStickers,\n recentStickers,\n favoriteStickers,\n addedSetIds,\n stickerSetsById,\n shouldPlay,\n onStickerSelect,\n loadStickerSets,\n loadRecentStickers,\n loadFavoriteStickers,\n loadAddedStickers,\n addRecentSticker,\n unfaveSticker,\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 headerRef = useRef(null);\n const [activeSetIndex, setActiveSetIndex] = useState(0);\n\n const { observe: observeIntersection } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: STICKER_INTERSECTION_THROTTLE,\n }, (entries) => {\n entries.forEach((entry) => {\n const { id } = entry.target as HTMLDivElement;\n if (!id || !id.startsWith('sticker-set-')) {\n return;\n }\n\n const index = Number(id.replace('sticker-set-', ''));\n stickerSetIntersections[index] = entry.isIntersecting;\n });\n\n const intersectingWithIndexes = stickerSetIntersections\n .map((isIntersecting, index) => ({ index, isIntersecting }))\n .filter(({ isIntersecting }) => isIntersecting);\n\n if (!intersectingWithIndexes.length) {\n return;\n }\n\n setActiveSetIndex(intersectingWithIndexes[Math.floor(intersectingWithIndexes.length / 2)].index);\n });\n const { observe: observeIntersectionForCovers } = useIntersectionObserver({ rootRef: headerRef });\n\n const lang = useLang();\n\n const areAddedLoaded = Boolean(addedSetIds);\n\n const allSets = useMemo(() => {\n if (!addedSetIds) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return [\n {\n id: 'recent',\n title: lang('RecentStickers'),\n stickers: recentStickers,\n count: recentStickers.length,\n },\n {\n id: 'favorite',\n title: lang('FavoriteStickers'),\n stickers: favoriteStickers,\n count: favoriteStickers.length,\n },\n ...addedSetIds.map((id) => stickerSetsById[id]).filter(Boolean),\n ];\n }, [addedSetIds, lang, recentStickers, favoriteStickers, stickerSetsById]);\n\n const noPopulatedSets = useMemo(() => (\n areAddedLoaded\n && allSets.filter((set) => set.stickers && set.stickers.length).length === 0\n ), [allSets, areAddedLoaded]);\n\n useEffect(() => {\n if (loadAndPlay) {\n loadStickerSets();\n loadRecentStickers();\n loadFavoriteStickers();\n }\n }, [loadAndPlay, loadFavoriteStickers, loadRecentStickers, loadStickerSets]);\n\n useEffect(() => {\n if (addedSetIds && addedSetIds.length) {\n loadAddedStickers();\n }\n }, [addedSetIds, loadAddedStickers]);\n\n useHorizontalScroll(headerRef);\n\n // Scroll container and header when active set changes\n useEffect(() => {\n if (!areAddedLoaded) {\n return;\n }\n\n const header = headerRef.current;\n if (!header) {\n return;\n }\n\n const newLeft = activeSetIndex * HEADER_BUTTON_WIDTH - (header.offsetWidth / 2 - HEADER_BUTTON_WIDTH / 2);\n\n fastSmoothScrollHorizontal(header, newLeft);\n }, [areAddedLoaded, activeSetIndex]);\n\n const selectStickerSet = useCallback((index: number) => {\n setActiveSetIndex(index);\n const stickerSetEl = document.getElementById(`sticker-set-${index}`)!;\n fastSmoothScroll(containerRef.current!, stickerSetEl, 'start', undefined, SMOOTH_SCROLL_DISTANCE);\n }, []);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n onStickerSelect(sticker);\n addRecentSticker({ sticker });\n }, [addRecentSticker, onStickerSelect]);\n\n const handleStickerUnfave = useCallback((sticker: ApiSticker) => {\n unfaveSticker({ sticker });\n }, [unfaveSticker]);\n\n const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION);\n\n function renderCover(stickerSet: StickerSetOrRecent, index: number) {\n const firstSticker = stickerSet.stickers && stickerSet.stickers[0];\n const buttonClassName = buildClassName(\n 'symbol-set-button sticker-set-button',\n index === activeSetIndex && 'activated',\n );\n\n if (stickerSet.id === 'recent' || stickerSet.id === 'favorite' || stickerSet.hasThumbnail || !firstSticker) {\n return (\n selectStickerSet(index)}\n >\n {stickerSet.id === 'recent' ? (\n \n ) : stickerSet.id === 'favorite' ? (\n \n ) : stickerSet.isAnimated ? (\n \n ) : (\n \n )}\n \n );\n } else {\n return (\n \n );\n }\n }\n\n const fullClassName = buildClassName('StickerPicker', className);\n\n if (!areAddedLoaded || !canRenderContents || noPopulatedSets || !canSendStickers) {\n return (\n
\n {!canSendStickers ? (\n
Sending stickers is not allowed in this chat.
\n ) : noPopulatedSets ? (\n
You have no saved Stickers.
\n ) : (\n \n )}\n
\n );\n }\n\n return (\n
\n \n {allSets.map(renderCover)}\n
\n
\n {allSets.map((stickerSet, i) => (\n = i - 1 && activeSetIndex <= i + 1}\n onStickerSelect={handleStickerSelect}\n onStickerUnfave={handleStickerUnfave}\n />\n ))}\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n setsById,\n added,\n recent,\n favorite,\n } = global.stickers;\n\n return {\n recentStickers: recent.stickers,\n favoriteStickers: favorite.stickers,\n stickerSetsById: setsById,\n addedSetIds: added.setIds,\n shouldPlay: global.settings.byKey.shouldLoopStickers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadStickerSets',\n 'loadRecentStickers',\n 'loadFavoriteStickers',\n 'loadAddedStickers',\n 'addRecentSticker',\n 'unfaveSticker',\n ]),\n)(StickerPicker));\n","import React, {\n FC, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiVideo } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useVideoCleanup from '../../hooks/useVideoCleanup';\nimport useBuffering from '../../hooks/useBuffering';\nimport useCanvasBlur from '../../hooks/useCanvasBlur';\n\nimport Spinner from '../ui/Spinner';\n\nimport './GifButton.scss';\n\ntype OwnProps = {\n gif: ApiVideo;\n observeIntersection: ObserveFn;\n isDisabled?: boolean;\n onClick: (gif: ApiVideo) => void;\n};\n\nconst GifButton: FC = ({\n gif, observeIntersection, isDisabled, onClick,\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 hasThumbnail = gif.thumbnail && !!gif.thumbnail.dataUri;\n const localMediaHash = `gif${gif.id}`;\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n const loadAndPlay = isIntersecting && !isDisabled;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !loadAndPlay, ApiMediaFormat.BlobUrl);\n const thumbRef = useCanvasBlur(gif.thumbnail && gif.thumbnail.dataUri, Boolean(previewBlobUrl));\n const videoData = useMedia(localMediaHash, !loadAndPlay, ApiMediaFormat.BlobUrl);\n const shouldRenderVideo = Boolean(loadAndPlay && videoData);\n const { transitionClassNames } = useTransitionForMedia(hasThumbnail || previewBlobUrl || videoData, 'slow');\n const { isBuffered, bufferingHandlers } = useBuffering(true);\n const shouldRenderSpinner = loadAndPlay && !isBuffered;\n\n useVideoCleanup(videoRef, [shouldRenderVideo]);\n\n const handleClick = useCallback(\n () => onClick({\n ...gif,\n blobUrl: videoData,\n }),\n [onClick, gif, videoData],\n );\n\n const className = buildClassName(\n 'GifButton',\n gif.width && gif.height && gif.width < gif.height ? 'vertical' : 'horizontal',\n transitionClassNames,\n localMediaHash,\n );\n\n return (\n \n {hasThumbnail && (\n \n )}\n {!hasThumbnail && previewBlobUrl && (\n \n )}\n {(shouldRenderVideo || previewBlobUrl) && (\n \n \n \n )}\n {shouldRenderSpinner && (\n \n )}\n \n );\n};\n\nexport default memo(GifButton);\n","import React, {\n FC, useEffect, memo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiVideo } from '../../../api/types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\n\nimport Loading from '../../ui/Loading';\nimport GifButton from '../../common/GifButton';\n\nimport './GifPicker.scss';\n\ntype OwnProps = {\n className: string;\n loadAndPlay: boolean;\n canSendGifs: boolean;\n onGifSelect: (gif: ApiVideo) => void;\n};\n\ntype StateProps = {\n savedGifs?: ApiVideo[];\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_DEBOUNCE = 300;\n\nconst GifPicker: FC = ({\n className,\n loadAndPlay,\n canSendGifs,\n savedGifs,\n onGifSelect,\n loadSavedGifs,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE });\n\n useEffect(() => {\n if (loadAndPlay) {\n loadSavedGifs();\n }\n }, [loadAndPlay, loadSavedGifs]);\n\n const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION);\n\n return (\n
\n {!canSendGifs ? (\n
Sending GIFs is not allowed in this chat.
\n ) : canRenderContents && savedGifs && savedGifs.length ? (\n savedGifs.map((gif) => (\n \n ))\n ) : canRenderContents && savedGifs ? (\n
No saved GIFs.
\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n savedGifs: global.gifs.saved.gifs,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadSavedGifs']),\n)(GifPicker));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\ntype OwnProps = {\n activeTab: SymbolMenuTabs;\n onSwitchTab: (tab: SymbolMenuTabs) => void;\n onRemoveSymbol: () => void;\n onSearchOpen: (type: 'stickers' | 'gifs') => void;\n};\n\nexport enum SymbolMenuTabs {\n 'Emoji',\n 'Stickers',\n 'GIFs',\n}\n\n// Getting enum string values for display in Tabs.\n// See: https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\nexport const SYMBOL_MENU_TAB_TITLES = Object.values(SymbolMenuTabs)\n .filter((value): value is string => typeof value === 'string');\n\nconst SYMBOL_MENU_TAB_ICONS = {\n [SymbolMenuTabs.Emoji]: 'icon-smile',\n [SymbolMenuTabs.Stickers]: 'icon-stickers',\n [SymbolMenuTabs.GIFs]: 'icon-gifs',\n};\n\nconst SymbolMenuFooter: FC = ({\n activeTab, onSwitchTab, onRemoveSymbol, onSearchOpen,\n}) => {\n const lang = useLang();\n\n function renderTabButton(tab: SymbolMenuTabs) {\n return (\n onSwitchTab(tab)}\n ariaLabel={SYMBOL_MENU_TAB_TITLES[tab]}\n round\n faded\n color=\"translucent\"\n >\n \n \n );\n }\n\n const handleSearchOpen = useCallback(() => {\n onSearchOpen(activeTab === SymbolMenuTabs.Stickers ? 'stickers' : 'gifs');\n }, [activeTab, onSearchOpen]);\n\n function stopPropagation(event: any) {\n event.stopPropagation();\n }\n\n return (\n
\n {activeTab !== SymbolMenuTabs.Emoji && (\n \n \n \n )}\n\n {renderTabButton(SymbolMenuTabs.Emoji)}\n {renderTabButton(SymbolMenuTabs.Stickers)}\n {renderTabButton(SymbolMenuTabs.GIFs)}\n\n {activeTab === SymbolMenuTabs.Emoji && (\n \n \n \n )}\n
\n );\n};\n\nexport default memo(SymbolMenuFooter);\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiSticker, ApiVideo } from '../../../api/types';\n\nimport { IAllowedAttachmentOptions } from '../../../modules/helpers';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../util/environment';\nimport { fastRaf } from '../../../util/schedulers';\nimport buildClassName from '../../../util/buildClassName';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Menu from '../../ui/Menu';\nimport Transition from '../../ui/Transition';\nimport EmojiPicker from './EmojiPicker';\nimport StickerPicker from './StickerPicker';\nimport GifPicker from './GifPicker';\nimport SymbolMenuFooter, { SYMBOL_MENU_TAB_TITLES, SymbolMenuTabs } from './SymbolMenuFooter';\nimport Portal from '../../ui/Portal';\n\nimport './SymbolMenu.scss';\n\nconst ANIMATION_DURATION = 350;\n\nexport type OwnProps = {\n isOpen: boolean;\n allowedAttachmentOptions: IAllowedAttachmentOptions;\n onLoad: () => void;\n onClose: () => void;\n onEmojiSelect: (emoji: string) => void;\n onStickerSelect: (sticker: ApiSticker) => void;\n onGifSelect: (gif: ApiVideo) => void;\n onRemoveSymbol: () => void;\n onSearchOpen: (type: 'stickers' | 'gifs') => void;\n addRecentEmoji: AnyToVoidFunction;\n};\n\nlet isActivated = false;\n\nconst SymbolMenu: FC = ({\n isOpen, allowedAttachmentOptions,\n onLoad, onClose,\n onEmojiSelect, onStickerSelect, onGifSelect,\n onRemoveSymbol, onSearchOpen, addRecentEmoji,\n}) => {\n const [activeTab, setActiveTab] = useState(0);\n const [recentEmojis, setRecentEmojis] = useState([]);\n\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onClose, false, false);\n\n if (!isActivated && isOpen) {\n isActivated = true;\n }\n\n useEffect(() => {\n onLoad();\n }, [onLoad]);\n\n useLayoutEffect(() => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n if (isOpen) {\n document.body.classList.add('enable-symbol-menu-transforms');\n document.body.classList.add('is-symbol-menu-open');\n }\n\n return () => {\n if (isOpen) {\n fastRaf(() => {\n document.body.classList.remove('is-symbol-menu-open');\n setTimeout(() => {\n document.body.classList.remove('enable-symbol-menu-transforms');\n }, ANIMATION_DURATION);\n });\n }\n };\n }, [isOpen]);\n\n const recentEmojisRef = useRef(recentEmojis);\n recentEmojisRef.current = recentEmojis;\n useEffect(() => {\n if (!recentEmojisRef.current.length) {\n return;\n }\n\n recentEmojisRef.current.forEach((name) => {\n addRecentEmoji({ emoji: name });\n });\n\n setRecentEmojis([]);\n }, [isOpen, activeTab, addRecentEmoji]);\n\n const handleEmojiSelect = useCallback((emoji: string, name: string) => {\n setRecentEmojis((emojis) => {\n return [...emojis, name];\n });\n\n onEmojiSelect(emoji);\n }, [onEmojiSelect]);\n\n const handleSearch = useCallback((type: 'stickers' | 'gifs') => {\n onClose();\n onSearchOpen(type);\n }, [onClose, onSearchOpen]);\n\n const lang = useLang();\n\n const { canSendStickers, canSendGifs } = allowedAttachmentOptions;\n\n function renderContent(isActive: boolean, isFrom: boolean) {\n switch (activeTab) {\n case SymbolMenuTabs.Emoji:\n return (\n \n );\n case SymbolMenuTabs.Stickers:\n return (\n \n );\n case SymbolMenuTabs.GIFs:\n return (\n \n );\n }\n\n return undefined;\n }\n\n function stopPropagation(event: any) {\n event.stopPropagation();\n }\n\n const content = (\n <>\n
\n {isActivated && (\n \n {renderContent}\n \n )}\n
\n {IS_MOBILE_SCREEN && (\n \n \n \n )}\n \n \n );\n\n if (IS_MOBILE_SCREEN) {\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'SymbolMenu mobile-menu',\n transitionClassNames,\n );\n\n return (\n \n
\n {content}\n
\n
\n );\n }\n\n return (\n \n {content}\n \n );\n};\n\nexport default memo(SymbolMenu);\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { CONTENT_TYPES_FOR_QUICK_UPLOAD } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport { IAllowedAttachmentOptions } from '../../../modules/helpers';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './AttachMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n allowedAttachmentOptions: IAllowedAttachmentOptions;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n onPollCreate: () => void;\n onClose: () => void;\n};\n\nconst AttachMenu: FC = ({\n isOpen, allowedAttachmentOptions, onFileSelect, onPollCreate, onClose,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\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 CONTENT_TYPES_FOR_QUICK_UPLOAD,\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 const { canAttachMedia, canAttachPolls } = allowedAttachmentOptions;\n\n return (\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\nexport default memo(AttachMenu);\n","import React, {\n FC, memo, useEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { STICKER_SIZE_PICKER } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport Loading from '../../ui/Loading';\nimport StickerButton from '../../common/StickerButton';\n\nimport './StickerTooltip.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n};\n\ntype StateProps = {\n stickers?: ApiSticker[];\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst StickerTooltip: FC = ({\n isOpen,\n onStickerSelect,\n stickers,\n clearStickersForEmoji,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n const prevStickers = usePrevious(stickers, true);\n const displayedStickers = stickers || prevStickers;\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE });\n\n useEffect(() => (isOpen ? captureEscKeyListener(clearStickersForEmoji) : undefined), [isOpen, clearStickersForEmoji]);\n\n const handleMouseEnter = () => {\n document.body.classList.add('no-select');\n };\n\n const handleMouseLeave = () => {\n document.body.classList.remove('no-select');\n };\n\n const className = buildClassName(\n 'StickerTooltip composer-tooltip custom-scroll',\n transitionClassNames,\n !(displayedStickers && displayedStickers.length) && 'hidden',\n );\n\n return (\n \n {shouldRender && displayedStickers ? (\n displayedStickers.map((sticker) => (\n \n ))\n ) : shouldRender ? (\n \n ) : undefined}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { stickers } = global.stickers.forEmoji;\n\n return { stickers };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['clearStickersForEmoji']),\n)(StickerTooltip));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../modules/selectors';\nimport useMouseInside from '../../../hooks/useMouseInside';\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\ntype DispatchProps = Pick;\n\nconst BotKeyboardMenu: FC = ({\n isOpen, message, onClose, clickInlineButton,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\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 (setGlobal, actions): DispatchProps => pick(actions, [\n 'clickInlineButton',\n ]),\n)(BotKeyboardMenu));\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './CustomSendMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onSilentSend?: NoneToVoidFunction;\n onScheduleSend?: NoneToVoidFunction;\n onClose: NoneToVoidFunction;\n onCloseAnimationEnd?: NoneToVoidFunction;\n};\n\nconst CustomSendMenu: FC = ({\n isOpen, onSilentSend, onScheduleSend, onClose, onCloseAnimationEnd,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n\n const lang = useLang();\n\n return (\n \n {onSilentSend && {lang('SendWithoutSound')}}\n {onScheduleSend && {lang('ScheduleMessage')}}\n \n );\n};\n\nexport default memo(CustomSendMenu);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport cycleRestrict from '../../../util/cycleRestrict';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport findInViewport from '../../../util/findInViewport';\nimport isFullyVisible from '../../../util/isFullyVisible';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevDuringAnimation from '../../../hooks/usePrevDuringAnimation';\n\nimport Loading from '../../ui/Loading';\nimport EmojiButton from './EmojiButton';\n\nimport './EmojiTooltip.scss';\nimport { LangCode } from '../../../types';\n\nconst VIEWPORT_MARGIN = 8;\nconst EMOJI_BUTTON_WIDTH = 44;\n\nfunction setItemVisible(index: number, containerRef: Record) {\n const container = containerRef.current!;\n if (!container) {\n return;\n }\n\n const { visibleIndexes, allElements } = findInViewport(\n container,\n '.EmojiButton',\n VIEWPORT_MARGIN,\n true,\n true,\n true,\n );\n\n if (!allElements.length || !allElements[index]) {\n return;\n }\n const first = visibleIndexes[0];\n if (!visibleIndexes.includes(index)\n || (index === first && !isFullyVisible(container, allElements[first], true))) {\n const position = index > visibleIndexes[visibleIndexes.length - 1] ? 'start' : 'end';\n const newLeft = position === 'start' ? index * EMOJI_BUTTON_WIDTH : 0;\n\n fastSmoothScrollHorizontal(container, newLeft);\n }\n}\n\nexport type OwnProps = {\n isOpen: boolean;\n language: LangCode;\n onEmojiSelect: (text: string) => void;\n onClose: NoneToVoidFunction;\n addRecentEmoji: AnyToVoidFunction;\n loadEmojiKeywords: AnyToVoidFunction;\n emojis: Emoji[];\n};\n\nconst CLOSE_DURATION = 350;\n\nconst EmojiTooltip: FC = ({\n isOpen,\n language,\n emojis,\n onClose,\n onEmojiSelect,\n addRecentEmoji,\n loadEmojiKeywords,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n const listEmojis: Emoji[] = usePrevDuringAnimation(emojis.length ? emojis : undefined, CLOSE_DURATION) || [];\n\n const [selectedIndex, setSelectedIndex] = useState(-1);\n\n useEffect(() => {\n loadEmojiKeywords({ language });\n }, [loadEmojiKeywords, language]);\n\n useEffect(() => {\n setSelectedIndex(0);\n }, [emojis]);\n\n useEffect(() => {\n setItemVisible(selectedIndex, containerRef);\n }, [selectedIndex]);\n\n const getSelectedIndex = useCallback((newIndex: number) => {\n if (!emojis.length) {\n return -1;\n }\n\n const emojisCount = emojis.length;\n return cycleRestrict(emojisCount, newIndex);\n }, [emojis]);\n\n\n const handleArrowKey = useCallback((value: number, e: KeyboardEvent) => {\n e.preventDefault();\n setSelectedIndex((index) => (getSelectedIndex(index + value)));\n }, [setSelectedIndex, getSelectedIndex]);\n\n const handleSelectEmoji = useCallback((e: KeyboardEvent) => {\n if (emojis.length && selectedIndex > -1) {\n const emoji = emojis[selectedIndex];\n if (emoji) {\n e.preventDefault();\n onEmojiSelect(emoji.native);\n addRecentEmoji({ emoji: emoji.id });\n }\n }\n }, [addRecentEmoji, emojis, onEmojiSelect, selectedIndex]);\n\n useEffect(() => (isOpen ? captureKeyboardListeners({\n onEsc: onClose,\n onLeft: (e: KeyboardEvent) => handleArrowKey(-1, e),\n onRight: (e: KeyboardEvent) => handleArrowKey(1, e),\n onEnter: handleSelectEmoji,\n }) : undefined), [handleArrowKey, handleSelectEmoji, isOpen, onClose]);\n\n const handleMouseEnter = () => {\n document.body.classList.add('no-select');\n };\n\n const handleMouseLeave = () => {\n document.body.classList.remove('no-select');\n };\n\n const className = buildClassName(\n 'EmojiTooltip composer-tooltip custom-scroll-x',\n transitionClassNames,\n );\n\n return (\n \n {shouldRender && listEmojis ? (\n listEmojis.map((emoji, index) => (\n \n ))\n ) : shouldRender ? (\n \n ) : undefined}\n \n );\n};\n\nexport default memo(EmojiTooltip);\n","import React, {\n FC, useMemo, memo, useRef,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiUser, ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport {\n selectUser,\n selectChatMessages,\n selectChat,\n selectCurrentTextSearch,\n} from '../../modules/selectors';\nimport {\n getMessageSummaryText,\n getChatTitle,\n getUserFullName,\n isChatChannel,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport { orderBy, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport ListItem from '../ui/ListItem';\nimport LastMessageMeta from '../common/LastMessageMeta';\nimport Avatar from '../common/Avatar';\n\nimport './RightSearch.scss';\n\nexport type OwnProps = {\n chatId: number;\n threadId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n messagesById?: Record;\n query?: string;\n totalCount?: number;\n foundIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\ninterface Result {\n message: ApiMessage;\n senderUser?: ApiUser;\n senderChat?: ApiChat;\n onClick: NoneToVoidFunction;\n}\n\nconst RightSearch: FC = ({\n chatId,\n threadId,\n chat,\n messagesById,\n query,\n totalCount,\n foundIds,\n searchTextMessagesLocal,\n focusMessage,\n}) => {\n const lang = useLang();\n\n const foundResults = useMemo(() => {\n if (!query || !foundIds || !foundIds.length || !messagesById) {\n return MEMO_EMPTY_ARRAY;\n }\n\n const results = foundIds.map((id) => {\n const message = messagesById[id];\n if (!message) {\n return undefined;\n }\n\n const senderUser = message.senderId ? selectUser(getGlobal(), message.senderId) : undefined;\n\n let senderChat;\n if (chat && isChatChannel(chat)) {\n senderChat = chat;\n } else if (message.forwardInfo) {\n const { isChannelPost, fromChatId } = message.forwardInfo;\n senderChat = isChannelPost && fromChatId ? selectChat(getGlobal(), fromChatId) : undefined;\n } else {\n senderChat = message.senderId ? selectChat(getGlobal(), message.senderId) : undefined;\n }\n\n return {\n message,\n senderUser,\n senderChat,\n onClick: () => focusMessage({ chatId, threadId, messageId: id }),\n };\n }).filter(Boolean) as Result[];\n\n return orderBy(results, ({ message }) => message.date, 'desc');\n }, [chatId, threadId, focusMessage, foundIds, chat, messagesById, query]);\n\n const renderSearchResult = ({\n message, senderUser, senderChat, onClick,\n }: Result) => {\n const title = senderChat ? getChatTitle(lang, senderChat) : getUserFullName(senderUser);\n const text = getMessageSummaryText(lang, message);\n\n return (\n \n \n
\n
\n

{title && renderText(title)}

\n \n
\n
\n {renderText(text, ['emoji', 'highlight'], { highlight: query })}\n
\n
\n \n );\n };\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, true, (index) => {\n if (foundResults && foundResults[index]) {\n foundResults[index].onClick();\n }\n }, '.ListItem-button', true);\n\n return (\n \n

\n {!query ? (\n lang('lng_dlg_search_for_messages')\n ) : (totalCount === 0 || !foundResults.length) ? (\n lang('lng_search_no_results')\n ) : totalCount === 1 ? (\n '1 message found'\n ) : (\n `${(foundResults.length && (totalCount || foundResults.length))} messages found`\n )}\n

\n {foundResults.map(renderSearchResult)}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const messagesById = chat && selectChatMessages(global, chat.id);\n if (!chat || !messagesById) {\n return {};\n }\n\n const { query, results } = selectCurrentTextSearch(global) || {};\n const { totalCount, foundIds } = results || {};\n\n return {\n chat,\n messagesById,\n query,\n totalCount,\n foundIds,\n };\n },\n (global, actions): DispatchProps => pick(actions, ['searchTextMessagesLocal', 'focusMessage']),\n)(RightSearch));\n","import React, {\n FC, useEffect, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiStickerSet } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport { ObserveFn } from '../../hooks/useIntersectionObserver';\n\nimport { STICKER_SIZE_SEARCH } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport { selectShouldLoopStickers, selectStickerSet } from '../../modules/selectors';\nimport useFlag from '../../hooks/useFlag';\nimport useOnChange from '../../hooks/useOnChange';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport StickerButton from '../common/StickerButton';\nimport StickerSetModal from '../common/StickerSetModal.async';\nimport Spinner from '../ui/Spinner';\n\ntype OwnProps = {\n stickerSetId: string;\n observeIntersection: ObserveFn;\n isSomeModalOpen: boolean;\n onModalToggle: (isOpen: boolean) => void;\n};\n\ntype StateProps = {\n set?: ApiStickerSet;\n shouldPlay?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst STICKERS_TO_DISPLAY = 5;\n\nconst StickerSetResult: FC = ({\n stickerSetId, observeIntersection, set, shouldPlay,\n loadStickers, toggleStickerSet, isSomeModalOpen, onModalToggle,\n}) => {\n const lang = useLang();\n const isAdded = set && Boolean(set.installedDate);\n const areStickersLoaded = Boolean(set && set.stickers);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n useOnChange(() => {\n onModalToggle(isModalOpen);\n }, [isModalOpen, onModalToggle]);\n\n const displayedStickers = useMemo(() => {\n if (!set) {\n return [];\n }\n\n const coverStickerIds = (set.covers || []).map(({ id }) => id);\n const otherStickers = set.stickers ? set.stickers.filter(({ id }) => !coverStickerIds.includes(id)) : [];\n\n return [...set.covers || [], ...otherStickers].slice(0, STICKERS_TO_DISPLAY);\n }, [set]);\n\n useEffect(() => {\n // Featured stickers are initialized with one sticker in collection (cover of SickerSet)\n if (!areStickersLoaded && displayedStickers.length < STICKERS_TO_DISPLAY) {\n loadStickers({ stickerSetId });\n }\n }, [areStickersLoaded, displayedStickers.length, loadStickers, stickerSetId]);\n\n const handleAddClick = useCallback(() => {\n toggleStickerSet({ stickerSetId });\n }, [toggleStickerSet, stickerSetId]);\n\n if (!set) {\n return undefined;\n }\n\n const canRenderStickers = displayedStickers.length > 0;\n\n return (\n
\n
\n
\n

{set.title}

\n

{lang('Stickers', set.count, 'i')}

\n
\n \n {lang(isAdded ? 'Stickers.Installed' : 'Stickers.Install')}\n \n
\n
\n {!canRenderStickers && }\n {canRenderStickers && displayedStickers.map((sticker) => (\n \n ))}\n
\n {canRenderStickers && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { stickerSetId }): StateProps => {\n return {\n set: selectStickerSet(global, stickerSetId),\n shouldPlay: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadStickers', 'toggleStickerSet']),\n)(StickerSetResult));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport { throttle } from '../../util/schedulers';\nimport { selectCurrentStickerSearch } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\nimport StickerSetResult from './StickerSetResult';\n\nimport './StickerSearch.scss';\n\ntype StateProps = {\n query?: string;\n featuredIds?: string[];\n resultIds?: string[];\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst StickerSearch: FC = ({\n query,\n featuredIds,\n resultIds,\n loadFeaturedStickers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const lang = useLang();\n\n const [isModalOpen, setIsModalOpen] = useState(false);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE });\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadFeaturedStickers();\n });\n });\n\n function renderContent() {\n if (query === undefined) {\n return undefined;\n }\n\n if (!query && featuredIds) {\n return featuredIds.map((id) => (\n \n ));\n }\n\n if (resultIds) {\n if (!resultIds.length) {\n return

Nothing found.

;\n }\n\n return resultIds.map((id) => (\n \n ));\n }\n\n return ;\n }\n\n return (\n
\n {renderContent()}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentSearch = selectCurrentStickerSearch(global);\n const { query, resultIds } = currentSearch || {};\n const { featured } = global.stickers;\n\n return {\n query,\n featuredIds: featured.setIds,\n resultIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFeaturedStickers']),\n)(StickerSearch));\n","import React, {\n FC, memo, useRef, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiVideo } from '../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n selectCurrentGifSearch,\n selectChat,\n selectIsChatWithBot,\n selectCurrentMessageList,\n} from '../../modules/selectors';\nimport { getAllowedAttachmentOptions } from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport GifButton from '../common/GifButton';\nimport Loading from '../ui/Loading';\n\nimport './GifSearch.scss';\n\ntype StateProps = {\n query?: string;\n results?: ApiVideo[];\n chat?: ApiChat;\n isChatWithBot?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst PRELOAD_BACKWARDS = 96; // GIF Search bot results are multiplied by 24\nconst INTERSECTION_DEBOUNCE = 300;\n\nconst GifSearch: FC = ({\n query,\n results,\n chat,\n isChatWithBot,\n searchMoreGifs,\n sendMessage,\n setGifSearchQuery,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE });\n\n const { canSendGifs } = getAllowedAttachmentOptions(chat, isChatWithBot);\n\n const handleGifClick = useCallback((gif: ApiVideo) => {\n if (canSendGifs) {\n sendMessage({ gif });\n }\n\n if (IS_TOUCH_ENV) {\n setGifSearchQuery({ query: undefined });\n }\n }, [canSendGifs, sendMessage, setGifSearchQuery]);\n\n const lang = useLang();\n\n function renderContent() {\n if (query === undefined) {\n return undefined;\n }\n\n if (!results) {\n return (\n \n );\n }\n\n if (!results.length) {\n return (\n

{lang('NoGIFsFound')}

\n );\n }\n\n return results.map((gif) => (\n \n ));\n }\n\n const hasResults = Boolean(query !== undefined && results && results.length);\n\n return (\n
\n \n {renderContent()}\n \n\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentSearch = selectCurrentGifSearch(global);\n const { query, results } = currentSearch || {};\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n\n return {\n query,\n results,\n chat,\n isChatWithBot,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['searchMoreGifs', 'sendMessage', 'setGifSearchQuery']),\n)(GifSearch));\n","import React, {\n FC, useCallback, useState, memo, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiChat,\n ApiMessage,\n ApiPollAnswer,\n ApiPollResult,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport { pick } from '../../util/iteratees';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport ShowMoreButton from '../ui/ShowMoreButton';\nimport Loading from '../ui/Loading';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\n\nimport './PollAnswerResults.scss';\n\ntype OwnProps = {\n chat: ApiChat;\n message: ApiMessage;\n answer: ApiPollAnswer;\n answerVote: ApiPollResult;\n totalVoters: number;\n};\n\ntype StateProps = {\n voters?: number[];\n offset: string;\n};\n\ntype DispatchProps = Pick;\n\nconst INITIAL_LIMIT = 4;\nconst VIEW_MORE_LIMIT = 50;\n\nconst PollAnswerResults: FC = ({\n chat,\n message,\n answer,\n answerVote,\n totalVoters,\n voters,\n offset,\n loadPollOptionResults,\n openChat,\n closePollResults,\n}) => {\n const prevVotersCount = usePrevious(answerVote.votersCount);\n const [isLoading, setIsLoading] = useState(true);\n const areVotersLoaded = Boolean(voters);\n const { option, text } = answer;\n const lang = useLang();\n\n useEffect(() => {\n // For update when new votes arrive or when the user takes back his vote\n if (!areVotersLoaded || prevVotersCount !== answerVote.votersCount) {\n loadPollOptionResults({\n chat, messageId: message.id, option, offset, limit: INITIAL_LIMIT, shouldResetVoters: true,\n });\n }\n // eslint-disable-next-line\n }, [answerVote.votersCount, areVotersLoaded]);\n\n const handleViewMoreClick = useCallback(() => {\n setIsLoading(true);\n loadPollOptionResults({\n chat, messageId: message.id, option, offset, limit: VIEW_MORE_LIMIT,\n });\n }, [chat, loadPollOptionResults, message.id, offset, option]);\n\n useEffect(() => {\n setIsLoading(false);\n }, [voters]);\n\n const handleMemberClick = useCallback((id: number) => {\n openChat({ id });\n closePollResults();\n }, [closePollResults, openChat]);\n\n function renderViewMoreButton() {\n const leftVotersCount = answerVote.votersCount - voters!.length;\n\n return answerVote.votersCount > INITIAL_LIMIT && leftVotersCount > 0 && (\n \n );\n }\n\n return (\n
\n
\n {voters\n ? voters.map((id) => (\n handleMemberClick(id)}\n >\n \n \n ))\n : }\n {voters && renderViewMoreButton()}\n
\n
\n {text}\n \n {getPercentage(answerVote.votersCount, totalVoters)}%\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 memo(withGlobal(\n (global, { answer }: OwnProps): StateProps => {\n const { voters, offsets } = global.pollResults;\n\n return {\n voters: voters && voters[answer.option],\n offset: (offsets && offsets[answer.option]) || '',\n };\n },\n (global, actions): DispatchProps => pick(actions, ['loadPollOptionResults', 'openChat', 'closePollResults']),\n)(PollAnswerResults));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiChat } from '../../api/types';\nimport { selectChat, selectChatMessage } from '../../modules/selectors';\nimport { buildCollectionByKey } from '../../util/iteratees';\nimport { getMessagePoll } from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\n\nimport PollAnswerResults from './PollAnswerResults';\nimport Loading from '../ui/Loading';\n\nimport './PollResults.scss';\n\ntype StateProps = {\n chat?: ApiChat;\n message?: ApiMessage;\n lastSyncTime?: number;\n};\n\nconst PollResults: FC = ({\n chat,\n message,\n lastSyncTime,\n}) => {\n const lang = useLang();\n if (!message || !chat) {\n return ;\n }\n\n const { summary, results } = getMessagePoll(message)!;\n if (!results.results) {\n return undefined;\n }\n\n const resultsByOption = buildCollectionByKey(results.results, 'option');\n\n return (\n
\n

{summary.question}

\n
\n {lastSyncTime && summary.answers.map((answer) => (\n \n ))}\n {!lastSyncTime && }\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n pollResults: { chatId, messageId },\n lastSyncTime,\n } = global;\n\n if (!chatId || !messageId) {\n return {};\n }\n\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n chat,\n message,\n lastSyncTime,\n };\n },\n)(PollResults));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat, selectUser } from '../../../modules/selectors';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\nimport './Management.scss';\n\ntype OwnProps = {\n userId: number;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat: ApiChat;\n progress?: ManagementProgress;\n};\n\ntype DispatchProps = Pick;\n\nconst ERROR_FIRST_NAME_MISSING = 'Please provide first name';\n\nconst ManageUser: FC = ({\n userId,\n user,\n chat,\n progress,\n updateContact,\n deleteUser,\n deleteHistory,\n closeManagement,\n openChat,\n}) => {\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [error, setError] = useState();\n const lang = useLang();\n\n const currentFirstName = user ? (user.firstName || '') : '';\n const currentLastName = user ? (user.lastName || '') : '';\n const currentIsMuted = chat ? chat.isMuted : undefined;\n\n const [firstName, setFirstName] = useState(currentFirstName);\n const [lastName, setLastName] = useState(currentLastName);\n const [isNotificationsEnabled, setIsNotificationsEnabled] = useState(!currentIsMuted);\n\n useEffect(() => {\n setIsNotificationsEnabled(!currentIsMuted);\n }, [currentIsMuted]);\n\n useEffect(() => {\n setIsProfileFieldsTouched(false);\n closeDeleteDialog();\n }, [closeDeleteDialog, userId]);\n\n useEffect(() => {\n setFirstName(currentFirstName);\n setLastName(currentLastName);\n }, [currentFirstName, currentLastName, user]);\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n closeDeleteDialog();\n }\n }, [closeDeleteDialog, progress]);\n\n const handleFirstNameChange = useCallback((e: ChangeEvent) => {\n setFirstName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleLastNameChange = useCallback((e: ChangeEvent) => {\n setLastName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleNotificationChange = useCallback((e: ChangeEvent) => {\n setIsNotificationsEnabled(e.target.checked);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleProfileSave = useCallback(() => {\n const trimmedFirstName = firstName.trim();\n const trimmedLastName = lastName.trim();\n\n if (!trimmedFirstName.length) {\n setError(ERROR_FIRST_NAME_MISSING);\n }\n\n updateContact({\n userId,\n isMuted: !isNotificationsEnabled,\n firstName: trimmedFirstName,\n lastName: trimmedLastName,\n });\n }, [firstName, lastName, updateContact, userId, isNotificationsEnabled]);\n\n const handleDeleteContact = useCallback(() => {\n deleteHistory({\n chatId: chat.id,\n shouldDeleteForAll: false,\n });\n deleteUser({ userId });\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [chat.id, closeDeleteDialog, closeManagement, deleteHistory, deleteUser, openChat, userId]);\n\n if (!user) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n \n \n \n
\n \n
\n
\n
\n \n {lang('DeleteContact')}\n \n
\n
\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId }): StateProps => {\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId)!;\n const { progress } = global.management;\n\n return {\n user, chat, progress,\n };\n },\n (global, actions): DispatchProps => pick(actions, [\n 'updateContact', 'deleteUser', 'closeManagement', 'openChat', 'deleteHistory',\n ]),\n)(ManageUser));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens, ManagementProgress } from '../../../types';\nimport { ApiChat, ApiChatBannedRights, ApiMediaFormat } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { getChatAvatarHash, getHasAdminRight, isChatBasicGroup } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport { selectChat } from '../../../modules/selectors';\nimport { formatInteger } from '../../../util/textFormat';\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\nimport './Management.scss';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n progress?: ManagementProgress;\n isBasicGroup: boolean;\n hasLinkedChannel: boolean;\n canChangeInfo?: boolean;\n canBanUsers?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst GROUP_TITLE_EMPTY = 'Group title can\\'t be empty';\n\n// Some checkboxes control multiple rights, and some rights are not controlled from Permissions screen,\n// so we need to define the amount manually\nconst TOTAL_PERMISSIONS_COUNT = 8;\n\nconst ManageGroup: FC = ({\n chatId,\n chat,\n progress,\n isBasicGroup,\n hasLinkedChannel,\n canChangeInfo,\n canBanUsers,\n onScreenSelect,\n togglePreHistoryHidden,\n updateChat,\n deleteHistory,\n leaveChannel,\n deleteChannel,\n closeManagement,\n openChat,\n}) => {\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const currentTitle = chat.title;\n const currentAbout = chat.fullInfo ? (chat.fullInfo.about || '') : '';\n\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [title, setTitle] = useState(currentTitle);\n const [about, setAbout] = useState(currentAbout);\n const [photo, setPhoto] = useState();\n const [error, setError] = useState();\n const imageHash = getChatAvatarHash(chat);\n const currentAvatarBlobUrl = useMedia(imageHash, false, ApiMediaFormat.BlobUrl);\n const lang = useLang();\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const handleClickEditType = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatPrivacyType);\n }, [onScreenSelect]);\n\n const handleClickDiscussion = useCallback(() => {\n onScreenSelect(ManagementScreens.Discussion);\n }, [onScreenSelect]);\n\n const handleClickPermissions = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupPermissions);\n }, [onScreenSelect]);\n\n const handleClickAdministrators = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }, [onScreenSelect]);\n\n const handleSetPhoto = useCallback((file: File) => {\n setPhoto(file);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleTitleChange = useCallback((e: ChangeEvent) => {\n setTitle(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleAboutChange = useCallback((e: ChangeEvent) => {\n setAbout(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUpdateGroup = useCallback(() => {\n const trimmedTitle = title.trim();\n const trimmedAbout = about.trim();\n\n if (!trimmedTitle.length) {\n setError(GROUP_TITLE_EMPTY);\n return;\n }\n\n updateChat({\n chatId,\n title: trimmedTitle,\n about: trimmedAbout,\n photo,\n });\n }, [about, chatId, photo, title, updateChat]);\n\n const handleClickMembers = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupMembers);\n }, [onScreenSelect]);\n\n const handleTogglePreHistory = useCallback(() => {\n if (!chat.fullInfo) {\n return;\n }\n\n const { isPreHistoryHidden } = chat.fullInfo;\n\n togglePreHistoryHidden({ chatId: chat.id, isEnabled: !isPreHistoryHidden });\n }, [chat, togglePreHistoryHidden]);\n\n const enabledPermissionsCount = useMemo(() => {\n if (!chat.defaultBannedRights) {\n return 0;\n }\n\n let totalCount = [\n 'sendMessages',\n 'sendMedia',\n 'embedLinks',\n 'sendPolls',\n 'changeInfo',\n 'inviteUsers',\n 'pinMessages',\n ].filter(\n (key) => !chat.defaultBannedRights![key as keyof ApiChatBannedRights],\n ).length;\n\n const { sendStickers, sendGifs } = chat.defaultBannedRights;\n\n // These two rights are controlled with a single checkbox\n if (!sendStickers && !sendGifs) {\n totalCount += 1;\n }\n\n return totalCount;\n }, [chat]);\n\n const adminsCount = (chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0;\n\n const handleDeleteGroup = useCallback(() => {\n if (isBasicGroup) {\n deleteHistory({ chatId: chat.id, shouldDeleteForAll: false });\n } else if (!chat.isCreator) {\n leaveChannel({ chatId: chat.id });\n } else {\n deleteChannel({ chatId: chat.id });\n }\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [\n isBasicGroup, chat.isCreator, chat.id,\n closeDeleteDialog, closeManagement, deleteHistory, leaveChannel, deleteChannel, openChat,\n ]);\n\n if (chat.isRestricted) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n \n \n \n {chat.isCreator && (\n \n {lang('GroupType')}\n {chat.username ? lang('TypePublic') : lang('TypePrivate')}\n \n )}\n {hasLinkedChannel && (\n \n {lang('LinkedChannel')}\n {lang('DiscussionUnlink')}\n \n )}\n \n {lang('ChannelPermissions')}\n \n {enabledPermissionsCount}/{TOTAL_PERMISSIONS_COUNT}\n \n \n \n {lang('ChannelAdministrators')}\n {formatInteger(adminsCount)}\n \n
\n
\n \n {lang('GroupMembers')}\n {formatInteger(chat.membersCount!)}\n \n\n {chat.fullInfo && (\n
\n \n
\n )}\n
\n
\n \n {lang('DeleteMega')}\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 { progress } = global.management;\n const hasLinkedChannel = Boolean(chat.fullInfo && chat.fullInfo.linkedChatId);\n\n return {\n chat,\n progress,\n isBasicGroup: isChatBasicGroup(chat),\n hasLinkedChannel,\n canChangeInfo: getHasAdminRight(chat, 'changeInfo'),\n canBanUsers: getHasAdminRight(chat, 'banUsers'),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'togglePreHistoryHidden', 'updateChat', 'closeManagement',\n 'deleteHistory', 'leaveChannel', 'deleteChannel', 'openChat',\n ]),\n)(ManageGroup));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens } from '../../../types';\nimport { ApiChat, ApiChatBannedRights, ApiChatMember } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n currentUserId?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FLOATING_BUTTON_ANIMATION_TIMEOUT_MS = 250;\n\nfunction getLangKeyForBannedRightKey(key: string) {\n switch (key) {\n case 'sendMessages':\n return 'UserRestrictionsNoSend';\n case 'sendMedia':\n return 'UserRestrictionsNoSendMedia';\n case 'sendStickers':\n return 'UserRestrictionsNoSendStickers';\n case 'embedLinks':\n return 'UserRestrictionsNoEmbedLinks';\n case 'sendPolls':\n return 'UserRestrictionsNoSendPolls';\n case 'changeInfo':\n return 'UserRestrictionsNoChangeInfo';\n case 'inviteUsers':\n return 'UserRestrictionsInviteUsers';\n case 'pinMessages':\n return 'UserRestrictionsPinMessages';\n default:\n return undefined;\n }\n}\n\nconst ManageGroupPermissions: FC = ({\n onScreenSelect,\n onChatMemberSelect,\n chat,\n currentUserId,\n updateChatDefaultBannedRights,\n}) => {\n const [permissions, setPermissions] = useState({});\n const [havePermissionChanged, setHavePermissionChanged] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const lang = useLang();\n\n const handleRemovedUsersClick = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupRemovedUsers);\n }, [onScreenSelect]);\n\n const handleAddExceptionClick = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupUserPermissionsCreate);\n }, [onScreenSelect]);\n\n const handleExceptionMemberClick = useCallback((member: ApiChatMember) => {\n onChatMemberSelect(member.userId, member.promotedByUserId === currentUserId);\n onScreenSelect(ManagementScreens.GroupUserPermissions);\n }, [currentUserId, onChatMemberSelect, onScreenSelect]);\n\n useEffect(() => {\n setPermissions((chat && chat.defaultBannedRights) || {});\n setHavePermissionChanged(false);\n setTimeout(() => {\n setIsLoading(false);\n }, FLOATING_BUTTON_ANIMATION_TIMEOUT_MS);\n }, [chat]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatBannedRights]),\n ...(name === 'sendStickers' && {\n sendGifs: getUpdatedPermissionValue(p[name]),\n }),\n }));\n setHavePermissionChanged(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!chat) {\n return;\n }\n\n setIsLoading(true);\n updateChatDefaultBannedRights({ chatId: chat.id, bannedRights: permissions });\n }, [chat, permissions, updateChatDefaultBannedRights]);\n\n const removedUsersCount = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.kickedMembers) {\n return 0;\n }\n\n return chat.fullInfo.kickedMembers.length;\n }, [chat]);\n\n const exceptionMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.members) {\n return [];\n }\n\n return chat.fullInfo.members.filter(({ bannedRights }) => !!bannedRights);\n }, [chat]);\n\n const getMemberExceptions = useCallback((member: ApiChatMember) => {\n const { bannedRights } = member;\n if (!bannedRights || !chat) {\n return undefined;\n }\n\n const { defaultBannedRights } = chat;\n\n return Object.keys(bannedRights).reduce((result, key) => {\n if (\n !bannedRights[key as keyof ApiChatBannedRights]\n || (defaultBannedRights && defaultBannedRights[key as keyof ApiChatBannedRights])\n || key === 'sendInline' || key === 'viewMessages' || key === 'sendGames'\n ) {\n return result;\n }\n\n const langKey = getLangKeyForBannedRightKey(key);\n\n if (!langKey) {\n return result;\n }\n\n const translatedString = lang(langKey);\n\n return `${result}${!result.length ? translatedString : `, ${translatedString}`}`;\n }, '');\n }, [chat, lang]);\n\n return (\n
\n
\n
\n

{lang('ChannelPermissionsHeader')}

\n\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n
\n \n {lang('ChannelBlockedUsers')}\n {removedUsersCount}\n \n
\n\n
\n

{lang('PrivacyExceptions')}

\n\n \n {lang('ChannelAddException')}\n \n\n {exceptionMembers.map((member) => (\n handleExceptionMemberClick(member)}\n >\n \n \n ))}\n
\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n return { chat, currentUserId: global.currentUserId };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatDefaultBannedRights']),\n)(ManageGroupPermissions));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatMember, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { selectChat } from '../../../modules/selectors';\nimport { getUserFullName } from '../../../modules/helpers';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n usersById: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageGroupRemovedUsers: FC = ({\n chat,\n usersById,\n updateChatMemberBannedRights,\n}) => {\n const lang = useLang();\n\n const removedMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.kickedMembers) {\n return [];\n }\n\n return chat.fullInfo.kickedMembers;\n }, [chat]);\n\n const getRemovedBy = useCallback((member: ApiChatMember) => {\n if (!member.kickedByUserId) {\n return undefined;\n }\n\n const kickedByUser = usersById[member.kickedByUserId];\n if (!kickedByUser) {\n return undefined;\n }\n\n return lang('UserRemovedBy', getUserFullName(kickedByUser));\n }, [lang, usersById]);\n\n const getContextActions = useCallback((member: ApiChatMember) => {\n if (!chat) {\n return undefined;\n }\n\n return [{\n title: lang('Unblock'),\n icon: 'delete',\n destructive: true,\n handler: () => updateChatMemberBannedRights({\n chatId: chat.id,\n userId: member.userId,\n bannedRights: {},\n }),\n }];\n }, [lang, chat, updateChatMemberBannedRights]);\n\n return (\n
\n
\n
\n

{lang('NoBlockedGroup2')}

\n\n {removedMembers.map((member) => (\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 { byId: usersById } = global.users;\n\n return { chat, usersById };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatMemberBannedRights']),\n)(ManageGroupRemovedUsers));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ManagementScreens, ManagementProgress } from '../../../types';\nimport { ApiChat, ApiMediaFormat } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { getChatAvatarHash, getHasAdminRight } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './Management.scss';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n progress?: ManagementProgress;\n isSignaturesShown: boolean;\n canChangeInfo?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst CHANNEL_TITLE_EMPTY = 'Channel title can\\'t be empty';\n\nconst ManageChannel: FC = ({\n chatId,\n chat,\n progress,\n isSignaturesShown,\n canChangeInfo,\n onScreenSelect,\n updateChat,\n toggleSignatures,\n closeManagement,\n leaveChannel,\n deleteChannel,\n openChat,\n}) => {\n const currentTitle = chat ? (chat.title || '') : '';\n const currentAbout = chat && chat.fullInfo ? (chat.fullInfo.about || '') : '';\n const hasLinkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId;\n\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [title, setTitle] = useState(currentTitle);\n const [about, setAbout] = useState(currentAbout);\n const [photo, setPhoto] = useState();\n const [error, setError] = useState();\n const imageHash = chat && getChatAvatarHash(chat);\n const currentAvatarBlobUrl = useMedia(imageHash, false, ApiMediaFormat.BlobUrl);\n const lang = useLang();\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const adminsCount = (chat && chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0;\n\n const handleClickEditType = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatPrivacyType);\n }, [onScreenSelect]);\n\n const handleClickDiscussion = useCallback(() => {\n onScreenSelect(ManagementScreens.Discussion);\n }, [onScreenSelect]);\n\n const handleClickAdministrators = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }, [onScreenSelect]);\n\n const handleSetPhoto = useCallback((file: File) => {\n setPhoto(file);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleTitleChange = useCallback((e: ChangeEvent) => {\n setTitle(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleAboutChange = useCallback((e: ChangeEvent) => {\n setAbout(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUpdateChannel = useCallback(() => {\n const trimmedTitle = title.trim();\n const trimmedAbout = about.trim();\n\n if (!trimmedTitle.length) {\n setError(CHANNEL_TITLE_EMPTY);\n return;\n }\n\n updateChat({\n chatId,\n title: trimmedTitle,\n about: trimmedAbout,\n photo,\n });\n }, [about, chatId, photo, title, updateChat]);\n\n const handleToggleSignatures = useCallback(() => {\n toggleSignatures({ chatId, isEnabled: !isSignaturesShown });\n }, [chatId, isSignaturesShown, toggleSignatures]);\n\n const handleClickSubscribers = useCallback(() => {\n onScreenSelect(ManagementScreens.ChannelSubscribers);\n }, [onScreenSelect]);\n\n\n const handleDeleteChannel = useCallback(() => {\n if (chat.isCreator) {\n deleteChannel({ chatId: chat.id });\n } else {\n leaveChannel({ chatId: chat.id });\n }\n\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [chat.isCreator, chat.id, closeDeleteDialog, closeManagement, leaveChannel, deleteChannel, openChat]);\n\n if (chat.isRestricted) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n \n \n \n {chat.isCreator && (\n \n {lang('ChannelType')}\n {chat.username ? lang('TypePublic') : lang('TypePrivate')}\n \n )}\n \n {lang('Discussion')}\n {hasLinkedChat ? lang('DiscussionUnlink') : lang('Add')}\n \n \n {lang('ChannelAdministrators')}\n {adminsCount}\n \n
\n \n
\n
\n
\n \n {lang('ChannelSubscribers')}\n {lang('Subscribers', chat.membersCount!, 'i')}\n \n
\n
\n \n {chat.isCreator ? lang('ChannelDelete') : lang('LeaveChannel')}\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 { progress } = global.management;\n const isSignaturesShown = Boolean(chat && chat.isSignaturesShown);\n\n return {\n chat,\n progress,\n isSignaturesShown,\n canChangeInfo: getHasAdminRight(chat, 'changeInfo'),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSignatures', 'updateChat', 'closeManagement', 'leaveChannel', 'deleteChannel', 'openChat',\n ]),\n)(ManageChannel));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { selectChat, selectManagement } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport { isChatChannel } from '../../../modules/helpers';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport SafeLink from '../../common/SafeLink';\nimport ListItem from '../../ui/ListItem';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Loading from '../../ui/Loading';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport UsernameInput from '../../common/UsernameInput';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype PrivacyType = 'private' | 'public';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat: ApiChat;\n isChannel: boolean;\n progress?: ManagementProgress;\n isUsernameAvailable?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageChatPrivacyType: FC = ({\n chat,\n isChannel,\n progress,\n isUsernameAvailable,\n checkPublicLink,\n updatePublicLink,\n updatePrivateLink,\n}) => {\n const isPublic = Boolean(chat.username);\n const privateLink = chat.fullInfo && chat.fullInfo.inviteLink;\n\n const [privacyType, setPrivacyType] = useState(isPublic ? 'public' : 'private');\n const [username, setUsername] = useState();\n const [isRevokeConfirmDialogOpen, openRevokeConfirmDialog, closeRevokeConfirmDialog] = useFlag();\n\n const canUpdate = (\n (privacyType === 'public' && username && isUsernameAvailable)\n || (privacyType === 'private' && isPublic)\n );\n\n useEffect(() => {\n if (privacyType && !privateLink) {\n updatePrivateLink();\n }\n }, [privacyType, privateLink, updatePrivateLink]);\n\n const handleOptionChange = useCallback((value: string) => {\n setPrivacyType(value as PrivacyType);\n }, []);\n\n const handleSave = useCallback(() => {\n updatePublicLink({ username: privacyType === 'public' ? username : '' });\n }, [privacyType, updatePublicLink, username]);\n\n const handleRevokePrivateLink = useCallback(() => {\n closeRevokeConfirmDialog();\n updatePrivateLink();\n }, [closeRevokeConfirmDialog, updatePrivateLink]);\n\n const lang = useLang();\n const langPrefix1 = isChannel ? 'Channel' : 'Mega';\n const langPrefix2 = isChannel ? 'Channel' : 'Group';\n\n const options = [\n { value: 'private', label: lang(`${langPrefix1}Private`), subLabel: lang(`${langPrefix1}PrivateInfo`) },\n { value: 'public', label: lang(`${langPrefix1}Public`), subLabel: lang(`${langPrefix1}PublicInfo`) },\n ];\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n

{lang(`${langPrefix2}Type`)}

\n \n
\n {privacyType === 'private' ? (\n
\n {privateLink ? (\n <>\n \n

\n {lang(`${langPrefix1}PrivateLinkHelp`)}\n

\n\n \n {lang('RevokeLink')}\n \n \n \n ) : (\n \n )}\n
\n ) : (\n
\n \n

\n {lang(`${langPrefix2}.Username.CreatePublicLinkHelp`)}\n

\n
\n )}\n
\n \n {isLoading ? (\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 { isUsernameAvailable } = selectManagement(global, chatId)!;\n\n return {\n chat,\n isChannel: isChatChannel(chat),\n progress: global.management.progress,\n isUsernameAvailable,\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'checkPublicLink', 'updatePublicLink', 'updatePrivateLink',\n ]),\n)(ManageChatPrivacyType));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\n\nimport { STICKER_SIZE_DISCUSSION_GROUPS } from '../../../config';\nimport { selectChat } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport getAnimationData from '../../common/helpers/animatedAssets';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport NothingFound from '../../common/NothingFound';\nimport GroupChatInfo from '../../common/GroupChatInfo';\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport useFlag from '../../../hooks/useFlag';\nimport renderText from '../../common/helpers/renderText';\nimport Avatar from '../../common/Avatar';\nimport { isChatChannel } from '../../../modules/helpers';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n chatsByIds: Record;\n linkedChat?: ApiChat;\n forDiscussionIds?: number[];\n isChannel?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageDiscussion: FC = ({\n chat,\n chatId,\n chatsByIds,\n linkedChat,\n forDiscussionIds,\n isChannel,\n onScreenSelect,\n loadGroupsForDiscussion,\n linkDiscussionGroup,\n unlinkDiscussionGroup,\n}) => {\n const [linkedGroupId, setLinkedGroupId] = useState();\n const [animationData, setAnimationData] = useState>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n const [isConfirmUnlinkGroupDialogOpen, openConfirmUnlinkGroupDialog, closeConfirmUnlinkGroupDialog] = useFlag();\n const [isConfirmLinkGroupDialogOpen, openConfirmLinkGroupDialog, closeConfirmLinkGroupDialog] = useFlag();\n const lang = useLang();\n const linkedChatId = linkedChat && linkedChat.id;\n\n useEffect(() => {\n loadGroupsForDiscussion();\n }, [loadGroupsForDiscussion]);\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('DiscussionGroups').then(setAnimationData);\n }\n }, [animationData]);\n\n const handleUnlinkGroupSessions = useCallback(() => {\n closeConfirmUnlinkGroupDialog();\n unlinkDiscussionGroup({ channelId: isChannel ? chatId : linkedChatId });\n if (!isChannel) {\n onScreenSelect(ManagementScreens.Initial);\n }\n }, [closeConfirmUnlinkGroupDialog, unlinkDiscussionGroup, isChannel, chatId, linkedChatId, onScreenSelect]);\n\n const handleLinkGroupSessions = useCallback(() => {\n closeConfirmLinkGroupDialog();\n linkDiscussionGroup({ channelId: chatId, chatId: linkedGroupId });\n }, [closeConfirmLinkGroupDialog, linkDiscussionGroup, chatId, linkedGroupId]);\n\n const onDiscussionClick = (groupId: number) => {\n setLinkedGroupId(groupId);\n openConfirmLinkGroupDialog();\n };\n\n function renderUnlinkGroupHeader() {\n return (\n
\n \n
\n {lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n
\n
\n );\n }\n function renderLinkGroupHeader() {\n const linkedGroup = chatsByIds[linkedGroupId];\n\n if (!linkedGroup) {\n return undefined;\n }\n\n return (\n
\n \n
\n {lang('Channel.DiscussionGroup.LinkGroup')}\n
\n
\n );\n }\n\n function renderLinkGroupConfirmText() {\n const linkedGroup = chatsByIds[linkedGroupId];\n\n if (!linkedGroup) {\n return undefined;\n }\n\n if (linkedGroup.hasPrivateLink) {\n return renderText(\n `Do you want to make **${linkedGroup.title}** the discussion board for **${chat!.title}**?`,\n ['br', 'simple_markdown'],\n );\n // return renderText(\n // lang('DiscussionLinkGroupPublicAlert', linkedChat.title, chat!.title),\n // ['br', 'simple_markdown'],\n // );\n }\n\n return renderText(\n // eslint-disable-next-line max-len\n `Do you want to make **${linkedGroup.title}** the discussion board for **${chat!.title}**?\\n\\nAnyone from the channel will be able to see messages in this group.`,\n ['br', 'simple_markdown'],\n );\n // return renderText(\n // lang('DiscussionLinkGroupPrivateAlert', linkedChat.title, chat!.title),\n // ['br', 'simple_markdown'],\n // );\n }\n\n function renderLinkedGroup() {\n return (\n
\n \n \n \n \n {lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n \n \n
\n );\n }\n\n function renderDiscussionGroups() {\n return (\n
\n

{lang('DiscussionChannelHelp')}

\n\n
\n \n {lang('DiscussionCreateGroup')}\n \n {forDiscussionIds ? (\n forDiscussionIds.map((id, i) => (\n { onDiscussionClick(id); }}\n >\n \n \n ))\n ) : (\n \n )}\n
\n

{lang('DiscussionChannelHelp2')}

\n \n
\n );\n }\n\n return (\n
\n
\n
\n
\n {animationData && (\n \n )}\n
\n {linkedChat && renderLinkedGroup()}\n {!linkedChat && renderDiscussionGroups()}\n
\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { forDiscussionIds, byId: chatsByIds } = global.chats;\n const linkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId\n ? selectChat(global, chat.fullInfo.linkedChatId)\n : undefined;\n\n return {\n chat,\n chatsByIds,\n forDiscussionIds,\n linkedChat,\n isChannel: chat && isChatChannel(chat),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadGroupsForDiscussion', 'linkDiscussionGroup', 'unlinkDiscussionGroup',\n ]),\n)(ManageDiscussion));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatBannedRights } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype OwnProps = {\n chatId: number;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isFormFullyDisabled?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageGroupUserPermissions: FC = ({\n chat,\n selectedChatMemberId,\n onScreenSelect,\n updateChatMemberBannedRights,\n isFormFullyDisabled,\n}) => {\n const [permissions, setPermissions] = useState({});\n const [havePermissionChanged, setHavePermissionChanged] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [isBanConfirmationDialogOpen, openBanConfirmationDialog, closeBanConfirmationDialog] = useFlag();\n const lang = useLang();\n\n const selectedChatMember = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.members) {\n return undefined;\n }\n\n return chat.fullInfo.members.find(({ userId }) => userId === selectedChatMemberId);\n }, [chat, selectedChatMemberId]);\n\n useEffect(() => {\n if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) {\n onScreenSelect(ManagementScreens.GroupPermissions);\n }\n }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]);\n\n useEffect(() => {\n setPermissions((selectedChatMember && selectedChatMember.bannedRights) || (chat && chat.defaultBannedRights) || {});\n setHavePermissionChanged(false);\n setIsLoading(false);\n }, [chat, selectedChatMember]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatBannedRights]),\n ...(name === 'sendStickers' && {\n sendGifs: getUpdatedPermissionValue(p[name]),\n }),\n }));\n setHavePermissionChanged(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!chat || !selectedChatMemberId) {\n return;\n }\n\n setIsLoading(true);\n updateChatMemberBannedRights({\n chatId: chat.id,\n userId: selectedChatMemberId,\n bannedRights: permissions,\n });\n }, [chat, selectedChatMemberId, permissions, updateChatMemberBannedRights]);\n\n const handleBanFromGroup = useCallback(() => {\n if (!chat || !selectedChatMemberId) {\n return;\n }\n\n updateChatMemberBannedRights({\n chatId: chat.id,\n userId: selectedChatMemberId,\n bannedRights: {\n viewMessages: true,\n },\n });\n }, [chat, selectedChatMemberId, updateChatMemberBannedRights]);\n\n const getControlIsDisabled = useCallback((key: keyof ApiChatBannedRights) => {\n if (isFormFullyDisabled) {\n return true;\n }\n\n if (!chat || !chat.defaultBannedRights) {\n return false;\n }\n\n return chat.defaultBannedRights[key];\n }, [chat, isFormFullyDisabled]);\n\n if (!selectedChatMember) {\n return undefined;\n }\n\n return (\n
\n
\n
\n \n \n \n\n

{lang('UserRestrictionsCanDo')}

\n\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n {!isFormFullyDisabled && (\n
\n \n {lang('UserRestrictionsBlock')}\n \n
\n )}\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n\n \n
\n );\n};\n\n\nexport default memo(withGlobal(\n (global, { chatId, isPromotedByCurrentUser }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const isFormFullyDisabled = !(chat.isCreator || isPromotedByCurrentUser);\n\n return { chat, isFormFullyDisabled };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatMemberBannedRights']),\n)(ManageGroupUserPermissions));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens } from '../../../types';\nimport { ApiChat, ApiChatMember, ApiUser } from '../../../api/types';\nimport { getUserFullName, isChatChannel } from '../../../modules/helpers';\n\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n currentUserId?: number;\n isChannel: boolean;\n usersById: Record;\n};\n\nconst ManageChatAdministrators: FC = ({\n chat,\n isChannel,\n currentUserId,\n usersById,\n onScreenSelect,\n onChatMemberSelect,\n}) => {\n const lang = useLang();\n\n function handleRecentActionsClick() {\n onScreenSelect(ManagementScreens.GroupRecentActions);\n }\n\n const adminMembers = useMemo(() => {\n if (!chat.fullInfo || !chat.fullInfo.adminMembers) {\n return [];\n }\n\n return chat.fullInfo.adminMembers.sort((a, b) => {\n if (a.isOwner) {\n return -1;\n } else if (b.isOwner) {\n return 1;\n }\n\n return 0;\n });\n }, [chat]);\n\n const handleAdminMemberClick = useCallback((member: ApiChatMember) => {\n onChatMemberSelect(member.userId, member.promotedByUserId === currentUserId);\n onScreenSelect(ManagementScreens.ChatAdminRights);\n }, [currentUserId, onChatMemberSelect, onScreenSelect]);\n\n const getMemberStatus = useCallback((member: ApiChatMember) => {\n if (member.isOwner) {\n return lang('ChannelCreator');\n }\n\n const promotedByUser = member.promotedByUserId ? usersById[member.promotedByUserId] : undefined;\n\n if (promotedByUser) {\n return lang('EditAdminPromotedBy', getUserFullName(promotedByUser));\n }\n\n return lang('ChannelAdmin');\n }, [lang, usersById]);\n\n return (\n
\n
\n
\n \n {lang('EventLog')}\n {lang(isChannel ? 'EventLogInfoDetailChannel' : 'EventLogInfoDetail')}\n \n
\n\n
\n

\n {isChannel\n ? 'You can add administrators to help you manage your channel.'\n : 'You can add administrators to help you manage your group.'}\n

\n\n {adminMembers.map((member) => (\n handleAdminMemberClick(member)}\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 { byId: usersById } = global.users;\n\n return {\n chat,\n currentUserId: global.currentUserId,\n isChannel: isChatChannel(chat),\n usersById,\n };\n },\n // (setGlobal, actions): DispatchProps => pick(actions, ['togglePreHistoryHidden', 'updateChat']),\n)(ManageChatAdministrators));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatMember } from '../../../api/types';\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n};\n\nconst ManageGroupRecentActions: FC = ({ chat }) => {\n const lang = useLang();\n\n const adminMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.adminMembers) {\n return [];\n }\n\n return chat.fullInfo.adminMembers.sort((a, b) => {\n if (a.isOwner) {\n return -1;\n } else if (b.isOwner) {\n return 1;\n }\n\n return 0;\n });\n }, [chat]);\n\n const getMemberStatus = useCallback((member: ApiChatMember) => {\n if (member.isOwner) {\n return lang('ChannelCreator');\n }\n\n return lang('ChannelAdmin');\n }, [lang]);\n\n return (\n
\n
\n
\n

Actions

\n\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n
\n

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

\n\n
\n \n
\n\n {adminMembers.map((member) => (\n \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\n return { chat };\n },\n)(ManageGroupRecentActions));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatAdminRights, ApiUser } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat } from '../../../modules/selectors';\nimport { getUserFullName, isChatBasicGroup, isChatChannel } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport InputText from '../../ui/InputText';\n\ntype OwnProps = {\n chatId: number;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n usersById: Record;\n currentUserId?: number;\n isChannel: boolean;\n isFormFullyDisabled: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst CUSTOM_TITLE_MAX_LENGTH = 16;\n\nconst ManageGroupAdminRights: FC = ({\n selectedChatMemberId,\n onScreenSelect,\n chat,\n usersById,\n currentUserId,\n isChannel,\n isFormFullyDisabled,\n updateChatAdmin,\n}) => {\n const [permissions, setPermissions] = useState({});\n const [isTouched, setIsTouched] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [isDismissConfirmationDialogOpen, openDismissConfirmationDialog, closeDismissConfirmationDialog] = useFlag();\n const [customTitle, setCustomTitle] = useState('');\n const lang = useLang();\n\n const selectedChatMember = useMemo(() => {\n if (!chat.fullInfo || !chat.fullInfo.adminMembers) {\n return undefined;\n }\n\n return chat.fullInfo.adminMembers.find(({ userId }) => userId === selectedChatMemberId);\n }, [chat, selectedChatMemberId]);\n\n useEffect(() => {\n if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }\n }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]);\n\n useEffect(() => {\n setPermissions((selectedChatMember && selectedChatMember.adminRights) || {});\n setCustomTitle(((selectedChatMember && selectedChatMember.customTitle) || '').substr(0, CUSTOM_TITLE_MAX_LENGTH));\n setIsTouched(false);\n setIsLoading(false);\n }, [selectedChatMember]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatAdminRights]),\n }));\n setIsTouched(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!selectedChatMemberId) {\n return;\n }\n\n setIsLoading(true);\n updateChatAdmin({\n chatId: chat.id,\n userId: selectedChatMemberId,\n adminRights: permissions,\n customTitle,\n });\n }, [chat, selectedChatMemberId, permissions, customTitle, updateChatAdmin]);\n\n const handleDismissAdmin = useCallback(() => {\n if (!selectedChatMemberId) {\n return;\n }\n\n updateChatAdmin({\n chatId: chat.id,\n userId: selectedChatMemberId,\n adminRights: {},\n });\n closeDismissConfirmationDialog();\n }, [chat.id, closeDismissConfirmationDialog, selectedChatMemberId, updateChatAdmin]);\n\n const getControlIsDisabled = useCallback((key: keyof ApiChatAdminRights) => {\n if (isChatBasicGroup(chat)) {\n return false;\n }\n\n if (isFormFullyDisabled || !chat.adminRights) {\n return true;\n }\n\n return !chat.adminRights![key];\n }, [chat, isFormFullyDisabled]);\n\n const memberStatus = useMemo(() => {\n if (!selectedChatMember) {\n return undefined;\n }\n\n if (selectedChatMember.isOwner) {\n return lang('ChannelCreator');\n }\n\n const promotedByUser = selectedChatMember.promotedByUserId\n ? usersById[selectedChatMember.promotedByUserId]\n : undefined;\n\n if (promotedByUser) {\n return lang('EditAdminPromotedBy', getUserFullName(promotedByUser));\n }\n\n return lang('ChannelAdmin');\n }, [selectedChatMember, usersById, lang]);\n\n const handleCustomTitleChange = useCallback((e) => {\n const { value } = e.target;\n setCustomTitle(value);\n setIsTouched(true);\n }, []);\n\n if (!selectedChatMember) {\n return undefined;\n }\n\n return (\n
\n
\n
\n \n \n \n\n

{lang('EditAdminWhatCanDo')}

\n\n
\n \n
\n {isChannel && (\n
\n \n
\n )}\n {isChannel && (\n
\n \n
\n )}\n
\n \n
\n {!isChannel && (\n
\n \n
\n )}\n
\n \n
\n {!isChannel && (\n
\n \n
\n )}\n
\n \n
\n {!isChannel && (\n
\n \n
\n )}\n\n {isFormFullyDisabled && (\n

\n {lang('Channel.EditAdmin.CannotEdit')}\n

\n )}\n\n {!isChannel && (\n \n )}\n\n {currentUserId !== selectedChatMemberId && !isFormFullyDisabled && (\n \n {lang('EditAdminRemoveAdmin')}\n \n )}\n
\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n\n \n
\n );\n};\n\n\nexport default memo(withGlobal(\n (global, { chatId, isPromotedByCurrentUser }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { byId: usersById } = global.users;\n const { currentUserId } = global;\n const isChannel = isChatChannel(chat);\n const isFormFullyDisabled = !(chat.isCreator || isPromotedByCurrentUser);\n\n return {\n chat,\n usersById,\n currentUserId,\n isChannel,\n isFormFullyDisabled,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatAdmin']),\n)(ManageGroupAdminRights));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { selectChat } from '../../../modules/selectors';\nimport { sortUserIds, isChatChannel } from '../../../modules/helpers';\nimport { pick } from '../../../util/iteratees';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport NothingFound from '../../common/NothingFound';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n usersById: Record;\n members?: ApiChatMember[];\n isChannel?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageGroupMembers: FC = ({\n members,\n usersById,\n isChannel,\n openUserInfo,\n}) => {\n const memberIds = useMemo(() => {\n if (!members || !usersById) {\n return undefined;\n }\n\n return sortUserIds(members.map(({ userId }) => userId), usersById);\n }, [members, usersById]);\n\n const handleMemberClick = useCallback((id: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n return (\n
\n
\n
\n {memberIds ? (\n memberIds.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \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 { byId: usersById } = global.users;\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const isChannel = chat && isChatChannel(chat);\n\n return {\n members,\n usersById,\n isChannel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(ManageGroupMembers));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\n\nimport { selectChat } from '../../../modules/selectors';\nimport { sortUserIds, isChatChannel } from '../../../modules/helpers';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport NothingFound from '../../common/NothingFound';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number) => void;\n};\n\ntype StateProps = {\n usersById: Record;\n members?: ApiChatMember[];\n isChannel?: boolean;\n};\n\nconst ManageGroupUserPermissionsCreate: FC = ({\n usersById,\n members,\n isChannel,\n onScreenSelect,\n onChatMemberSelect,\n}) => {\n const memberIds = useMemo(() => {\n if (!members || !usersById) {\n return undefined;\n }\n\n return sortUserIds(members.filter((member) => !member.isOwner).map(({ userId }) => userId), usersById);\n }, [members, usersById]);\n\n const handleExceptionMemberClick = useCallback((memberId: number) => {\n onChatMemberSelect(memberId);\n onScreenSelect(ManagementScreens.GroupUserPermissions);\n }, [onChatMemberSelect, onScreenSelect]);\n\n return (\n
\n
\n
\n {memberIds ? (\n memberIds.map((id, i) => (\n handleExceptionMemberClick(id)}\n >\n \n \n ))\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 { byId: usersById } = global.users;\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const isChannel = chat && isChatChannel(chat);\n\n return {\n members,\n usersById,\n isChannel,\n };\n },\n)(ManageGroupUserPermissionsCreate));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens, ManagementType } from '../../../types';\n\nimport { selectCurrentManagementType } from '../../../modules/selectors';\n\nimport ManageUser from './ManageUser';\nimport ManageGroup from './ManageGroup';\nimport ManageGroupPermissions from './ManageGroupPermissions';\nimport ManageGroupRemovedUsers from './ManageGroupRemovedUsers';\nimport ManageChannel from './ManageChannel';\nimport ManageChatPrivacyType from './ManageChatPrivacyType';\nimport ManageDiscussion from './ManageDiscussion';\nimport ManageGroupUserPermissions from './ManageGroupUserPermissions';\nimport ManageChatAdministrators from './ManageChatAdministrators';\nimport ManageGroupRecentActions from './ManageGroupRecentActions';\nimport ManageGroupAdminRights from './ManageGroupAdminRights';\nimport ManageGroupMembers from './ManageGroupMembers';\nimport ManageGroupUserPermissionsCreate from './ManageGroupUserPermissionsCreate';\n\nexport type OwnProps = {\n chatId: number;\n currentScreen: ManagementScreens;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n managementType?: ManagementType;\n};\n\nconst Management: FC = ({\n chatId,\n currentScreen,\n selectedChatMemberId,\n isPromotedByCurrentUser,\n onScreenSelect,\n onChatMemberSelect,\n managementType,\n}) => {\n switch (currentScreen) {\n case ManagementScreens.Initial: {\n switch (managementType) {\n case 'user':\n return ;\n case 'group':\n return ;\n case 'channel':\n return ;\n }\n\n break;\n }\n\n case ManagementScreens.ChatPrivacyType:\n return (\n \n );\n\n case ManagementScreens.Discussion:\n return (\n \n );\n\n case ManagementScreens.GroupPermissions:\n return (\n \n );\n\n case ManagementScreens.GroupRemovedUsers:\n return (\n \n );\n\n case ManagementScreens.GroupUserPermissionsCreate:\n return (\n \n );\n\n case ManagementScreens.GroupUserPermissions:\n return (\n \n );\n\n case ManagementScreens.ChatAdministrators:\n return (\n \n );\n\n case ManagementScreens.GroupRecentActions:\n return (\n \n );\n\n case ManagementScreens.ChatAdminRights:\n return (\n \n );\n\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n return (\n \n );\n }\n\n return undefined; // Never reached\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const managementType = selectCurrentManagementType(global);\n\n return {\n managementType,\n };\n },\n)(Management));\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","const VISA = /^4[0-9]{12}(?:[0-9]{1,3})?$/;\nconst MASTERCARD1 = /^5[1-5][0-9]{11,14}$/;\nconst MASTERCARD2 = /^2[2-7][0-9]{11,14}$/;\n\nexport enum CardType {\n Default,\n Visa,\n Mastercard,\n}\n\nconst cards: Record = {\n [CardType.Default]: '',\n [CardType.Visa]: 'visa',\n [CardType.Mastercard]: 'mastercard',\n};\n\nexport function detectCardType(cardNumber: string): number {\n cardNumber = cardNumber.replace(/\\s/g, '');\n if (VISA.test(cardNumber)) {\n return CardType.Visa;\n }\n if (MASTERCARD1.test(cardNumber) || MASTERCARD2.test(cardNumber)) {\n return CardType.Mastercard;\n }\n return CardType.Default;\n}\n\nexport function detectCardTypeText(cardNumber: string): string {\n const cardType = detectCardType(cardNumber);\n return cards[cardType as number] || '';\n}\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\nimport { countryList } from '../../util/phoneNumber';\n\nexport type FormState = {\n streetLine1: string;\n streetLine2: string;\n city: string;\n state: string;\n countryIso2: string;\n postCode: string;\n fullName: string;\n email: string;\n phone: string;\n shipping: string;\n cardNumber: string;\n cardholder: string;\n expiry: string;\n cvv: string;\n billingCountry: string;\n billingZip: string;\n saveInfo: boolean;\n saveCredentials: boolean;\n formErrors: Record;\n};\n\nexport type FormActions = (\n 'changeAddress1' | 'changeAddress2' | 'changeCity' | 'changeState' | 'changeCountry' |\n 'changePostCode' | 'changeFullName' | 'changeEmail' | 'changePhone' | 'changeShipping' | 'updateUserInfo' |\n 'changeCardNumber' | 'changeCardholder' | 'changeExpiryDate' | 'changeCvvCode' | 'changeBillingCountry' |\n 'changeBillingZip' | 'changeSaveInfo' | 'changeSaveCredentials' | 'setFormErrors'\n);\nexport type FormEditDispatch = Dispatch;\n\nconst INITIAL_STATE: FormState = {\n streetLine1: '',\n streetLine2: '',\n city: '',\n state: '',\n countryIso2: '',\n postCode: '',\n fullName: '',\n email: '',\n phone: '',\n shipping: '',\n cardNumber: '',\n cardholder: '',\n expiry: '',\n cvv: '',\n billingCountry: '',\n billingZip: '',\n saveInfo: true,\n saveCredentials: false,\n formErrors: {},\n};\n\nconst reducer: StateReducer = (state, action) => {\n switch (action.type) {\n case 'changeAddress1':\n return {\n ...state,\n streetLine1: action.payload,\n formErrors: {\n ...state.formErrors,\n streetLine1: undefined,\n },\n };\n case 'changeAddress2':\n return {\n ...state,\n streetLine2: action.payload,\n formErrors: {\n ...state.formErrors,\n streetLine2: undefined,\n },\n };\n case 'changeCity':\n return {\n ...state,\n city: action.payload,\n formErrors: {\n ...state.formErrors,\n city: undefined,\n },\n };\n case 'changeState':\n return {\n ...state,\n state: action.payload,\n formErrors: {\n ...state.formErrors,\n state: undefined,\n },\n };\n case 'changeCountry':\n return {\n ...state,\n countryIso2: action.payload,\n billingCountry: getBillingCountry(action.payload),\n formErrors: {\n ...state.formErrors,\n countryIso2: undefined,\n },\n };\n case 'changePostCode':\n return {\n ...state,\n postCode: action.payload,\n formErrors: {\n ...state.formErrors,\n postCode: undefined,\n },\n };\n case 'changeFullName':\n return {\n ...state,\n fullName: action.payload,\n formErrors: {\n ...state.formErrors,\n fullName: undefined,\n },\n };\n case 'changeEmail':\n return {\n ...state,\n email: action.payload,\n formErrors: {\n ...state.formErrors,\n email: undefined,\n },\n };\n case 'changePhone':\n return {\n ...state,\n phone: action.payload,\n formErrors: {\n ...state.formErrors,\n phone: undefined,\n },\n };\n case 'changeShipping':\n return { ...state, shipping: action.payload };\n case 'changeCardNumber':\n return {\n ...state,\n cardNumber: action.payload,\n formErrors: {\n ...state.formErrors,\n cardNumber: undefined,\n },\n };\n case 'changeCardholder':\n return {\n ...state,\n cardholder: action.payload,\n formErrors: {\n ...state.formErrors,\n cardholder: undefined,\n },\n };\n case 'changeExpiryDate':\n return {\n ...state,\n expiry: action.payload,\n formErrors: {\n ...state.formErrors,\n expiry: undefined,\n },\n };\n case 'changeCvvCode':\n return {\n ...state,\n cvv: action.payload,\n formErrors: {\n ...state.formErrors,\n cvv: undefined,\n },\n };\n case 'changeBillingCountry':\n return {\n ...state,\n billingCountry: action.payload,\n formErrors: {\n ...state.formErrors,\n billingCountry: undefined,\n },\n };\n case 'changeBillingZip':\n return {\n ...state,\n billingZip: action.payload,\n formErrors: {\n ...state.formErrors,\n billingZip: undefined,\n },\n };\n case 'changeSaveInfo':\n return { ...state, saveInfo: action.payload };\n case 'changeSaveCredentials':\n return { ...state, saveCredentials: action.payload };\n case 'updateUserInfo':\n if (action.payload.countryIso2) {\n return {\n ...state,\n ...action.payload,\n billingCountry: getBillingCountry(action.payload.countryIso2),\n };\n }\n return { ...state, ...action.payload };\n case 'setFormErrors':\n return {\n ...state,\n formErrors: {\n ...state.formErrors,\n ...action.payload,\n },\n };\n default:\n return state;\n }\n};\n\nfunction getBillingCountry(countryCode: string) {\n const country = countryList.find(({ id }) => id === countryCode);\n return country ? country.name : '';\n}\n\nexport default () => {\n return useReducer(reducer, INITIAL_STATE);\n};\n","import { RefObject } from 'react';\n\nimport { IS_TOUCH_ENV } from '../util/environment';\nimport { fastRaf } from '../util/schedulers';\nimport { useEffect } from '../lib/teact/teact';\n\nconst DEFAULT_DURATION = 400;\n\nexport default function useFocusAfterAnimation(\n ref: RefObject, animationDuration = DEFAULT_DURATION,\n) {\n useEffect(() => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n setTimeout(() => {\n fastRaf(() => {\n if (ref.current) {\n ref.current.focus();\n }\n });\n }, animationDuration);\n }, [ref, animationDuration]);\n}\n","import { ChangeEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n id?: string;\n value?: string;\n label?: string;\n error?: string;\n ref?: RefObject;\n hasArrow?: boolean;\n placeholder?: string;\n onChange?: (e: ChangeEvent) => void;\n children: any;\n};\n\nconst Select: FC = (props) => {\n const {\n id,\n value,\n label,\n hasArrow,\n error,\n ref,\n placeholder,\n onChange,\n children,\n } = props;\n const labelText = error || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error && 'error',\n labelText && 'with-label',\n hasArrow && 'with-arrow',\n 'input-group',\n );\n\n return (\n
\n \n {children}\n \n {labelText && id && (\n \n )}\n
\n );\n};\n\nexport default memo(Select);\n","import React, {\n FC, useRef, useCallback, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\nimport useFocusAfterAnimation from '../../hooks/useFocusAfterAnimation';\nimport useLang from '../../hooks/useLang';\nimport { countryList } from '../../util/phoneNumber';\n\nimport InputText from '../ui/InputText';\nimport Select from '../ui/Select';\nimport Checkbox from '../ui/Checkbox';\n\nimport './ShippingInfo.scss';\n\nexport type OwnProps = {\n state: FormState;\n needEmail: boolean;\n needPhone: boolean;\n needName: boolean;\n needAddress: boolean;\n dispatch: FormEditDispatch;\n};\n\nconst ShippingInfo: FC = ({\n state,\n needEmail,\n needPhone,\n needName,\n needAddress,\n dispatch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const phoneRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const selectCountryRef = useRef(null);\n\n useEffect(() => {\n if (selectCountryRef.current\n && selectCountryRef.current.value !== state.countryIso2) {\n selectCountryRef.current.value = state.countryIso2;\n }\n }, [state.countryIso2]);\n\n const lang = useLang();\n\n useFocusAfterAnimation(inputRef);\n\n const handleAddress1Change = useCallback((e) => {\n dispatch({ type: 'changeAddress1', payload: e.target.value });\n }, [dispatch]);\n\n const handleAddress2Change = useCallback((e) => {\n dispatch({ type: 'changeAddress2', payload: e.target.value });\n }, [dispatch]);\n\n const handleCityChange = useCallback((e) => {\n dispatch({ type: 'changeCity', payload: e.target.value });\n }, [dispatch]);\n\n const handleStateChange = useCallback((e) => {\n dispatch({ type: 'changeState', payload: e.target.value });\n }, [dispatch]);\n\n const handleCountryChange = useCallback((e) => {\n dispatch({ type: 'changeCountry', payload: e.target.value });\n }, [dispatch]);\n\n const handlePostCodeChange = useCallback((e) => {\n dispatch({ type: 'changePostCode', payload: e.target.value });\n }, [dispatch]);\n\n const handleFullNameChange = useCallback((e) => {\n dispatch({ type: 'changeFullName', payload: e.target.value });\n }, [dispatch]);\n\n const handleEmailChange = useCallback((e) => {\n dispatch({ type: 'changeEmail', payload: e.target.value });\n }, [dispatch]);\n\n const handlePhoneChange = useCallback((e) => {\n let { value } = e.target;\n value = `+${value.replace(/\\D/g, '')}`;\n if (phoneRef.current) {\n phoneRef.current.value = value;\n }\n dispatch({ type: 'changePhone', payload: value });\n }, [dispatch]);\n\n const handleSaveInfoChange = useCallback((e) => {\n dispatch({ type: 'changeSaveInfo', payload: e.target.value });\n }, [dispatch]);\n\n const { formErrors } = state;\n return (\n
\n
\n {needAddress ? (\n
\n
{lang('PaymentShippingAddress')}
\n \n \n \n \n \n {countryList.map(({ name, id }) => (\n \n {name}\n \n ))}\n \n\n \n
\n ) : undefined}\n { needName || needEmail || needPhone ? (\n
{lang('PaymentShippingReceiver')}
\n ) : undefined }\n { needName && (\n \n ) }\n { needEmail && (\n \n ) }\n { needPhone && (\n \n ) }\n \n \n
\n );\n};\n\nexport default memo(ShippingInfo);\n","import React, {\n FC, useCallback, memo, useMemo, useEffect,\n} from '../../lib/teact/teact';\n\nimport { ShippingOption } from '../../types/index';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\n\nimport RadioGroup from '../ui/RadioGroup';\n\nimport './Shipping.scss';\n\nexport type OwnProps = {\n state: FormState;\n shippingOptions: ShippingOption[];\n currency: string;\n dispatch: FormEditDispatch;\n};\n\nconst Shipping: FC = ({\n state,\n shippingOptions,\n currency,\n dispatch,\n}) => {\n useEffect(() => {\n if (!shippingOptions || state.shipping) {\n return;\n }\n dispatch({ type: 'changeShipping', payload: shippingOptions[0].id });\n }, [shippingOptions, state.shipping, dispatch]);\n\n const handleShippingSelect = useCallback((value) => {\n dispatch({ type: 'changeShipping', payload: value });\n }, [dispatch]);\n\n const options = useMemo(() => (shippingOptions.map(({ id: value, title: label, amount }) => ({\n label,\n subLabel: `${currency} ${String(amount / 100)}`,\n value,\n }))), [shippingOptions, currency]);\n\n return (\n
\n
\n

Select shipping method

\n \n \n
\n );\n};\n\nexport default memo(Shipping);\n","import React, {\n FC, memo,\n} from '../../lib/teact/teact';\n\nimport { Price } from '../../types';\n\nimport './Checkout.scss';\n\nexport type OwnProps = {\n invoiceContent?: {\n title?: string;\n description?: string;\n text?: string;\n photoUrl?: string;\n };\n checkoutInfo?: {\n paymentMethod?: string;\n paymentProvider?: string;\n shippingAddress?: string;\n name?: string;\n phone?: string;\n shippingMethod?: string;\n };\n prices?: Price[];\n totalPrice?: number;\n shippingPrices?: Price[];\n currency?: string;\n};\n\nconst Checkout: FC = ({\n invoiceContent,\n prices,\n shippingPrices,\n checkoutInfo,\n currency,\n totalPrice,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const { photoUrl, title, text } = (invoiceContent || {});\n const {\n paymentMethod,\n paymentProvider,\n shippingAddress,\n name,\n phone,\n shippingMethod,\n } = (checkoutInfo || {});\n return (\n
\n
\n { photoUrl && (\n \"\"\n )}\n
\n
{ title }
\n

{ text }

\n
\n
\n
\n { prices && prices.map((item) => (\n renderPaymentItem(item.label, item.amount, currency, false)\n )) }\n { shippingPrices && shippingPrices.map((item) => (\n renderPaymentItem(item.label, item.amount, currency, false)\n )) }\n { totalPrice !== undefined && (\n renderPaymentItem('Total', totalPrice, currency, true)\n ) }\n
\n
\n {paymentMethod && renderCheckoutItem('icon-card', paymentMethod, 'Payment method')}\n {paymentProvider && renderCheckoutItem('stripe-provider', paymentProvider, 'Payment provider')}\n {shippingAddress && renderCheckoutItem('icon-location', shippingAddress, 'Shipping address')}\n {name && renderCheckoutItem('icon-user', name, 'Name')}\n {phone && renderCheckoutItem('icon-phone', phone, 'Phone number')}\n {shippingMethod && renderCheckoutItem('icon-truck', shippingMethod, 'Shipping method')}\n
\n
\n );\n};\n\nfunction renderPaymentItem(title: string, value: number, currency?: string, main = false) {\n return (\n
\n
\n { title }\n
\n
\n { `${currency || ''} ${(value / 100).toFixed(2)}` }\n
\n
\n );\n}\n\nfunction renderCheckoutItem(icon: string, title: string, data: string) {\n return (\n
\n \n
\n
\n { title }\n
\n

\n { data }\n

\n
\n
\n );\n}\n\nexport default memo(Checkout);\n","import React, {\n FC, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { formatCardExpiry } from '../middle/helpers/inputFormatters';\n\nimport InputText from '../ui/InputText';\n\nconst MAX_FIELD_LENGTH = 5;\n\nexport type OwnProps = {\n value: string;\n error?: string;\n onChange: (value: string) => void;\n};\n\nconst ExpiryInput : FC = ({ value, error, onChange }) => {\n // eslint-disable-next-line no-null/no-null\n const expiryInputRef = useRef(null);\n\n const handleKeyDown = useCallback((e) => {\n if (e.key === 'Backspace' && value.charAt(value.length - 1) === '/') {\n const newValue = value.slice(0, value.length - 1);\n if (expiryInputRef.current) {\n expiryInputRef.current.value = newValue;\n }\n }\n }, [value]);\n\n const handleChange = useCallback((e) => {\n onChange(formatCardExpiry(e.target.value));\n }, [onChange]);\n\n return (\n \n );\n};\n\nexport default memo(ExpiryInput);\n","export function formatCardExpiry(input: string) {\n input = input.replace(/[^\\d]/g, '').slice(0, 4);\n const parts = input.match(/.{1,2}/g);\n if (parts && parts[0] && Number(parts[0]) > 12) {\n parts[0] = '12';\n }\n if (parts && parts[0] && parts[0].length === 2 && !parts[1]) {\n parts[1] = '';\n }\n return parts ? parts.join('/') : '';\n}\n\nexport function formatCardNumber(input: string) {\n input = input.replace(/[^\\d]/g, '');\n const parts = input.match(/.{1,4}/g);\n return parts ? parts.join(' ') : '';\n}\n","export default __webpack_public_path__ + \"mastercard.4216118edafe23cc2dec7b8807ba4622.svg\";","export default __webpack_public_path__ + \"visa.e5a7c336e1deb4b92a636e2e053878c4.svg\";","import React, {\n FC, memo, useCallback, useState, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport useFocusAfterAnimation from '../../hooks/useFocusAfterAnimation';\nimport { formatCardNumber } from '../middle/helpers/inputFormatters';\nimport { detectCardType, CardType } from '../common/helpers/detectCardType';\n\nimport InputText from '../ui/InputText';\n\nimport './CardInput.scss';\n\n// @ts-ignore\nimport mastercardIconPath from '../../assets/mastercard.svg';\n// @ts-ignore\nimport visaIconPath from '../../assets/visa.svg';\n\nconst CARD_NUMBER_MAX_LENGTH = 23;\n\nexport type OwnProps = {\n value: string;\n error?: string;\n onChange: (value: string) => void;\n};\n\nconst CardInput : FC = ({ value, error, onChange }) => {\n // eslint-disable-next-line no-null/no-null\n const cardNumberRef = useRef(null);\n\n useFocusAfterAnimation(cardNumberRef);\n\n const [cardType, setCardType] = useState(CardType.Default);\n useEffect(() => {\n const newCardType = detectCardType(value);\n setCardType(newCardType);\n // eslint-disable-next-line\n }, []);\n\n const handleChange = useCallback((e) => {\n const newValue = formatCardNumber(e.target.value);\n const newCardType = detectCardType(e.target.value);\n setCardType(newCardType);\n onChange(newValue);\n if (cardNumberRef.current) {\n cardNumberRef.current.value = newValue;\n }\n }, [onChange, cardNumberRef]);\n\n const cardIcon = getCardIcon(cardType);\n\n return (\n
\n {cardIcon}\n \n
\n );\n};\n\nexport default memo(CardInput);\n\nfunction getCardIcon(cardType: CardType) {\n switch (cardType) {\n case CardType.Mastercard:\n return \"\";\n case CardType.Visa:\n return \"\";\n default:\n return undefined;\n }\n}\n","import React, {\n FC, useCallback, memo, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\nimport useLang from '../../hooks/useLang';\nimport { countryList } from '../../util/phoneNumber';\n\nimport InputText from '../ui/InputText';\nimport Checkbox from '../ui/Checkbox';\nimport Select from '../ui/Select';\nimport ExpiryInput from './ExpiryInput';\nimport CardInput from './CardInput';\n\nimport './PaymentInfo.scss';\n\nexport type OwnProps = {\n state: FormState;\n canSaveCredentials: boolean;\n needCardholderName?: boolean;\n needCountry?: boolean;\n needZip?: boolean;\n dispatch: FormEditDispatch;\n};\n\nconst PaymentInfo: FC = ({\n state,\n canSaveCredentials,\n needCardholderName,\n needCountry,\n needZip,\n dispatch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const selectCountryRef = useRef(null);\n\n useEffect(() => {\n if (selectCountryRef.current\n && selectCountryRef.current.value !== state.billingCountry) {\n selectCountryRef.current.value = state.billingCountry;\n }\n }, [state.billingCountry]);\n\n const handleCardNumberChange = useCallback((value) => {\n dispatch({ type: 'changeCardNumber', payload: value });\n }, [dispatch]);\n\n const handleCardholderChange = useCallback((e) => {\n dispatch({ type: 'changeCardholder', payload: e.target.value.toUpperCase() });\n }, [dispatch]);\n\n const handleExpiryChange = useCallback((value) => {\n dispatch({ type: 'changeExpiryDate', payload: value });\n }, [dispatch]);\n\n const handleCvvChange = useCallback((e) => {\n dispatch({ type: 'changeCvvCode', payload: e.target.value });\n }, [dispatch]);\n\n const handleCountryChange = useCallback((e) => {\n dispatch({ type: 'changeBillingCountry', payload: e.target.value });\n }, [dispatch]);\n\n const handleBillingPostCodeChange = useCallback((e) => {\n dispatch({ type: 'changeBillingZip', payload: e.target.value });\n }, [dispatch]);\n\n const handleChangeSaveCredentials = useCallback((e) => {\n dispatch({ type: 'changeSaveCredentials', payload: e.target.value });\n }, [dispatch]);\n\n const lang = useLang();\n\n const { formErrors = {} } = state;\n\n return (\n
\n
\n
{lang('PaymentCardTitle')}
\n \n { needCardholderName && (\n \n )}\n
\n \n \n
\n { needCountry || needZip ? (\n
{lang('PaymentBillingAddress')}
\n ) : undefined }\n { needCountry && (\n \n {\n countryList.map(({ name }) => (\n \n {name}\n \n ))\n }\n \n ) }\n { needZip && (\n \n )}\n { canSaveCredentials && (\n \n ) }\n \n
\n );\n};\n\nexport default memo(PaymentInfo);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { PaymentStep, ShippingOption, Price } from '../../types';\nimport { ApiError } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport { getCurrencySign } from '../middle/helpers/getCurrencySign';\nimport { detectCardTypeText } from '../common/helpers/detectCardType';\nimport { getShippingError } from '../../modules/helpers/payments';\nimport usePaymentReducer, { FormState } from '../../hooks/reducers/usePaymentReducer';\nimport useLang from '../../hooks/useLang';\n\nimport ShippingInfo from './ShippingInfo';\nimport Shipping from './Shipping';\nimport Checkout from './Checkout';\nimport PaymentInfo from './PaymentInfo';\nimport Button from '../ui/Button';\nimport Modal from '../ui/Modal';\nimport Transition from '../ui/Transition';\nimport Spinner from '../ui/Spinner';\n\nimport './PaymentModal.scss';\n\nconst DEFAULT_PROVIDER = 'stripe';\n\nexport type OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n nameRequested?: boolean;\n shippingAddressRequested?: boolean;\n phoneRequested?: boolean;\n emailRequested?: boolean;\n flexible?: boolean;\n phoneToProvider?: boolean;\n emailToProvider?: boolean;\n currency?: string;\n prices?: Price[];\n isProviderError: boolean;\n needCardholderName?: boolean;\n needCountry?: boolean;\n needZip?: boolean;\n globalErrors?: ApiError[];\n};\n\ntype GlobalStateProps = Pick;\n\ntype DispatchProps = Pick;\n\nconst Invoice: FC = ({\n isOpen,\n onClose,\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n nameRequested,\n shippingAddressRequested,\n phoneRequested,\n emailRequested,\n phoneToProvider,\n emailToProvider,\n currency,\n passwordMissing,\n isProviderError,\n invoiceContent,\n nativeProvider,\n prices,\n needCardholderName,\n needCountry,\n needZip,\n error,\n globalErrors,\n validateRequestedInfo,\n sendPaymentForm,\n setPaymentStep,\n sendCredentialsInfo,\n clearPaymentError,\n}) => {\n const [paymentState, paymentDispatch] = usePaymentReducer();\n const currencySign = getCurrencySign(currency);\n const [isLoading, setIsLoading] = useState(false);\n const lang = useLang();\n\n useEffect(() => {\n if (step || error || globalErrors) {\n setIsLoading(false);\n }\n }, [step, error, globalErrors]);\n\n useEffect(() => {\n if (error && error.field) {\n paymentDispatch({\n type: 'setFormErrors',\n payload: {\n [error.field]: error.fieldError,\n },\n });\n return;\n }\n if (globalErrors && globalErrors.length) {\n const errors = getShippingError(globalErrors);\n paymentDispatch({\n type: 'setFormErrors',\n payload: {\n ...errors,\n },\n });\n }\n }, [error, globalErrors, paymentDispatch]);\n\n useEffect(() => {\n if (savedInfo) {\n const {\n name: fullName, phone, email, shippingAddress,\n } = savedInfo;\n paymentDispatch({\n type: 'updateUserInfo',\n payload: {\n fullName,\n phone: phone && phone.charAt(0) !== '+'\n ? `+${phone}`\n : phone,\n email,\n ...(shippingAddress || {}),\n },\n });\n }\n }, [savedInfo, paymentDispatch]);\n\n const handleErrorModalClose = useCallback(() => {\n clearPaymentError();\n }, [clearPaymentError]);\n\n const totalPrice = useMemo(() => {\n if (step !== PaymentStep.Checkout) {\n return 0;\n }\n\n return getTotalPrice(prices, shippingOptions, paymentState.shipping);\n }, [step, paymentState.shipping, prices, shippingOptions]);\n\n const checkoutInfo = useMemo(() => {\n if (step !== PaymentStep.Checkout) {\n return undefined;\n }\n return getCheckoutInfo(paymentState, shippingOptions, nativeProvider || '');\n }, [step, paymentState, shippingOptions, nativeProvider]);\n\n function renderError() {\n if (!error) {\n return undefined;\n }\n return (\n \n

{error.description || 'Error'}

\n

{error.description || 'Error'}

\n \n {lang('OK')}\n \n
\n );\n }\n\n function renderModalContent(cuurentStep: PaymentStep) {\n switch (cuurentStep) {\n case PaymentStep.ShippingInfo:\n return (\n \n );\n case PaymentStep.Shipping:\n return (\n \n );\n case PaymentStep.PaymentInfo:\n return (\n \n );\n case PaymentStep.Checkout:\n return (\n \n );\n default:\n return undefined;\n }\n }\n\n const validateRequest = useCallback(() => {\n const { saveInfo } = paymentState;\n const requestInfo = getRequestInfo(paymentState);\n validateRequestedInfo({ requestInfo, saveInfo });\n }, [validateRequestedInfo, paymentState]);\n\n const sendCredentials = useCallback(() => {\n const credentials = getCredentials(paymentState);\n sendCredentialsInfo({\n credentials,\n });\n }, [sendCredentialsInfo, paymentState]);\n\n const sendForm = useCallback(() => {\n sendPaymentForm({\n shippingOptionId: paymentState.shipping,\n saveCredentials: paymentState.saveCredentials,\n });\n }, [sendPaymentForm, paymentState]);\n\n const setStep = useCallback((nextStep) => {\n setPaymentStep({ step: nextStep });\n }, [setPaymentStep]);\n\n const handleButtonClick = useCallback(() => {\n setIsLoading(true);\n switch (step) {\n case PaymentStep.ShippingInfo:\n return validateRequest();\n case PaymentStep.Shipping:\n return setStep(PaymentStep.PaymentInfo);\n case PaymentStep.PaymentInfo:\n return sendCredentials();\n case PaymentStep.Checkout:\n return sendForm();\n default:\n return () => {};\n }\n }, [step, validateRequest, setStep, sendCredentials, sendForm]);\n\n const modalHeader = useMemo(() => {\n switch (step) {\n case PaymentStep.ShippingInfo:\n return lang('PaymentShippingInfo');\n case PaymentStep.Shipping:\n return lang('PaymentShippingMethod');\n case PaymentStep.PaymentInfo:\n return lang('PaymentCardInfo');\n case PaymentStep.Checkout:\n return lang('PaymentCheckout');\n default:\n return '';\n }\n }, [step, lang]);\n\n const buttonText = useMemo(() => {\n switch (step) {\n case PaymentStep.Checkout:\n return lang('Checkout.PayPrice', `${currencySign}${(totalPrice / 100).toFixed(2)}`);\n default:\n return lang('Next');\n }\n }, [step, lang, currencySign, totalPrice]);\n\n if (isProviderError) {\n return (\n \n

\n Sorry, Telegram T doesn't support payments with this provider yet.
\n Please use one of our mobile apps to do this.\n

\n \n {lang('OK')}\n \n \n );\n }\n\n return (\n \n
\n \n \n \n

{modalHeader}

\n
\n {step !== undefined ? (\n \n {() => (\n
\n {renderModalContent(step)}\n
\n )}\n
\n ) : (\n
\n \n
\n )}\n
\n \n {buttonText}\n \n
\n {error && !error.field && renderError()}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps & GlobalStateProps => {\n const {\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n invoice,\n invoiceContent,\n nativeProvider,\n nativeParams,\n passwordMissing,\n error,\n } = global.payment;\n\n const isProviderError = Boolean(invoice && (!nativeProvider || nativeProvider !== DEFAULT_PROVIDER));\n const { needCardholderName, needCountry, needZip } = (nativeParams || {});\n const {\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = (invoice || {});\n\n return {\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n nativeProvider,\n passwordMissing,\n nameRequested,\n shippingAddressRequested,\n phoneRequested,\n emailRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n isProviderError,\n invoiceContent,\n needCardholderName,\n needCountry,\n needZip,\n error,\n globalErrors: global.errors,\n };\n },\n (setGlobal, actions): DispatchProps => {\n return pick(actions, [\n 'validateRequestedInfo',\n 'sendPaymentForm',\n 'setPaymentStep',\n 'sendCredentialsInfo',\n 'clearPaymentError',\n ]);\n },\n)(Invoice));\n\nfunction findShippingOption(shippingOptions: ShippingOption[], optionId: string) {\n return shippingOptions.find(({ id }) => id === optionId);\n}\n\nfunction getShippingPrices(shippingOptions: ShippingOption[], shippingOption: string) {\n const option = findShippingOption(shippingOptions, shippingOption);\n return option ? option.prices : undefined;\n}\n\nfunction getTotalPrice(prices: Price[] = [], shippingOptions: ShippingOption[] | undefined, shippingOption: string) {\n const shippingPrices = shippingOptions\n ? getShippingPrices(shippingOptions, shippingOption)\n : [];\n let total = 0;\n const totalPrices = prices.concat(shippingPrices || []);\n total = totalPrices.reduce((acc, cur) => {\n return acc + cur.amount;\n }, total);\n return total;\n}\n\nfunction getCheckoutInfo(state: FormState, shippingOptions: ShippingOption[] | undefined, paymentProvider: string) {\n const cardTypeText = detectCardTypeText(state.cardNumber);\n const paymentMethod = `${cardTypeText} *${state.cardNumber.slice(-4)}`;\n const shippingAddress = state.streetLine1\n ? `${state.streetLine1}, ${state.city}, ${state.countryIso2}`\n : undefined;\n const { phone, fullName: name } = state;\n const shippingOption = shippingOptions ? findShippingOption(shippingOptions, state.shipping) : undefined;\n const shippingMethod = shippingOption ? shippingOption.title : undefined;\n return {\n paymentMethod,\n paymentProvider,\n shippingAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n\nfunction getRequestInfo(paymentState: FormState) {\n const {\n streetLine1,\n streetLine2,\n city,\n state,\n countryIso2,\n postCode,\n fullName: name,\n phone,\n email,\n } = paymentState;\n\n const shippingAddress = {\n streetLine1,\n streetLine2,\n city,\n state,\n countryIso2,\n postCode,\n };\n\n return {\n name,\n phone,\n email,\n shippingAddress,\n };\n}\n\nfunction getCredentials(paymentState: FormState) {\n const {\n cardNumber, cardholder, expiry, cvv, billingCountry, billingZip,\n } = paymentState;\n const [expiryMonth, expiryYear] = expiry.split('/');\n const data = {\n cardNumber,\n cardholder,\n expiryMonth,\n expiryYear,\n cvv,\n country: billingCountry,\n zip: billingZip,\n };\n\n return {\n data,\n };\n}\n","import React, {\n FC, memo, useMemo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { Price } from '../../types';\nimport { ApiShippingAddress } from '../../api/types/payments';\n\nimport useLang from '../../hooks/useLang';\nimport { getCurrencySign } from '../middle/helpers/getCurrencySign';\n\nimport Checkout from './Checkout';\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './PaymentModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n prices?: Price[];\n shippingPrices: any;\n totalAmount?: number;\n currency?: string;\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n photoUrl?: string;\n text?: string;\n title?: string;\n credentialsTitle?: string;\n shippingMethod?: string;\n};\n\nconst ReceiptModal: FC = ({\n isOpen,\n onClose,\n prices,\n shippingPrices,\n totalAmount,\n currency,\n info,\n photoUrl,\n text,\n title,\n credentialsTitle,\n shippingMethod,\n}) => {\n const lang = useLang();\n const currencySign = getCurrencySign(currency);\n const checkoutInfo = useMemo(() => {\n return getCheckoutInfo(credentialsTitle, info, shippingMethod);\n }, [info, shippingMethod, credentialsTitle]);\n return (\n \n
\n
\n \n \n \n

{lang('PaymentReceipt')}

\n
\n
\n \n
\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { receipt } = global.payment;\n const {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n } = (receipt || {});\n\n return {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n };\n },\n)(ReceiptModal));\n\nfunction getCheckoutInfo(paymentMethod?: string,\n info?:\n { phone?: string;\n name?: string;\n shippingAddress?: ApiShippingAddress;\n },\n shippingMethod?: string) {\n if (!info) {\n return { paymentMethod };\n }\n const { shippingAddress } = info;\n const fullAddress = shippingAddress && shippingAddress.streetLine1\n ? `${shippingAddress.streetLine1}, ${shippingAddress.city}, ${shippingAddress.countryIso2}`\n : undefined;\n const { phone, name } = info;\n return {\n paymentMethod,\n paymentProvider: 'Stripe',\n shippingAddress: fullAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n \n {isCroppieReady ? (\n
\n ) : (\n \n )}\n \n \n \n \n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n
\n \n \n \n {croppedBlobUrl && \"Avatar\"}\n \n \n
\n );\n};\n\nexport default memo(AvatarEditable);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState>();\n const [peekMonkeyData, setPeekMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {closeMonkeyData && (\n \n )}\n {peekMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const lang = useLang();\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n
\n \n \n \n \n \n
\n
\n {canSubmit && (\n \n )}\n \n );\n};\n\nexport default memo(PasswordForm);\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/3.048f19f68ad10b65610e.css b/dist/3.b7d1e22369add742c79e.css similarity index 100% rename from dist/3.048f19f68ad10b65610e.css rename to dist/3.b7d1e22369add742c79e.css diff --git a/dist/3.b7d1e22369add742c79e.js b/dist/3.b7d1e22369add742c79e.js new file mode 100644 index 00000000..35921c49 --- /dev/null +++ b/dist/3.b7d1e22369add742c79e.js @@ -0,0 +1,2 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[3],Array(103).concat([function(e,t,a){"use strict";a.r(t),a.d(t,"MediaViewer",(function(){return de})),a.d(t,"ForwardPicker",(function(){return je})),a.d(t,"Errors",(function(){return ke})),a.d(t,"Notifications",(function(){return Ie})),a.d(t,"SafeLinkModal",(function(){return Pe})),a.d(t,"HistoryCalendar",(function(){return Te})),a.d(t,"CalendarModal",(function(){return Ae})),a.d(t,"DeleteMessageModal",(function(){return Re})),a.d(t,"PinMessageModal",(function(){return De})),a.d(t,"UnpinAllMessagesModal",(function(){return Be})),a.d(t,"MessageSelectToolbar",(function(){return qe})),a.d(t,"LeftSearch",(function(){return Nt})),a.d(t,"Settings",(function(){return on})),a.d(t,"ContactList",(function(){return mn})),a.d(t,"NewChat",(function(){return pn})),a.d(t,"NewChatStep1",(function(){return hn})),a.d(t,"NewChatStep2",(function(){return bn})),a.d(t,"ArchivedChats",(function(){return En})),a.d(t,"ContextMenuContainer",(function(){return Mn})),a.d(t,"StickerSetModal",(function(){return Fn})),a.d(t,"HeaderMenuContainer",(function(){return An})),a.d(t,"MobileSearch",(function(){return Dn})),a.d(t,"AttachmentModal",(function(){return Wn})),a.d(t,"PollModal",(function(){return Zn})),a.d(t,"SymbolMenu",(function(){return jc})),a.d(t,"AttachMenu",(function(){return Cc})),a.d(t,"MentionTooltip",(function(){return Vn})),a.d(t,"StickerTooltip",(function(){return yc})),a.d(t,"BotKeyboardMenu",(function(){return kc})),a.d(t,"CustomSendMenu",(function(){return Nc})),a.d(t,"DropArea",(function(){return Ic.b})),a.d(t,"TextFormatter",(function(){return Sc.a})),a.d(t,"EmojiTooltip",(function(){return Pc})),a.d(t,"RightSearch",(function(){return Fc})),a.d(t,"StickerSearch",(function(){return Rc})),a.d(t,"GifSearch",(function(){return Dc})),a.d(t,"PollResults",(function(){return xc})),a.d(t,"Management",(function(){return Jc})),a.d(t,"PaymentModal",(function(){return kr})),a.d(t,"ReceiptModal",(function(){return Sr}));var n=a(0),c=a(2),r=a(5),s=a(20),l=a(1),o=a(7),i=a(115),d=a(6),m=a(4),u=a(3),h=a(132),b=a(47),g=a(177),p=a(26),v=a(108),E=a(120),O=a(191),f=a(38),j=a(48),C=a(146),y=a(56);function k(e,t,a,n){const{mediaEl:c}=P(t,n);if(!c)return;const{width:r}=y.a.get();let o,d=!1;if(n){const{photo:e,video:t,webPage:a}=Object(m.v)(n);d=Boolean(t),o=t?Object(m.bb)(t):Object(m.S)(e||a.photo)}else o=i.a;const{width:u,height:h}=Object(i.j)(e,d),{width:b,height:g}=Object(i.e)(u,h,o.width,o.height),p=(r-b)/2,v=function(e){const t=window.matchMedia(i.b);let a=4.125;e&&(a+=t.matches?.875:3.375);return a*i.c}(e)+(h-g)/2;let{top:E,left:O,width:f,height:j}=c.getBoundingClientRect();if([s.h.SharedMedia,s.h.Album,s.h.ScheduledAlbum,s.h.SearchResult].includes(t)){const e=function(e,t,a,n,c,r){if(e===t){const s=Math.max(c,r)*(e/t);n-=(s-c)/2,a-=(s-r)/2,c=s,r=s}else if(e>t){const a=c;n-=((c=r*(e/t))-a)/2}else if(t>e){const n=r;a-=((r=c*(t/e))-n)/2}return{top:a,left:n,width:c,height:r}}(b,g,E,O,f,j);E=e.top,O=e.left,f=e.width,j=e.height}const C=O+f/2-(p+b/2),k=E+j/2-(v+g/2),N=f/b,S=j/g,F=I(a||c);w(F,{top:v+"px",left:p+"px",width:b+"px",height:g+"px",transform:`translate3d(${C}px, ${k}px, 0) scale(${N}, ${S})`}),M(F,t),document.body.classList.add("ghost-animating"),requestAnimationFrame(()=>{document.body.appendChild(F),requestAnimationFrame(()=>{F.style.transform="",function(e){e.firstChild.style.objectFit="default",e.classList.remove("rounded-corners","circle")}(F),setTimeout(()=>{requestAnimationFrame(()=>{document.body.contains(F)&&document.body.removeChild(F),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function N(e,t,a){const{container:n,mediaEl:c}=P(e,a);if(!c)return;const r=document.getElementById("MediaViewer").querySelector(".active .media-viewer-content img, .active .media-viewer-content video");if(!r||!c)return;const{top:o,left:i,width:d,height:m}=r.getBoundingClientRect(),{top:u,left:h,width:b,height:g}=c.getBoundingClientRect();let p=u;if(!function(e){if("none"===e.style.display)return!1;const t=e.getBoundingClientRect(),{height:a}=y.a.get();return t.top<=a&&t.top+t.height>=0}(n)){const{height:e}=y.a.get();p=uf?O=f:f>O&&(f=O));const C=document.getElementsByClassName("ghost")[0],k=C||I(t||c,e===s.h.ProfileAvatar);C||w(k,{top:p+"px",left:h+"px",width:b+"px",height:g+"px",transform:`translate3d(${v}px, ${E}px, 0) scale(${O}, ${f})`}),requestAnimationFrame(()=>{if(C){const{top:e,left:t,width:a,height:n}=C.getBoundingClientRect();w(k,{transition:"none",top:p+"px",left:h+"px",transformOrigin:"top left",transform:`translate3d(${t-h}px, ${e-p}px, 0) scale(${a/b}, ${n/g})`,width:b+"px",height:g+"px"})}document.body.classList.add("ghost-animating"),C||document.body.appendChild(k),requestAnimationFrame(()=>{C&&(C.style.transition=""),k.style.transform="",j&&(k.style.opacity="0"),M(k,e),setTimeout(()=>{requestAnimationFrame(()=>{document.body.contains(k)&&document.body.removeChild(k),document.body.classList.remove("ghost-animating")})},200+l.c)})})}function I(e,t=!1){const a=document.createElement("div");a.classList.add("ghost");const n=new Image;if("string"==typeof e?n.src=e:e instanceof HTMLVideoElement?n.src=e.poster:n.src=e.src,a.appendChild(n),t){a.classList.add("ProfileInfo");const e=document.querySelector("#RightColumn .ProfileInfo .info");e&&a.appendChild(e.cloneNode(!0))}return a}function S(e,t){const a=document.querySelector(".active > .MessageList");let n=e.offsetTop+t.closest(".content-inner, .WebPage").offsetTop;return e.id.includes("album-media-")&&(n+=e.parentElement.offsetTop+e.closest(".Message").offsetTop),n>a.scrollTop&&n+t.offsetHeight{if(n&&t)return{sender:Object(m.lb)(t)?Object(d.Gb)(e,t):Object(d.f)(e,t)};if(!a||!t)return{};const c=Object(d.k)(e,t,a);return{message:c,sender:c&&Object(d.tb)(e,c)}},(e,t)=>Object(u.l)(t,["closeMediaViewer","focusMessage"]))(({chatId:e,messageId:t,sender:a,isAvatar:c,message:r,closeMediaViewer:s,focusMessage:l})=>{const o=Object(n.m)(()=>{s(),l({chatId:e,messageId:t})},[e,l,t,s]),i=Object(F.a)();if(!a||!r&&!c)return;const d=a.id<0,u=Object(m.V)(i,a);return n.a.createElement("div",{className:"SenderInfo",onClick:o},d?n.a.createElement(x.a,{key:a.id,size:"medium",chat:a}):n.a.createElement(x.a,{key:a.id,size:"medium",user:a}),n.a.createElement("div",{className:"meta"},n.a.createElement("div",{className:"title",dir:"auto"},u&&Object(B.a)(u)),n.a.createElement("div",{className:"date",dir:"auto"},c?i("lng_mediaview_profile_photo"):Object(D.d)(i,1e3*r.date))))}),G=a(178),q=a(62),z=a(42),H=a(121);a(253);var $=({mediaData:e,isVideo:t,isZoomed:a,message:c,fileName:r,isAvatar:s,onCloseMediaViewer:l,onForward:i,onZoomToggle:d})=>{const[u,h]=Object(n.r)(!1),b=t&&c?Object(m.D)(c,"download"):void 0,{mediaData:g,downloadProgress:p}=Object(E.a)(b,!u);Object(n.n)(()=>{u&&g&&(Object(G.a)(g,r),h(!1))},[r,g,u]),Object(n.n)(()=>{h(!1)},[b]);const v=Object(n.m)(e=>{e.stopPropagation(),h(e=>!e)},[]),O=Object(F.a)(),f=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",className:t?"active":void 0,onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]);return o.g?n.a.createElement("div",{className:"MediaViewerActions-mobile"},n.a.createElement(q.a,{trigger:f,positionX:"right"},!s&&n.a.createElement(z.a,{icon:"forward",onClick:i},O("Forward")),t?n.a.createElement(z.a,{icon:u?"close":"download",onClick:v},u?Math.round(100*p)+"% Downloading...":"Download"):n.a.createElement(z.a,{icon:"download",href:e,download:r},O("AccActionDownload"))),u&&n.a.createElement(H.a,{progress:p,size:"s",noCross:!0})):n.a.createElement("div",{className:"MediaViewerActions"},!s&&n.a.createElement(n.a.Fragment,null,n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("Forward"),onClick:i},n.a.createElement("i",{className:"icon-forward"}))),t?n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("AccActionDownload"),onClick:v},u?n.a.createElement(H.a,{progress:p,size:"s",onClick:v}):n.a.createElement("i",{className:"icon-download"})):n.a.createElement(R.a,{href:e,download:r,round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("AccActionDownload")},n.a.createElement("i",{className:"icon-download"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:a?"Zoom Out":"Zoom In",onClick:d},n.a.createElement("i",{className:a?"icon-zoom-out":"icon-zoom-in"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent-white",ariaLabel:O("Close"),onClick:l},n.a.createElement("i",{className:"icon-close"})))},_=a(9);a(254);var V=({text:e="",isHideable:t,onClick:a})=>{const[c,r]=Object(n.r)(!1);return Object(n.n)(()=>{const e=document.querySelector(".MediaViewerFooter .media-text"),t=()=>{const t=e?e.clientHeight:0;r(t>2*i.c)};t();const a=Object(_.g)(t,500,!0);return window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[]),n.a.createElement("div",{className:"MediaViewerFooter "+(t?"hideable":""),onClick:function(t){e&&t.stopPropagation()}},e&&n.a.createElement("div",{className:"media-viewer-footer-content",onClick:a},n.a.createElement("p",{className:"media-text custom-scroll "+(c?"multiline":""),dir:"auto"},e)))},K=a(35),W=a(137);const Y=function(){if(void 0!==document.fullscreenElement)return"fullscreenElement";if(void 0!==document.mozFullScreenElement)return"mozFullScreenElement";if(void 0!==document.webkitFullscreenElement)return"webkitFullscreenElement";return""}();var Z=a(147),Q=a(136);const X=["bytes","kB","MB","GB","TB","PB"];var J=e=>{const t=0===e?0:Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**Math.floor(t)).toFixed(1)} ${X[t]}`};a(255);const ee=e=>{e.stopPropagation()};var te=({bufferedProgress:e,currentTime:t,duration:a,fileSize:c,isForceVisible:r,isForceMobileVersion:s,isPlayed:l,isFullscreenSupported:i,isFullscreen:d,onChangeFullscreen:m,onPlayPause:u,onSeek:h})=>{const[b,g]=Object(n.r)(!0);Object(n.n)(()=>{r&&g(r)},[r]),Object(n.n)(()=>{let e;return r||(o.g?g(!1):e=window.setTimeout(()=>{g(!1)},800)),()=>{e&&window.clearTimeout(e)}},[r]),Object(n.n)(()=>((b||r)&&document.body.classList.add("video-controls-visible"),()=>{document.body.classList.remove("video-controls-visible")}),[r,b]);const p=Object(F.a)();var v,E;if(b||r)return n.a.createElement("div",{className:"VideoPlayerControls "+(s?"mobile":""),onClick:ee},function(e,t,a,c){const r=e/t*100,s=100*a;return n.a.createElement("div",{className:"player-seekline"},n.a.createElement("div",{className:"player-seekline-track"},n.a.createElement("div",{className:"player-seekline-buffered",style:`width: ${s||0}%`}),n.a.createElement("div",{className:"player-seekline-played",style:`width: ${r||0}%`}),n.a.createElement("input",{min:"0",max:"100",step:.01,type:"range",onInput:c,className:"player-seekline-input",value:r||0})))}(t,a,e,h),n.a.createElement(R.a,{ariaLabel:p("AccActionPlay"),size:"tiny",ripple:!o.g,color:"translucent-white",className:"play",onClick:u},n.a.createElement("i",{className:l?"icon-pause":"icon-play"})),function(e,t){return n.a.createElement("div",{className:"player-time"},`${Object(D.e)(e)} / ${Object(D.e)(t)}`)}(t,a),e<1&&(v=e,E=c,n.a.createElement("div",{className:"player-file-size"},`${J(E*v)} / ${J(E)}`)),i&&n.a.createElement(R.a,{ariaLabel:"Fullscreen",size:"tiny",color:"translucent-white",className:"fullscreen",onClick:m},n.a.createElement("i",{className:""+(d?"icon-smallscreen":"icon-fullscreen")})))};a(256);function ae(){return(ae=Object.assign||function(e){for(var t=1;t{const m=Object(n.q)(null),[u,h]=Object(n.r)(!o.l||!o.e),[b,g]=Object(n.r)(0),[p,v]=Object(n.r)(!0),[E,O,f]=function(e,t){const[a,c]=Object(n.r)(Boolean(Y&&document[Y]));return Object(n.o)(()=>{const a=()=>{c(Boolean(Y&&document[Y]))},n=()=>{c(!0)},r=()=>{c(!1),t(!1)},s=e.current;return document.addEventListener("fullscreenchange",a,!1),document.addEventListener("webkitfullscreenchange",a,!1),document.addEventListener("mozfullscreenchange",a,!1),s&&(s.addEventListener("webkitbeginfullscreen",n,!1),s.addEventListener("webkitendfullscreen",r,!1)),()=>{document.removeEventListener("fullscreenchange",a,!1),document.removeEventListener("webkitfullscreenchange",a,!1),document.removeEventListener("mozfullscreenchange",a,!1),s&&(s.removeEventListener("webkitbeginfullscreen",n,!1),s.removeEventListener("webkitendfullscreen",r,!1))}},[]),Y||"iOS"===o.o?[a,()=>{e.current&&(Y||"iOS"===o.o)&&(e.current.requestFullscreen?e.current.requestFullscreen():e.current.webkitRequestFullscreen?e.current.webkitRequestFullscreen():e.current.webkitEnterFullscreen?e.current.webkitEnterFullscreen():e.current.mozRequestFullScreen&&e.current.mozRequestFullScreen(),c(!0))},()=>{e.current&&(document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen(),c(!1))}]:[!1]}(m,h),{isBuffered:j,bufferedProgress:C,bufferingHandlers:y}=Object(W.a)(),{shouldRender:k,transitionClassNames:N}=Object(K.a)(!j,void 0,void 0,"slow");Object(n.n)(()=>{i||!l?m.current.pause():e&&!o.l&&Object(Q.a)(m.current)},[i,l,e]),Object(n.n)(()=>{m.current.currentTime===m.current.duration?(g(0),h(!1)):g(m.current.currentTime)},[b]);const I=Object(n.m)(e=>{e.stopPropagation(),u?(m.current.pause(),h(!1)):(m.current.play(),h(!0))},[u]);Object(Z.a)(m,[]);const S=Object(n.m)(()=>{v(!0)},[]),w=Object(n.m)(()=>{v(!1)},[]),P=Object(n.m)(e=>{g(e.currentTarget.currentTime)},[]),M=Object(n.m)(()=>{g(0),h(!1)},[]),F=Object(n.m)(()=>{E&&f?f():!E&&O&&O()},[f,E,O]),L=Object(n.m)(e=>{e.stopPropagation(),m.current.currentTime=Number(e.target.value)*m.current.duration/100},[]),A=Object(n.m)(e=>{e.stopPropagation(),v(!p)},[p]);Object(n.n)(()=>{const e=e=>{"Enter"!==e.key&&" "!==e.key||I(e)};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}},[I]);const T=c&&`width: ${c.width}px; height: ${c.height}px`,R=`background-image: url(${a})`;return n.a.createElement("div",{className:"VideoPlayer",onClick:!t&&o.g?A:void 0,onMouseOver:t?void 0:S,onMouseOut:t?void 0:w},n.a.createElement("div",{style:T},n.a.createElement("video",ae({ref:m,autoPlay:o.l,playsInline:!0,loop:t,muted:t,id:"media-viewer-video",style:R,onEnded:M},y,{onTimeUpdate:P}),e&&n.a.createElement("source",{src:e}))),k&&n.a.createElement("div",{className:["spinner-container",N].join(" ")},!j&&n.a.createElement("div",{className:"buffering"},"Buffering..."),n.a.createElement(H.a,{size:"xl",progress:j?1:r,square:!0,onClick:d})),!t&&!k&&n.a.createElement(te,{isPlayed:u,bufferedProgress:C,currentTime:b,isFullscreenSupported:Boolean(O),isFullscreen:E,fileSize:s,duration:m.current?m.current.duration:0,isForceVisible:!u||p,isForceMobileVersion:c&&c.width<400,onSeek:L,onChangeFullscreen:F,onPlayPause:I}))}),ce=a(8);a(257);var re=Object(n.h)(({isShown:e,onChangeZoom:t})=>{const{transitionClassNames:a}=Object(K.a)(e),c=Object(f.a)(e),r=Object(n.q)(null),[s,l]=Object(n.r)(1),i=Object(n.q)(!1);Object(n.n)(()=>{e&&!c&&l(1.5)},[e,c]);const d=Object(n.m)(()=>{i.current=!0},[]),m=Object(n.m)(()=>{i.current=!1,1===s&&t(s,!i.current)},[t,s]);Object(n.n)(()=>{t(s,!i.current)},[s,t]);const u=Object(F.a)(),h=Object(ce.a)("ZoomControls",a);return n.a.createElement("div",{className:h},n.a.createElement(R.a,{disabled:1===s,size:"tiny",color:"translucent-white",ariaLabel:u("ZoomOut"),className:"zoom-out",ripple:!o.g,onClick:()=>{r.current&&l(Math.max(1,s-.5))}},n.a.createElement("i",{className:"icon-zoom-out"})),n.a.createElement(R.a,{disabled:3===s,size:"tiny",color:"translucent-white",ariaLabel:"Zoom In",className:"zoom-in",ripple:!o.g,onClick:()=>{r.current&&l(Math.min(3,s+.5))}},n.a.createElement("i",{className:"icon-zoom-in"})),n.a.createElement("div",{className:"seekline"},n.a.createElement("div",{className:"seekline-track"},n.a.createElement("div",{className:"seekline-played",style:`width: ${50*(s-1)}%`}),n.a.createElement("input",{ref:r,min:1,max:3,step:"0.5",value:s,type:"range",className:"seekline-input",onChange:e=>{l(Math.min(3,Math.max(Number(e.target.value),1)))},onMouseDown:d,onMouseUp:m}))))});a(258);const se=[1,0,0,1,0,0],le={1:1,1.5:1.5,2:2.2,2.5:3.3,3:5.5};var oe=Object(n.h)(({children:e,className:t,noWrap:a,canPan:c,zoomLevel:r,panDeltaX:s,panDeltaY:l,onPan:o})=>{const i=le[r]||r,[d,m]=Object(n.r)(!1),[h,b]=Object(n.r)({dx:s,dy:l,x:0,y:0}),[g,p]=Object(n.r)(se),v=Object(n.q)(null),E=Object(n.q)(null);Object(n.n)(()=>{const e=i||g[0],t=s||g[4],a=l||g[5],n=[...g];g[0]!==e&&(n[0]=e||n[0],n[3]=e||n[3]),g[4]!==t&&(n[4]=t),g[5]!==a&&(n[5]=a),Object(u.a)(g,n)||p(function(e,t,a){const n=a&&a.querySelector(".active img");if(!a||!n)return t;const c=a.getBoundingClientRect(),r=n.getBoundingClientRect(),s=r.width/e*t[0],l=r.height/e*t[3],o=(c.width-s)/2+t[4],i=(c.height-l)/2+t[5];return c.width&&c.width-150{c||p(se)},[c]),Object(n.n)(()=>{E.current&&(E.current.style.transform=`matrix(${g.toString()})`)},[a,g]);return a?e:n.a.createElement("div",{ref:v,className:"pan-wrapper "+(t||""),onMouseDown:e=>{if(!c)return;e.stopPropagation(),e.preventDefault();const t={dx:g[4],dy:g[5],x:e.pageX,y:e.pageY};b(t),m(!0),v.current&&v.current.classList.add("move")},onMouseUp:()=>{m(!1),v.current&&v.current.classList.remove("move"),o&&o(g[4],g[5])},onMouseMove:e=>{if(d){const t=function(e,t){const a=[...g],n=h.x-e,c=h.y-t;return a[4]=h.dx-n,a[5]=h.dy-c,a}(e.pageX,e.pageY);p(t),E.current&&(E.current.style.transform=`matrix(${g.toString()})`)}}},n.a.createElement("div",{ref:E,className:"pan-container"},e))});a(259);function ie(e,t,a){return e?n.a.createElement("img",{src:e,alt:"",style:t?`width: ${t.width}px`:"",draggable:Boolean(a)}):n.a.createElement("div",{className:"spinner-wrapper",style:t?`width: ${t.width}px`:""},n.a.createElement(L.a,{color:"white"}))}var de=Object(n.h)(Object(c.h)(e=>{const{chatId:t,threadId:a,messageId:n,avatarOwnerId:c,profilePhotoIndex:r,origin:l}=e.mediaViewer,{animationLevel:o}=e.settings.byKey;if(l===s.h.SearchResult){if(!t||!n)return{animationLevel:o};const a=Object(d.k)(e,t,n);return a?{chatId:t,messageId:n,senderId:a.senderId,origin:l,message:a,animationLevel:o}:{animationLevel:o}}if(c){return{messageId:-1,senderId:c,avatarOwner:Object(d.Gb)(e,c)||Object(d.f)(e,c),profilePhotoIndex:r||0,animationLevel:o,origin:l}}if(!(t&&a&&n))return{animationLevel:o};let i,m,u;if(i=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.pb)(e,t,n):Object(d.k)(e,t,n),!i)return{animationLevel:o};if(m=l&&[s.h.ScheduledAlbum,s.h.ScheduledInline].includes(l)?Object(d.qb)(e,t):Object(d.m)(e,t),l===s.h.Inline||l===s.h.Album)u=Object(d.gb)(e,t,a)||Object(d.Y)(e,t,a);else if(l===s.h.SharedMedia){const t=Object(d.v)(e),{foundIds:a}=t&&t.resultsByType&&t.resultsByType.media||{};u=a}return{chatId:t,threadId:a,messageId:n,senderId:i.senderId,origin:l,message:i,chatMessages:m,collectionIds:u,animationLevel:o}},(e,t)=>Object(u.l)(t,["openMediaViewer","closeMediaViewer","openForwardMenu","focusMessage"]))(({chatId:e,threadId:t,messageId:a,senderId:c,origin:d,avatarOwner:u,profilePhotoIndex:y,message:I,chatMessages:S,collectionIds:w,openMediaViewer:P,closeMediaViewer:M,openForwardMenu:L,focusMessage:D,animationLevel:B})=>{const x=Object(n.q)(null),G=Boolean(u||a),q=I?Object(m.R)(I):void 0,z=I?Object(m.G)(I):void 0,H=I?Object(m.P)(I):void 0,_=Boolean(q),K=Boolean(z||q),W=Boolean(H),Y=H?H.isGif:void 0,Z=d===s.h.SharedMedia,Q=d===s.h.SearchResult,X=B>=1?"mv-slide":"none",J=2===B?"slide-fade":"none",ee=2===B,te=u?`avatar${u.id}-${y}.jpg`:I&&Object(m.B)(I),ae=Object(f.a)(c),[ce,se]=Object(n.r)(!1),[le,de]=Object(n.r)(!1),[me,ue]=Object(n.r)(1),[he,be]=Object(n.r)({x:0,y:0}),ge=Object(n.p)(()=>_&&a?[a]:Object(m.i)(S||{},w||[],Z),[_,a,S,w,Z]),pe=a?ge.indexOf(a):-1,ve=0===pe||-1===pe,Ee=pe===ge.length-1||-1===pe;function Oe(e){if(u&&void 0!==y){const{photos:t}=u;return t&&t[y]?`photo${t[y].id}?size=c`:Object(m.f)(u,e?"big":"normal")}return I&&Object(m.D)(I,e?"viewerFull":"viewerPreview")}!G||ae&&ae===c&&x.current||(x.current=pe);const fe=Object(v.a)(I&&(Z||Q)&&Object(m.D)(I,"pictogram"),void 0,r.ApiMediaFormat.BlobUrl,void 0,ee&&350),je=Oe(),Ce=Object(v.a)(je,void 0,u&&je&&je.startsWith("profilePhoto")?r.ApiMediaFormat.DataUri:r.ApiMediaFormat.BlobUrl,void 0,ee&&350),{mediaData:ye,downloadProgress:ke}=Object(E.a)(Oe(!0),void 0,I&&Object(m.C)(I,"viewerFull"),void 0,ee&&350),Ne=z||H?(z||H).blobUrl:void 0;let Ie=!W&&(Ne||ye)||Ce||fe;const Se=Object(O.a)(!Ie&&I&&Object(m.E)(I));Ie||d===s.h.SearchResult||(Ie=Se);const we=K?Object(m.S)(_?Object(m.R)(I):Object(m.G)(I)):void 0,Pe=W?Object(m.bb)(Object(m.P)(I)):void 0;Object(n.n)(()=>{o.g&&document.body.classList.toggle("is-media-viewer-open",G)},[G]);const Me=Object(p.a)();Object(n.n)(()=>{const e=window.matchMedia(i.b);return"function"==typeof e.addEventListener?e.addEventListener("change",Me):"function"==typeof e.addListener&&e.addListener(Me),()=>{"function"==typeof e.removeEventListener?e.removeEventListener("change",Me):"function"==typeof e.removeListener&&e.removeListener(Me)}},[Me]);const Fe=Object(f.a)(I),Le=Object(f.a)(d),Ae=Object(f.a)(u),Te=Object(f.a)(Ie);Object(n.n)(()=>{if(ee&&G&&!Fe&&!Ae){Object(j.b)(350+l.c);const e=I?Object(C.a)(I):void 0;k(Boolean(e),d,Ie,I)}ee&&!G&&(Fe||Ae)&&(Object(j.b)(350+l.c),N(Le,Te,Fe||void 0))},[ee,G,d,Le,I,Fe,Ae,Ie,Te]),Object(n.n)(()=>{let e;return le?se(!0):e=window.setTimeout(()=>{se(!1)},350),()=>{e&&window.clearTimeout(e)}},[le]);const Re=()=>{de(!1),ue(1),be({x:0,y:0})},De=Object(n.m)(()=>{de(!le),ue(le?1:1.5),le&&be({x:0,y:0})},[le]),Be=Object(n.m)((e,t=!1)=>{ue(e),1===e&&t&&Re()},[]),xe=Object(n.m)(()=>{M(),Re()},[M]),Ue=Object(n.m)(()=>{xe(),D({chatId:e,threadId:t,messageId:a})},[xe,e,t,D,a]),Ge=Object(n.m)(()=>{L({fromChatId:e,messageIds:[a]}),Re()},[L,e,a]);Object(n.n)(()=>G?Object(b.a)(()=>{le?Re():xe()}):void 0,[xe,G,le]),Object(n.n)(()=>{W&&!Y&&Object(g.b)()},[Y,W]);const qe=Object(n.m)((e,t)=>{let a=ge.indexOf(e);return(-1===t&&a>0||1===t&&a{ve||P({chatId:e,threadId:t,messageId:a?qe(a,-1):void 0,origin:d})},[e,t,qe,ve,a,P,d]),He=Object(n.m)(()=>{Ee||P({chatId:e,threadId:t,messageId:a?qe(a,1):void 0,origin:d})},[e,t,qe,Ee,a,P,d]);Object(n.n)(()=>{const e=e=>{switch(e.key){case"Left":case"ArrowLeft":ze();break;case"Right":case"ArrowRight":He()}};return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)}}),Object(n.n)(()=>{const e=document.querySelector(".slide-container > .active, .slide-container > .to");if(!e)return;const t=Y&&!o.e;return Object(h.b)(e,{excludedClosestSelector:".backdrop, .navigation, .media-viewer-head, .media-viewer-footer"+(t?"":", .VideoPlayer"),onClick:()=>{le||xe()},onSwipe:o.l?(e,t)=>{t===h.a.Right?ze():t===h.a.Left?He():xe()}:void 0})},[xe,Y,le,He,ze,ce]);const $e=Object(n.m)((e,t)=>{be({x:e,y:t})},[]),_e=Object(F.a)();function Ve(t){if(u)return n.a.createElement("div",{key:e,className:"media-viewer-content"},ie(ye||Ce,Object(i.g)(i.a,!1),!o.g&&!le));if(I){const e=Object(C.a)(I),c=Boolean(e);return n.a.createElement("div",{key:a,className:"media-viewer-content "+(c?"has-footer":"")},K&&ie(Ne||ye||Ce||fe,I&&Object(i.g)(we,c),!o.g&&!le),W&&n.a.createElement(ne,{key:a,url:Ne||ye,isGif:Y,posterData:Ie,posterSize:I&&Object(i.g)(Pe,c,!0),downloadProgress:ke,fileSize:H.size,isMediaViewerOpen:G,noPlay:!t,onClose:xe}),e&&n.a.createElement(V,{text:e,onClick:Ue,isHideable:W}))}}function Ke(){return n.a.createElement(U,{key:u?u.id:a,chatId:u?u.id:e,messageId:a,isAvatar:Boolean(u)})}return n.a.createElement(A.a,{id:"MediaViewer",className:le?"zoomed":"",isOpen:G},()=>n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"media-viewer-head",dir:_e.isRtl?"rtl":void 0},o.g&&n.a.createElement(R.a,{className:"media-viewer-close",round:!0,size:"smaller",color:"translucent-white",ariaLabel:_e("Close"),onClick:xe},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(T.a,{activeKey:x.current,name:J},Ke),n.a.createElement($,{mediaData:ye||Ce,isVideo:W,isZoomed:le,message:I,fileName:te,onCloseMediaViewer:xe,onForward:Ge,onZoomToggle:De,isAvatar:Boolean(u)})),n.a.createElement(oe,{noWrap:!ce,canPan:le,panDeltaX:he.x,panDeltaY:he.y,zoomLevel:me,onPan:$e},n.a.createElement(T.a,{className:"slide-container",activeKey:pe,name:X},Ve)),!ve&&n.a.createElement("button",{type:"button",className:"navigation prev "+(W&&!Y&&"inline"),"aria-label":_e("AccDescrPrevious"),dir:_e.isRtl?"rtl":void 0,onClick:ze}),!Ee&&n.a.createElement("button",{type:"button",className:"navigation next "+(W&&!Y&&"inline"),"aria-label":_e("Next"),dir:_e.isRtl?"rtl":void 0,onClick:He}),n.a.createElement(re,{isShown:le,onChangeZoom:Be})))})),me=a(52),ue=a(127),he=a(63),be=a(16),ge=a(110),pe=a(45),ve=a(113),Ee=a(106),Oe=a(109),fe=a(123);a(260);var je=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a},currentUserId:n}=e;return{chatsById:t,activeListIds:a.active,archivedListIds:a.archived,currentUserId:n}},(e,t)=>Object(u.l)(t,["setForwardChatId","exitForwardMode","loadMoreChats"]))(({chatsById:e,activeListIds:t,archivedListIds:a,currentUserId:c,isOpen:s,setForwardChatId:l,exitForwardMode:i,loadMoreChats:d})=>{const[u,h]=Object(n.r)(""),b=Object(n.q)(null),g=Object(F.a)();Object(n.n)(()=>{s?o.g||setTimeout(()=>{requestAnimationFrame(()=>{b.current&&b.current.focus()})},500):(b.current&&b.current.blur(),setTimeout(()=>{h("")},300))},[s]);const p=Object(n.p)(()=>{const n=[...t||[],...a||[]];return Object(m.Db)([...n.filter(t=>{const a=e[t];return!a||!!Object(m.e)(a,r.MAIN_THREAD_ID)&&(!u||Object(me.a)(Object(m.l)(g,e[t],void 0,t===c),u))})],e,void 0,c?[c]:void 0)},[t,a,e,c,u,g]),[v,E]=Object(ue.a)(d,p,Boolean(u)),O=Object(n.m)(e=>{h(e.currentTarget.value)},[]),f=Object(n.q)(null),j=Object(he.a)(f,s,e=>{v&&l({id:v[e]})},".ListItem-button",!0),C=n.a.createElement("div",{className:"modal-header",dir:g.isRtl?"rtl":void 0},n.a.createElement(R.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:g("Close"),onClick:i},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(pe.a,{ref:b,value:u,onChange:O,onKeyDown:j,placeholder:g("ForwardTo")}));return n.a.createElement(ge.a,{isOpen:s,onClose:i,className:"ForwardPicker",header:C},v&&v.length?n.a.createElement(ve.a,{className:"picker-list custom-scroll",items:v,onLoadMore:E,noScrollRestore:Boolean(u),ref:f,onKeyDown:j},v.map(e=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable force-rounded-corners",onClick:()=>l({id:e})},Object(m.lb)(e)?n.a.createElement(Oe.a,{status:e===c?g("SavedMessagesInfo"):void 0,userId:e}):n.a.createElement(fe.a,{chatId:e})))):v&&!v.length?n.a.createElement("p",{className:"no-results"},"Sorry, nothing found."):n.a.createElement(be.a,null))})),Ce=a(169);a(261);function ye(e){return e.isSlowMode?"Slowmode enabled":"Something went wrong"}var ke=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["errors"]),(e,t)=>Object(u.l)(t,["dismissError"]))(({errors:e,dismissError:t})=>{const a=Object(F.a)();if(e.length)return n.a.createElement("div",{id:"Errors"},e.map(e=>n.a.createElement(ge.a,{isOpen:!0,onClose:t,className:"error",title:ye(e)},n.a.createElement("p",null,Object(Ce.a)(e)),n.a.createElement(R.a,{isText:!0,onClick:t},a("OK")))))})),Ne=a(180);var Ie=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["notifications"]),(e,t)=>Object(u.l)(t,["dismissNotification"]))(({notifications:e,dismissNotification:t})=>{if(e.length)return n.a.createElement("div",{id:"Notifications"},e.map(({message:e})=>n.a.createElement(Ne.a,{message:Object(B.a)(e,["emoji","br","links"]),onDismiss:t})))})),Se=a(135),we=a(117);var Pe=Object(n.h)(Object(c.h)(void 0,(e,t)=>Object(u.l)(t,["toggleSafeLinkModal"]))(({url:e,toggleSafeLinkModal:t})=>{const a=Object(F.a)(),c=Object(n.m)(()=>{window.open(e),t({url:void 0})},[t,e]),r=Object(n.m)(()=>{t({url:void 0})},[t]),s=Object(Se.a)(e);return n.a.createElement(we.a,{isOpen:Boolean(e),onClose:r,title:a("OpenUrlTitle"),textParts:Object(B.a)(a("OpenUrlAlert2",s),["links"]),confirmLabel:a("OpenUrlTitle"),confirmHandler:c})}));a(262);const Me=["M","T","W","T","F","S","S"];function Fe(e,t,a,n,c){const r=new Date(e,t,a,0,0,0,0),s=n&&new Date(n.getFullYear(),n.getMonth(),n.getDate(),0,0,0,0),l=c&&new Date(c.getFullYear(),c.getMonth(),c.getDate(),0,0,0,0);return!!(l&&r>l)||!!(s&&r{const h=Object(F.a)(),b=new Date,g=Object(n.p)(()=>e?new Date(e):new Date,[e]),p=t?new Date(t):void 0,[v,E]=Object(n.r)(g),[O,f]=Object(n.r)(Le(g.getHours())),[j,C]=Object(n.r)(Le(g.getMinutes())),y=v.getFullYear(),k=v.getMonth(),N=v.getDate();Object(n.n)(()=>{r&&E(g)},[r,g]);const I=c&&y>=b.getFullYear()&&k>=b.getMonth()||p&&y>=p.getFullYear()&&k>=p.getMonth(),S=a&&y<=b.getFullYear()&&k<=b.getMonth(),w=Object(n.p)(()=>function(e,t){const a=[],n=new Date;n.setFullYear(e),n.setMonth(t),n.setDate(1);const c=n.getDay();for(let e=1;e{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return f(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),23)),n=new Date(v.getTime());n.setHours(a),E(n);const c=Le(a);f(c),e.target.value=c},[v]),M=Object(n.m)(e=>{const t=e.target.value.replace(/[^\d]+/g,"");if(!t.length)return C(""),void(e.target.value="");const a=Math.max(0,Math.min(Number(t),59)),n=new Date(v.getTime());n.setMinutes(a),E(n);const c=Le(a);C(c),e.target.value=c},[v]);return n.a.createElement(ge.a,{isOpen:r,onClose:d,className:"CalendarModal"},n.a.createElement("div",{className:"container"},n.a.createElement("div",{className:"month-selector"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:d},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h4",null,Object(D.f)(h,v,o.g)),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",disabled:S,onClick:S?void 0:function(){E(e=>{const t=new Date(e);return t.setMonth(t.getMonth()-1),t})}},n.a.createElement("i",{className:"icon-previous"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",disabled:I,onClick:I?void 0:function(){E(e=>{const t=new Date(e);return t.setMonth(t.getMonth()+1),t})}},n.a.createElement("i",{className:"icon-next"})))),n.a.createElement("div",{className:"calendar-wrapper"},n.a.createElement("div",{className:"calendar-grid"},Me.map(e=>n.a.createElement("div",{className:"day-button faded weekday"},n.a.createElement("span",null,e))),w.map(e=>n.a.createElement("div",{role:"button",tabIndex:0,onClick:()=>{return t=e,void E(e=>{const a=new Date(e);return a.setDate(t),a});var t},className:Object(ce.a)("day-button",Fe(y,k,e,a?b:void 0,c?b:p)?"disabled":""+(e?"clickable":""),e===N&&"selected")},!!e&&n.a.createElement("span",null,e))))),s&&n.a.createElement("div",{className:"timepicker"},n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:O,onChange:P}),":",n.a.createElement("input",{type:"text",className:"form-control",inputMode:"decimal",value:j,onChange:M})),n.a.createElement("div",{className:"footer"},n.a.createElement(R.a,{onClick:function(){m(v)}},s?function(e,t){const a=Object(D.c)(e,t,!0);if("Today"===a)return e("Conversation.ScheduleMessage.SendToday",Object(D.h)(t));return e("Conversation.ScheduleMessage.SendOn",a).replace("%@",Object(D.h)(t))}(h,v):l),i&&n.a.createElement(R.a,{onClick:u,isText:!0},i)))});var Te=Object(n.h)(Object(c.h)(e=>({selectedAt:e.historyCalendarSelectedAt}),(e,t)=>Object(u.l)(t,["searchMessagesByDate","closeHistoryCalendar"]))(({isOpen:e,selectedAt:t,searchMessagesByDate:a,closeHistoryCalendar:c})=>{const r=Object(n.m)(e=>{a({timestamp:e.valueOf()/1e3}),c()},[c,a]),s=Object(F.a)();return n.a.createElement(Ae,{isOpen:e,selectedAt:t,isPastMode:!0,submitButtonLabel:s("JumpToDate"),onClose:c,onSubmit:r})}));var Re=Object(n.h)(Object(c.h)((e,{message:t,isSchedule:a})=>{const{threadId:n}=Object(d.y)(e)||{},{canDeleteForAll:c}=n&&Object(d.b)(e,t,n)||{},r=Object(d.f)(e,t.chatId);return{canDeleteForAll:!a&&c,contactName:r&&Object(m.lb)(r.id)?Object(m.Y)(Object(d.Gb)(e,Object(m.U)(r))):void 0,willDeleteForCurrentUserOnly:r&&Object(m.ib)(r)&&!c,willDeleteForAll:r&&Object(m.nb)(r)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages"]))(({isOpen:e,isSchedule:t,message:a,album:c,canDeleteForAll:r,contactName:s,willDeleteForCurrentUserOnly:l,willDeleteForAll:o,onClose:i,deleteMessages:d,deleteScheduledMessages:m})=>{const u=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];d({messageIds:e,shouldDeleteForAll:!0}),i()},[d,a.id,i,c]),h=Object(n.m)(()=>{const e=c&&c.messages?c.messages.map(({id:e})=>e):[a.id];t?m({messageIds:e}):d({messageIds:e,shouldDeleteForAll:!1}),i()},[c,a.id,t,i,m,d]),b=Object(F.a)();return n.a.createElement(ge.a,{isOpen:e,onClose:i,onEnter:e&&!r?h:void 0,className:"delete",title:b("DeleteSingleMessagesTitle")},n.a.createElement("p",null,b("AreYouSureDeleteSingleMessage")),l&&n.a.createElement("p",null,b("lng_delete_for_me_chat_hint")),o&&n.a.createElement("p",null,b("lng_delete_for_everyone_hint",1,"i")),r&&n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},s&&b("Conversation.DeleteMessagesFor",Object(B.a)(s)),!s&&b("Conversation.DeleteMessagesForEveryone")),n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},b(r?"ChatList.DeleteForCurrentUser":"Delete")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:i},b("Cancel")))}));var De=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(m.lb)(t),n=Object(d.P)(e,t),c=Object(d.f)(e,t),r=!!c&&Object(m.jb)(c),s=!!c&&Object(m.ib)(c),l=!!c&&Object(m.nb)(c);return{isPrivateChat:a,isChatWithSelf:n,isChannel:r,isGroup:s,isSuperGroup:l,canPinForAll:a&&!n||l||s,contactName:c&&Object(m.lb)(c.id)?Object(m.Y)(Object(d.Gb)(e,Object(m.U)(c))):void 0}},(e,t)=>Object(u.l)(t,["pinMessage"]))(({isOpen:e,messageId:t,chatId:a,isChannel:c,isGroup:r,isSuperGroup:s,canPinForAll:l,contactName:o,onClose:i,pinMessage:d})=>{const m=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1}),i()},[d,a,t,i]),u=Object(n.m)(()=>{d({chatId:a,messageId:t,isUnpin:!1,isOneSide:!0,isSilent:!0}),i()},[a,t,i,d]),h=Object(F.a)();return n.a.createElement(ge.a,{isOpen:e,onClose:i,className:"pin",title:h("PinMessageAlertTitle")},n.a.createElement("p",null,h(c?"PinMessageAlertChannel":r||s?"PinMessageAlert":"PinMessageAlertChat")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:u},h("DialogPin")),l&&n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:m},o?h("Conversation.PinMessagesFor",o):h("Conversation.PinMessageAlert.PinAndNotifyMembers")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:i},h("Cancel")))}));var Be=Object(n.h)(({isOpen:e,pinnedMessagesCount:t=0,onClose:a,onUnpin:c})=>{const r=Object(F.a)();return n.a.createElement(ge.a,{isOpen:e,onClose:a,className:"unpin-all",title:r("Chat.PanelUnpinAllMessages")},n.a.createElement("p",null,r("Chat.UnpinAllMessagesConfirmation",t,"i")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:c},r("DialogUnpin")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:a},r("Cancel")))}),xe=a(34),Ue=a(55);var Ge=Object(n.h)(Object(c.h)((e,{isSchedule:t})=>{const{messageIds:a}=e.selectedMessages||{},{canDeleteForAll:n}=Object(d.e)(e),c=Object(d.r)(e);return{selectedMessageIds:a,canDeleteForAll:!t&&n,contactName:c&&Object(m.lb)(c.id)?Object(m.Y)(Object(d.Gb)(e,Object(m.U)(c))):void 0,willDeleteForCurrentUserOnly:c&&Object(m.ib)(c)&&!n,willDeleteForAll:c&&Object(m.nb)(c)}},(e,t)=>Object(u.l)(t,["deleteMessages","deleteScheduledMessages","exitMessageSelectMode"]))(({isOpen:e,isSchedule:t,selectedMessageIds:a,canDeleteForAll:c,contactName:r,willDeleteForCurrentUserOnly:s,willDeleteForAll:l,onClose:o,deleteMessages:i,deleteScheduledMessages:d,exitMessageSelectMode:m})=>{const u=Object(n.m)(()=>{i({messageIds:a,shouldDeleteForAll:!0}),m(),o()},[i,m,a,o]),h=Object(n.m)(()=>{t?d({messageIds:a}):i({messageIds:a,shouldDeleteForAll:!1}),m(),o()},[t,m,o,d,a,i]),b=Object(F.a)();if(a)return n.a.createElement(ge.a,{isOpen:e,onClose:o,onEnter:c?void 0:h,className:"delete",title:b("Conversation.DeleteManyMessages")},n.a.createElement("p",null,b("AreYouSureDeleteFewMessages")),s&&n.a.createElement("p",null,"This will delete them just for you, not for other participants in the chat."),l&&n.a.createElement("p",null,"This will delete them for everyone in this chat."),c&&n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:u},r?b("ChatList.DeleteForEveryone",Object(B.a)(r)):b("Conversation.DeleteMessagesForEveryone")),n.a.createElement(R.a,{color:"danger",className:"confirm-dialog-button",isText:!0,onClick:h},b(c?"ChatList.DeleteForCurrentUser":"Delete")),n.a.createElement(R.a,{className:"confirm-dialog-button",isText:!0,onClick:o},b("Cancel")))}));a(263);var qe=Object(n.h)(Object(c.h)(e=>{const{type:t}=Object(d.y)(e)||{},{canDelete:a}=Object(d.e)(e);return{isSchedule:"scheduled"===t,selectedMessagesCount:Object(d.sb)(e),canDeleteMessages:a}},(e,t)=>Object(u.l)(t,["exitMessageSelectMode","openForwardMenuForSelectedMessages"]))(({canPost:e,isActive:t,messageListType:a,isSchedule:c,selectedMessagesCount:r,canDeleteMessages:s,exitMessageSelectMode:l,openForwardMenuForSelectedMessages:o})=>{const[i,d,m]=Object(xe.a)();Object(n.n)(()=>t&&!i?Object(Ue.a)({onBackspace:d,onDelete:d,onEsc:l}):void 0,[t,i,d,l]);const u=Object(f.a)(r||void 0,!0),h=t?r:u,b=Object(F.a)(),g=b("VoiceOver.Chat.MessagesSelected",h),p=Object(ce.a)("MessageSelectToolbar",e&&"with-composer",t&&"shown");return n.a.createElement("div",{className:p},n.a.createElement("div",{className:"MessageSelectToolbar-inner"},n.a.createElement(R.a,{color:"translucent",round:!0,onClick:l,ariaLabel:"Exit select mode"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("span",{className:"MessageSelectToolbar-count",title:g},g),!!r&&n.a.createElement("div",{className:"MessageSelectToolbar-actions"},"scheduled"!==a&&n.a.createElement(z.a,{icon:"forward",ariaLabel:"Forward Messages",onClick:o},n.a.createElement("span",{className:"item-text"},b("Forward"))),n.a.createElement(z.a,{destructive:!0,icon:"delete",onClick:d,disabled:!s,ariaLabel:b("EditAdminGroupDeleteMessages")},n.a.createElement("span",{className:"item-text"},b("Delete"))))),n.a.createElement(Ge,{isOpen:i,isSchedule:c,onClose:m}))})),ze=a(168),He=a(50),$e=a(170),_e=e=>{const t=Object(n.q)(null),a=Object(n.m)(a=>{if("Enter"!==a.key)return;t.current===document.activeElement&&e()},[e]);return Object(n.n)(()=>(window.addEventListener("keydown",a,!1),()=>window.removeEventListener("keydown",a)),[a]),t},Ve=a(157);var Ke=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(m.U)(a);return{chat:a,privateChatUser:n?Object(d.Gb)(e,n):void 0,isPinned:Object(d.N)(e,t)}})(({chatId:e,chat:t,privateChatUser:a,isPinned:c,withUsername:r,onClick:s})=>{const[l,o,i]=Object(xe.a)(),d=Object($e.a)({chat:t,privateChatUser:a,isPinned:c,handleDelete:o}),u=()=>{s(e)},h=_e(u);if(t)return n.a.createElement(Ee.a,{className:"chat-item-clickable search-result",onClick:u,contextActions:d,buttonRef:h},Object(m.lb)(e)?n.a.createElement(Oe.a,{userId:e,withUsername:r,avatarSize:"large"}):n.a.createElement(fe.a,{chatId:e,withUsername:r,avatarSize:"large"}),n.a.createElement(Ve.a,{isOpen:l,onClose:i,chat:t}))})),We=a(143);a(264);const Ye=Object(_.g)(e=>e(),6e4,!0);var Ze=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.topPeers,a=e.users.byId,{recentlyFoundChatIds:n}=e.globalSearch;return{topUserIds:t,usersById:a,recentlyFoundChatIds:n}},(e,t)=>Object(u.l)(t,["loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats"]))(({topUserIds:e,usersById:t,recentlyFoundChatIds:a,onReset:c,loadTopUsers:r,loadContactList:s,openChat:l,addRecentlyFoundChatId:o,clearRecentlyFoundChats:i})=>{const d=Object(n.q)(null);Object(n.n)(()=>{Ye(()=>{r(),s()})},[r,s]),Object(We.a)(d,!e);const u=Object(n.m)(e=>{l({id:e}),c(),setTimeout(()=>{o({id:e})},250)},[l,o,c]),h=Object(F.a)();return n.a.createElement("div",{className:"RecentContacts custom-scroll"},e&&n.a.createElement("div",{className:"top-peers-section",dir:h.isRtl?"rtl":void 0},n.a.createElement("div",{ref:d,className:"top-peers no-selection"},e.map(e=>n.a.createElement("div",{className:"top-peer-item",onClick:()=>u(e),dir:h.isRtl?"rtl":void 0},n.a.createElement(x.a,{user:t[e]}),n.a.createElement("div",{className:"top-peer-name"},Object(B.a)(Object(m.Y)(t[e])||" ")))))),a&&n.a.createElement("div",{className:"search-section pt-1"},n.a.createElement("h3",{className:"section-heading mt-0 recent-chats-header",dir:h.isRtl?"rtl":void 0},h("Recent"),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:"Clear recent chats",onClick:i,isRtl:h.isRtl},n.a.createElement("i",{className:"icon-close"}))),a.map(e=>n.a.createElement(Ke,{chatId:e,onClick:u}))))})),Qe=a(133),Xe=a(27);a(265);var Je=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);if(!a)return{};const n=Object(m.U)(a);return{chat:a,...n&&{privateChatUser:Object(d.Gb)(e,n)},lastSyncTime:e.lastSyncTime}},(e,t)=>Object(u.l)(t,["focusMessage"]))(({message:e,searchQuery:t,chatId:a,chat:c,privateChatUser:r,focusMessage:s,lastSyncTime:l})=>{const i=Object(m.E)(e),d=Object(v.a)(Object(m.D)(e,"micro")),u=Boolean(Object(m.I)(e)),h=Object(n.m)(()=>{s({chatId:a,messageId:e.id})},[a,s,e.id]),b=Object(F.a)(),g=_e(h);if(c)return n.a.createElement(Ee.a,{className:"ChatMessage chat-item-clickable",ripple:!o.g,onClick:h,buttonRef:g},n.a.createElement(x.a,{chat:c,user:r,withOnlineStatus:!0,isSavedMessages:r&&r.isSelf,lastSyncTime:l}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"info-row"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",{dir:"auto"},Object(B.a)(Object(m.l)(b,c,r))),c.isVerified&&n.a.createElement(Qe.a,null)),n.a.createElement("div",{className:"message-date"},n.a.createElement(Xe.a,{className:"date"},Object(D.g)(b,1e3*e.date)))),n.a.createElement("div",{className:"subtitle"},n.a.createElement("div",{className:"message",dir:"auto"},function(e,t,a,c,r){if(!a)return Object(B.a)(Object(m.N)(e,t));return n.a.createElement("span",{className:"media-preview"},n.a.createElement("img",{src:a,alt:"",className:r?"round":void 0}),Object(m.P)(t)&&n.a.createElement("i",{className:"icon-play"}),Object(B.a)(Object(m.N)(e,t,!0),["emoji","highlight"],{highlight:c}))}(b,e,d||i,t,u)))))}));a(266);var et=Object(n.h)(({searchDate:e,onSelect:t})=>{const a=Object(n.p)(()=>function(e){if(e.match(/^\d{2,4}-\d{2}-\d{2}$/g)){const t=new Date(e);return[{date:t,text:Object(D.a)(t)}]}const t=[],a=new Date,n=a.getFullYear(),c=a.getTime()>new Date(`${n}-${e}`).getTime()?n:n-1;for(let a=0;a<8;a++){const n=new Date(`${c-a}-${e}`);t.push({date:n,text:Object(D.a)(n)})}return t}(e),[e]);return n.a.createElement("section",{className:"DateSuggest custom-scroll custom-scroll-x"},a.map(({date:e,text:a})=>n.a.createElement("div",{onClick:()=>t(e),className:"date-item",key:a},n.a.createElement("i",{className:"icon-calendar"}),n.a.createElement("span",null,a))))}),tt=a(118),at=a(141);const nt=Object(_.g)(e=>e(),500,!0);var ct=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{byId:a}=e.users,{userIds:n}=e.contactList||{};if(!n)return{chatsById:t,usersById:a};const{currentUserId:c,messages:r,lastSyncTime:s}=e,{fetchingStatus:l,globalResults:o,localResults:i,resultsByType:d}=e.globalSearch,{chatIds:m,userIds:u}=o||{},{chatIds:h,userIds:b}=i||{},{byChatId:g}=r,{foundIds:p}=d&&d.text||{};return{currentUserId:c,localContactIds:n,localChatIds:h,localUserIds:b,globalChatIds:m,globalUserIds:u,foundIds:p,globalMessagesByChatId:g,chatsById:t,usersById:a,fetchingStatus:l,lastSyncTime:s}},(e,t)=>Object(u.l)(t,["openChat","addRecentlyFoundChatId","searchMessagesGlobal","setGlobalSearchChatId"]))(({searchQuery:e,searchDate:t,dateSearchQuery:a,currentUserId:c,localContactIds:r,localChatIds:l,localUserIds:i,globalChatIds:d,globalUserIds:h,foundIds:b,globalMessagesByChatId:g,chatsById:p,usersById:v,fetchingStatus:E,lastSyncTime:O,onReset:f,onSearchDateSelect:j,openChat:C,addRecentlyFoundChatId:y,searchMessagesGlobal:k,setGlobalSearchChatId:N})=>{const I=Object(F.a)(),[S,w]=Object(n.r)(!1),[P,M]=Object(n.r)(!1),L=Object(n.m)(({direction:t})=>{O&&t===s.e.Backwards&&nt(()=>{k({type:"text",query:e})})},[O,k,e]),A=Object(n.m)(e=>{C({id:e}),e!==c&&y({id:e}),o.g||f()},[c,C,y,f]),T=Object(n.m)(e=>{N({id:e})},[N]),R=Object(n.p)(()=>{if(!e||e.startsWith("@")&&e.length<2)return He.a;const t=r?r.filter(t=>{const a=v[t];if(!a)return!1;const n=Object(m.Z)(a);return n&&Object(me.a)(n,e)||Object(me.a)(a.username,e)}):[];return[...c&&Object(me.a)(I("SavedMessages"),e)?[c]:[],...Object(m.Db)(Object(u.o)([...t,...l||[],...i||[]]),p)]},[e,r,c,I,l,i,p,v]),D=Object(n.p)(()=>!e||e.length<4||!d||!h?He.a:Object(m.Db)(Object(u.o)([...d,...h]),p,!0),[p,d,h,e]),B=Object(n.p)(()=>(e||t)&&b&&0!==b.length?b.map(e=>{const[t,a]=e.split("_").map(Number);return g&&g[t]&&g[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):He.a,[b,g,e,t]),x=Object(n.m)(()=>{w(!S)},[S]),U=Object(n.m)(()=>{M(!P)},[P]);const G=E&&!E.chats&&!E.messages&&!R.length&&!D.length&&!B.length;return e||t?n.a.createElement(ve.a,{className:"LeftSearch custom-scroll",items:B,onLoadMore:L,noScrollRestoreOnTop:!0,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(et,{searchDate:a,onSelect:j})),G&&n.a.createElement(tt.a,{text:I("ChatList.Search.NoResults"),description:I("ChatList.Search.NoResultsDescription")}),!!R.length&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar",dir:I.isRtl?"rtl":void 0},R.map(e=>n.a.createElement(at.a,{chatOrUserId:e,onClick:T,clickArg:e}))),!!R.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading",dir:I.isRtl?"auto":void 0},R.length>3&&n.a.createElement(Xe.a,{onClick:x},I(S?"ChatList.Search.ShowLess":"ChatList.Search.ShowMore")),I("DialogList.SearchSectionDialogs")),R.map((e,t)=>{if(S||!(t>=3))return n.a.createElement(Ke,{chatId:e,onClick:A})})),!!D.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading",dir:I.isRtl?"auto":void 0},D.length>3&&n.a.createElement(Xe.a,{onClick:U},I(P?"ChatList.Search.ShowLess":"ChatList.Search.ShowMore")),I("DialogList.SearchSectionGlobal")),D.map((e,t)=>{if(P||!(t>=3))return n.a.createElement(Ke,{chatId:e,withUsername:!0,onClick:A})})),!!B.length&&n.a.createElement("div",{className:"search-section"},n.a.createElement("h3",{className:"section-heading",dir:I.isRtl?"auto":void 0},I("SearchMessages")),B.map((function(t){const a=Object(m.N)(I,t),c=p[t.chatId];if(a&&c)return n.a.createElement(Je,{chatId:t.chatId,message:t,searchQuery:e})})))):n.a.createElement(Ze,{onReset:f})}));const rt=Object(_.g)(e=>e(),500,!0);var st=Object(n.h)(Object(c.h)(e=>{const{byId:t}=e.chats,{currentUserId:a,messages:{byChatId:n},lastSyncTime:c}=e,{fetchingStatus:r,resultsByType:s}=e.globalSearch,{foundIds:l}=s&&s.text||{};return{currentUserId:a,foundIds:l,globalMessagesByChatId:n,chatsById:t,fetchingStatus:r,lastSyncTime:c}},(e,t)=>Object(u.l)(t,["searchMessagesGlobal"]))(({searchQuery:e,currentUserId:t,dateSearchQuery:a,foundIds:c,globalMessagesByChatId:r,chatsById:l,fetchingStatus:o,lastSyncTime:i,searchMessagesGlobal:d,onSearchDateSelect:u})=>{const h=Object(F.a)(),b=Object(n.m)(({direction:a})=>{i&&a===s.e.Backwards&&rt(()=>{d({type:"text",query:e,chatId:t})})},[t,i,d,e]),g=Object(n.p)(()=>c&&0!==c.length?c.map(e=>{const[t,a]=e.split("_").map(Number);return r&&r[t]&&r[t].byId[a]}).filter(Boolean).sort((e,t)=>t.date-e.date):He.a,[c,r]);const p=o&&!o.chats&&!o.messages&&!g.length;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content custom-scroll chat-list",items:g,onLoadMore:b,noFastList:!0},a&&n.a.createElement("div",{className:"chat-selection no-selection no-scrollbar"},n.a.createElement(et,{searchDate:a,onSelect:u})),p&&n.a.createElement(tt.a,{text:h("ChatList.Search.NoResults"),description:h("ChatList.Search.NoResultsDescription")}),!!g.length&&g.map((function(t){const a=Object(m.N)(h,t),c=l[t.chatId];if(a&&c)return n.a.createElement(Je,{chatId:t.chatId,message:t,searchQuery:e})}))))}));function lt(e){return(t,a)=>{const{byId:n}=t.chats,{byId:c}=t.users,{fetchingStatus:r,resultsByType:s,chatId:l}=t.globalSearch,o="audio"!==e?e:a&&a.isVoice?"voice":"audio",{byChatId:i}=t.messages,{foundIds:d}=s&&s[o]||{};return{isLoading:void 0===d||!!r&&Boolean(r.chats||r.messages),chatsById:n,usersById:c,globalMessagesByChatId:i,foundIds:d,searchChatId:l,lastSyncTime:t.lastSyncTime}}}var ot=a(119),it=a(165);const dt=Object(_.g)(e=>e(),500,!0);var mt=Object(n.h)(Object(c.h)(lt("media"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","openMediaViewer"]))(({searchQuery:e,searchChatId:t,isLoading:a,globalMessagesByChatId:c,foundIds:r,lastSyncTime:o,searchMessagesGlobal:i,openMediaViewer:d})=>{const m=Object(F.a)(),u=Object(n.m)(({direction:a})=>{o&&a===s.e.Backwards&&dt(()=>{i({type:"media",query:e,chatId:t})})},[o,i,e,t]),h=Object(n.p)(()=>r&&c?r.map(e=>{const[t,a]=e.split("_").map(Number);return c[t]&&c[t].byId[a]}).filter(Boolean):He.a,[c,r]),b=Object(n.m)((e,t)=>{d({chatId:t,messageId:e,origin:s.h.SearchResult})},[d]);const g=Object(ot.a)([e],l.pb)&&!a,p=g&&r&&r.length>0&&!e,v=g&&r&&r.length>0&&e,E=Object(ce.a)("search-content custom-scroll",v&&"chat-list");return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:E,items:h,itemSelector:e?".ListItem":".Media",onLoadMore:u,noFastList:!0},!g&&n.a.createElement(be.a,null),g&&(!r||0===r.length)&&n.a.createElement(tt.a,{text:m("ChatList.Search.NoResults"),description:m("ChatList.Search.NoResultsDescription")}),p&&n.a.createElement("div",{className:"media-list",dir:m.isRtl?"rtl":void 0},h.map(e=>n.a.createElement(it.a,{key:e.id,idPrefix:"search-media",message:e,onClick:b}))),v&&h.map(e=>n.a.createElement(Je,{key:e.id,chatId:e.chatId,message:e}))))}));function ut(e,t,a,n){const{senderId:c}=t;if(!c)return;const r=Object(m.lb)(c)?n[c]:a[c];let s=Object(m.V)(e,r);const l=a[t.chatId];return l&&(Object(m.lb)(c)&&r.isSelf?s=`${e("FromYou")} → ${Object(m.l)(e,l)}`:Object(m.kb)(l)&&(s+=" → "+Object(m.l)(e,l))),s}var ht=a(185);const bt=Object(_.g)(e=>e(),500,!0);var gt=Object(n.h)(Object(c.h)(lt("links"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:m,focusMessage:u})=>{const h=Object(F.a)(),b=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&bt(()=>{m({type:"links",query:e,chatId:t})})},[d,m,e,t]),g=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number);return o[t]&&o[t].byId[a]}).filter(Boolean):He.a,[o,i]),p=Object(n.m)((e,t)=>{u({chatId:t,messageId:e})},[u]);const v=Object(ot.a)([e],l.pb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content documents-list custom-scroll",items:g,onLoadMore:b,noFastList:!0},!v&&n.a.createElement(be.a,null),v&&(!i||0===i.length)&&n.a.createElement(tt.a,{text:h("ChatList.Search.NoResults"),description:h("ChatList.Search.NoResultsDescription")}),v&&i&&i.length>0&&g.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(g[t-1].date);return n.a.createElement("div",{className:"ListItem",dir:h.isRtl?"rtl":void 0,key:e.id},a&&n.a.createElement("p",{className:"section-heading",dir:h.isRtl?"rtl":void 0},Object(D.f)(h,new Date(1e3*e.date))),n.a.createElement(ht.a,{key:e.id,message:e,senderTitle:ut(h,e,c,r),onMessageClick:p}))})))})),pt=a(160);const vt=Object(_.g)(e=>e(),500,!0);var Et=Object(n.h)(Object(c.h)(lt("documents"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage"]))(({searchQuery:e,searchChatId:t,isLoading:a,chatsById:c,usersById:r,globalMessagesByChatId:o,foundIds:i,lastSyncTime:d,searchMessagesGlobal:u,focusMessage:h})=>{const b=Object(F.a)(),g=Object(n.m)(({direction:a})=>{d&&a===s.e.Backwards&&vt(()=>{u({type:"documents",query:e,chatId:t})})},[d,u,e,t]),p=Object(n.p)(()=>i&&o?i.map(e=>{const[t,a]=e.split("_").map(Number),n=o[t]&&o[t].byId[a];return n&&Object(m.y)(n)?n:void 0}).filter(Boolean):He.a,[o,i]),v=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]);const E=Object(ot.a)([e],l.pb)&&!a;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content documents-list custom-scroll",items:p,onLoadMore:g,noFastList:!0},!E&&n.a.createElement(be.a,null),E&&(!i||0===i.length)&&n.a.createElement(tt.a,{text:b("ChatList.Search.NoResults"),description:b("ChatList.Search.NoResultsDescription")}),E&&i&&i.length>0&&p.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(p[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading"},Object(D.f)(b,new Date(1e3*e.date))),n.a.createElement(pt.a,{message:e,withDate:!0,datetime:e.date,smaller:!0,sender:ut(b,e,c,r),className:"scroll-item",onDateClick:v}))})))})),Ot=a(167);const ft=Object(_.g)(e=>e(),500,!0);var jt=Object(n.h)(Object(c.h)(lt("audio"),(e,t)=>Object(u.l)(t,["searchMessagesGlobal","focusMessage","openAudioPlayer"]))(({isVoice:e,searchQuery:t,searchChatId:a,isLoading:c,chatsById:r,usersById:o,globalMessagesByChatId:i,foundIds:d,lastSyncTime:m,searchMessagesGlobal:u,focusMessage:h,openAudioPlayer:b})=>{const g=Object(F.a)(),p=e?"voice":"audio",v=Object(n.m)(({direction:e})=>{m&&e===s.e.Backwards&&ft(()=>{u({type:p,query:t,chatId:a})})},[p,m,u,t,a]),E=Object(n.p)(()=>d&&i?d.map(e=>{const[t,a]=e.split("_").map(Number);return i[t]&&i[t].byId[a]}).filter(Boolean):He.a,[i,d]),O=Object(n.m)((e,t)=>{h({chatId:t,messageId:e})},[h]),f=Object(n.m)((e,t)=>{b({chatId:t,messageId:e})},[b]);const j=Object(ot.a)([t],l.pb)&&!c;return n.a.createElement("div",{className:"LeftSearch"},n.a.createElement(ve.a,{className:"search-content documents-list custom-scroll",items:E,onLoadMore:v,noFastList:!0},!j&&n.a.createElement(be.a,null),j&&(!d||0===d.length)&&n.a.createElement(tt.a,{text:g("ChatList.Search.NoResults"),description:g("ChatList.Search.NoResultsDescription")}),j&&d&&d.length>0&&E.map((e,t)=>{const a=0===t||Object(D.n)(e.date)!==Object(D.n)(E[t-1].date);return n.a.createElement("div",{className:"ListItem",key:e.id},a&&n.a.createElement("p",{className:"section-heading",dir:g.isRtl?"rtl":void 0},Object(D.f)(g,new Date(1e3*e.date))),n.a.createElement(Ot.a,{key:e.id,message:e,renderingFor:"searchResult",senderTitle:ut(g,e,r,o),date:e.date,lastSyncTime:m,className:"scroll-item",onPlay:f,onDateClick:O}))})))}));a(267);const Ct=[{type:s.c.ChatList,title:"SearchAllChatsShort"},{type:s.c.Media,title:"SharedMediaTab2"},{type:s.c.Links,title:"SharedLinksTab2"},{type:s.c.Files,title:"SharedFilesTab2"},{type:s.c.Music,title:"SharedMusicTab2"},{type:s.c.Voice,title:"SharedVoiceTab2"}],yt=[{type:s.c.ChatList,title:"All Messages"},...Ct.slice(1)],kt=Object.keys(s.c).length/2;var Nt=Object(n.h)(Object(c.h)(e=>{const{currentContent:t,chatId:a}=e.globalSearch;return{currentContent:t,chatId:a}},(e,t)=>Object(u.l)(t,["setGlobalSearchContent","setGlobalSearchDate"]))(({searchQuery:e,searchDate:t,isActive:a,currentContent:c=s.c.ChatList,chatId:r,setGlobalSearchContent:l,setGlobalSearchDate:o,onReset:i})=>{const d=Object(F.a)(),[m,u]=Object(n.r)(0),h=Object(n.p)(()=>Object(D.l)(e),[e]),b=Object(n.m)(e=>{const t=Ct[e];l({content:t.type}),u(e)},[l]),g=Object(n.m)(e=>{o({date:e.getTime()/1e3})},[o]),p=Object(n.q)(null),v=Object(he.a)(p,a,void 0,".ListItem-button",!0);return n.a.createElement("div",{className:"LeftSearch",ref:p,onKeyDown:v},n.a.createElement(ze.a,{activeTab:m,tabs:r?yt:Ct,onSwitchTab:b}),n.a.createElement(T.a,{name:d.isRtl?"slide-reversed":"slide",renderCount:kt,activeKey:c},()=>{switch(c){case s.c.ChatList:return r?n.a.createElement(st,{searchQuery:e,dateSearchQuery:h,onReset:i,onSearchDateSelect:g}):n.a.createElement(ct,{searchQuery:e,searchDate:t,dateSearchQuery:h,onReset:i,onSearchDateSelect:g});case s.c.Media:return n.a.createElement(mt,{searchQuery:e});case s.c.Links:return n.a.createElement(gt,{searchQuery:e});case s.c.Files:return n.a.createElement(Et,{searchQuery:e});case s.c.Music:return n.a.createElement(jt,{key:"audio",searchQuery:e});case s.c.Voice:return n.a.createElement(jt,{key:"voice",isVoice:!0,searchQuery:e});default:return}}))}));function It(e,t){const a=Object(n.q)(e),[c,r]=Object(n.r)(t);return[c,Object(n.m)(e=>{r(t=>a.current(t,e))},[])]}const St=[{icon:"user",title:"FilterContacts",key:"contacts"},{icon:"non-contacts",title:"FilterNonContacts",key:"nonContacts"},{icon:"group",title:"FilterGroups",key:"groups"},{icon:"channel",title:"FilterChannels",key:"channels"},{icon:"bots",title:"FilterBots",key:"bots"}],wt=[{icon:"mute",title:"FilterMuted",key:"excludeMuted"},{icon:"archive",title:"FilterArchived",key:"excludeArchived"},{icon:"readchats",title:"FilterRead",key:"excludeRead"}],Pt=["includedChatIds","bots","channels","groups","contacts","nonContacts"],Mt=["excludedChatIds","excludeArchived","excludeMuted","excludeRead"];function Ft(e,t,a){let n=[],c=[];if("included"===t){const{includedChatIds:t,...r}=a?e.includeFilters||{}:Object(u.l)(e.folder,Pt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}else{const{excludedChatIds:t,...r}=a?e.excludeFilters||{}:Object(u.l)(e.folder,Mt);n=t||[],c=Object.keys(r).filter(e=>Boolean(r[e]))}return{selectedChatIds:n,selectedChatTypes:c}}function Lt(e){if(e){const{includedChatIds:t,...a}=e;if(Object.values(a).filter(Boolean).length>1||t&&t.length)return"";if(a.bots)return"Bots";if(a.groups)return"Groups";if(a.channels)return"Channels";if(a.contacts)return"Contacts";if(a.nonContacts)return"Non-Contacts"}return""}const At={mode:"create",chatFilter:"",folder:{title:"",includedChatIds:[],excludedChatIds:[]}},Tt=(e,t)=>{switch(t.type){case"setTitle":return{...e,folder:{...e.folder,title:t.payload},isTouched:!0};case"editIncludeFilters":return{...e,includeFilters:Object(u.l)(e.folder,Pt)};case"editExcludeFilters":return{...e,excludeFilters:Object(u.l)(e.folder,Mt)};case"setIncludeFilters":return{...e,includeFilters:t.payload,chatFilter:""};case"setExcludeFilters":return{...e,excludeFilters:t.payload,chatFilter:""};case"saveFilters":return e.includeFilters?{...e,folder:{...Object(u.j)(e.folder,Pt),title:e.folder.title?e.folder.title:Lt(e.includeFilters),...e.includeFilters},includeFilters:void 0,chatFilter:"",isTouched:!0}:e.excludeFilters?{...e,folder:{...Object(u.j)(e.folder,Mt),...e.excludeFilters},excludeFilters:void 0,chatFilter:"",isTouched:!0}:e;case"editFolder":{const{id:e,description:a,...n}=t.payload;return{mode:"edit",folderId:e,folder:n,chatFilter:""}}case"setChatFilter":return{...e,chatFilter:t.payload};case"setIsLoading":return{...e,isLoading:t.payload};case"setError":return{...e,error:t.payload};case"reset":return At;default:return e}};const Rt={currentPassword:"",password:"",hint:"",email:""},Dt=(e,t)=>{switch(t.type){case"setCurrentPassword":return{...e,currentPassword:t.payload};case"setPassword":return{...e,password:t.payload};case"setHint":return{...e,hint:t.payload};case"setEmail":return{...e,email:t.payload};case"reset":return Rt;default:return e}};var Bt=Object(n.h)(Object(c.h)(void 0,(e,t)=>Object(u.l)(t,["signOut","deleteChatFolder"]))(({currentScreen:e,editedFolderId:t,onReset:a,onSaveFilter:c,signOut:r,deleteChatFolder:l})=>{const[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(n.m)(()=>{d(!0)},[]),b=Object(n.m)(()=>{d(!1)},[]),g=Object(n.m)(()=>{u(!0)},[]),p=Object(n.m)(()=>{u(!1)},[]),v=Object(n.m)(()=>{b(),r()},[b,r]),E=Object(n.m)(()=>{p(),l({id:t}),a()},[t,p,l,a]),O=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(R.a,{round:!0,ripple:!o.g,size:"smaller",color:"translucent",className:t?"active":"",onClick:e,ariaLabel:"More actions"},n.a.createElement("i",{className:"icon-more"})),[]),f=Object(F.a)();return n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:a,ariaLabel:f("AccDescrGoBack")},n.a.createElement("i",{className:"icon-arrow-left"})),function(){switch(e){case s.m.EditProfile:return n.a.createElement("h3",null,f("lng_settings_information"));case s.m.General:return n.a.createElement("h3",null,f("General"));case s.m.Notifications:return n.a.createElement("h3",null,f("Notifications"));case s.m.Privacy:return n.a.createElement("h3",null,f("PrivacySettings"));case s.m.Language:return n.a.createElement("h3",null,f("Language"));case s.m.GeneralChatBackground:return n.a.createElement("h3",null,f("ChatBackground"));case s.m.GeneralChatBackgroundColor:return n.a.createElement("h3",null,f("SetColor"));case s.m.PrivacyPhoneNumber:return n.a.createElement("h3",null,f("PrivacyPhone"));case s.m.PrivacyLastSeen:return n.a.createElement("h3",null,f("PrivacyLastSeen"));case s.m.PrivacyProfilePhoto:return n.a.createElement("h3",null,f("Privacy.ProfilePhoto"));case s.m.PrivacyForwarding:return n.a.createElement("h3",null,f("PrivacyForwards"));case s.m.PrivacyGroupChats:return n.a.createElement("h3",null,f("AutodownloadGroupChats"));case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement("h3",null,f("AlwaysShareWith"));case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement("h3",null,f("NeverShareWith"));case s.m.PrivacyActiveSessions:return n.a.createElement("h3",null,f("SessionsTitle"));case s.m.PrivacyBlockedUsers:return n.a.createElement("h3",null,f("BlockedUsers"));case s.m.TwoFaDisabled:case s.m.TwoFaEnabled:return n.a.createElement("h3",null,f("TwoStepVerification"));case s.m.TwoFaNewPassword:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:return n.a.createElement("h3",null,f("EnterPassword"));case s.m.TwoFaNewPasswordConfirm:return n.a.createElement("h3",null,f("PleaseReEnterPassword"));case s.m.TwoFaNewPasswordHint:case s.m.TwoFaChangePasswordHint:return n.a.createElement("h3",null,f("PasswordHint"));case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaRecoveryEmail:return n.a.createElement("h3",null,f("RecoveryEmailTitle"));case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement("h3",null,"Recovery Email Code");case s.m.TwoFaCongratulations:return n.a.createElement("h3",null,f("TwoStepVerificationPasswordSet"));case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement("h3",null,f("PleaseEnterCurrentPassword"));case s.m.Folders:return n.a.createElement("h3",null,f("Filters"));case s.m.FoldersCreateFolder:return n.a.createElement("h3",null,f("FilterNew"));case s.m.FoldersEditFolder:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,f("FilterEdit")),t&&n.a.createElement(q.a,{className:"settings-more-menu",trigger:O,positionX:"right"},n.a.createElement(z.a,{icon:"delete",destructive:!0,onClick:g},"Delete Folder")));case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement("div",{className:"settings-main-header"},e===s.m.FoldersIncludedChats?n.a.createElement("h3",null,f("FilterInclude")):n.a.createElement("h3",null,f("FilterExclude")),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",className:"color-primary",onClick:c,ariaLabel:f("AutoDeleteConfirm")},n.a.createElement("i",{className:"icon-check"})));default:return n.a.createElement("div",{className:"settings-main-header"},n.a.createElement("h3",null,f("SETTINGS")),n.a.createElement(q.a,{className:"settings-more-menu",trigger:O,positionX:"right"},n.a.createElement(z.a,{icon:"logout",onClick:h},f("LogOutTitle"))))}}(),n.a.createElement(we.a,{isOpen:i,onClose:b,text:"Are you sure you want to log out?",confirmLabel:"Log Out",confirmHandler:v,confirmIsDestructive:!0}),n.a.createElement(we.a,{isOpen:m,onClose:p,text:"Are you sure you want to delete this folder?",confirmLabel:"Delete",confirmHandler:E,confirmIsDestructive:!0}))})),xt=a(18);var Ut=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e;return{currentUser:t?Object(d.Gb)(e,t):void 0}})(({onScreenSelect:e,currentUser:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-main-menu"},t&&n.a.createElement("div",{className:"settings-current-user"},n.a.createElement(x.a,{user:t,size:"jumbo"}),n.a.createElement("p",{className:"name"},Object(m.Z)(t)),n.a.createElement("p",{className:"phone"},Object(xt.c)(t.phoneNumber))),n.a.createElement(Ee.a,{icon:"edit",onClick:()=>e(s.m.EditProfile)},a("lng_settings_information")),n.a.createElement(Ee.a,{icon:"folder",onClick:()=>e(s.m.Folders)},a("Filters")),n.a.createElement(Ee.a,{icon:"settings",onClick:()=>e(s.m.General)},a("Telegram.GeneralSettingsViewController")),n.a.createElement(Ee.a,{icon:"unmute",onClick:()=>e(s.m.Notifications)},a("Notifications")),n.a.createElement(Ee.a,{icon:"lock",onClick:()=>e(s.m.Privacy)},a("PrivacySettings")),n.a.createElement(Ee.a,{icon:"language",onClick:()=>e(s.m.Language)},a("Language"))))})),Gt=a(130);a(268);var qt=({isShown:e,className:t,color:a="primary",ariaLabel:c,disabled:r,onClick:s,children:l})=>{const o=Object(ce.a)("FloatingActionButton",e&&"revealed",t);return n.a.createElement(R.a,{className:o,color:a,round:!0,disabled:r,onClick:e&&!r?s:void 0,ariaLabel:c,tabIndex:-1},l)};const zt=/https:\/\/t\.me\/?/i,Ht=/^([a-zA-Z0-9_]+)$/,$t=Object(_.a)(e=>e(),250,!1);var _t=Object(n.h)(({currentUsername:e,asLink:t,isLoading:a,isUsernameAvailable:c,checkUsername:r,onChange:s})=>{const[l,o]=Object(n.r)(e||""),i=Object(F.a)(),d=t?"SetUrl":"Username",m=i(t?"SetUrlPlaceholder":"Username"),[u,h]=Object(n.p)(()=>l.length?l.length<5?[void 0,m+" is too short"]:l.length>32?[void 0,m+" is too long"]:Ht.test(l)?void 0===c?[]:[c?i(d+"Available","Username"):void 0,!1===c?i(d+"InUse"):void 0]:[void 0,m+" contains invalid characters"]:[],[l,c,i,d,m]);Object(n.n)(()=>{o(e||"")},[t,e]);const b=Object(n.m)(e=>{const a=e.target.value.trim().replace(zt,"");o(a),e.target.value=`${t?"https://t.me/":""}${a}`;const n=function(e){return e.length>=5&&e.length<=32&&Ht.test(e)}(a);n&&$t(()=>{r({username:a})}),s&&s(!!n&&a)},[t,r,s]);return n.a.createElement(pe.a,{value:`${t?"https://t.me/":""}${l}`,onChange:b,label:m,error:h,success:u,readOnly:a})});const Vt=Object(_.g)(e=>e(),6e4,!0);var Kt=Object(n.h)(Object(c.h)(e=>{const{currentUserId:t}=e,{progress:a,isUsernameAvailable:n}=e.profileEdit||{},c=t?Object(d.Gb)(e,t):void 0;if(!c)return{progress:a,isUsernameAvailable:n};const{firstName:r,lastName:s,username:l,fullInfo:o}=c,{bio:i}=o||{};return{currentAvatarHash:Object(m.f)(c),currentFirstName:r,currentLastName:s,currentBio:i,currentUsername:l,progress:a,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["loadCurrentUser","updateProfile","checkUsername"]))(({currentAvatarHash:e,currentFirstName:t,currentLastName:a,currentBio:c,currentUsername:l,progress:o,isUsernameAvailable:i,loadCurrentUser:d,updateProfile:m,checkUsername:u})=>{const[h,b]=Object(n.r)(!1),[g,p]=Object(n.r)(!1),[E,O]=Object(n.r)(),[f,j]=Object(n.r)(),[C,y]=Object(n.r)(t||""),[k,N]=Object(n.r)(a||""),[I,S]=Object(n.r)(c||""),[w,P]=Object(n.r)(l||""),M=Object(v.a)(e,!1,r.ApiMediaFormat.BlobUrl),A=o===s.j.InProgress,T=!1===w,R=Object(n.p)(()=>!T&&(Boolean(f)||g||!0===i),[f,g,T,i]);Object(n.n)(()=>{Vt(()=>{d()})},[d]),Object(n.n)(()=>{j(void 0)},[M]),Object(n.n)(()=>{y(t||""),N(a||""),S(c||"")},[t,a,c]),Object(n.n)(()=>{P(l||"")},[l]),Object(n.n)(()=>{o===s.j.Complete&&(p(!1),b(!1),O(void 0))},[o]);const D=Object(n.m)(e=>{j(e)},[]),x=Object(n.m)(e=>{y(e.target.value),p(!0)},[]),U=Object(n.m)(e=>{N(e.target.value),p(!0)},[]),G=Object(n.m)(e=>{S(e.target.value),p(!0)},[]),q=Object(n.m)(e=>{P(e),b(!0)},[]),z=Object(n.m)(()=>{const e=C.trim(),t=k.trim(),a=I.trim();e.length?a.length>70?O("Bio can' be longer than 70 characters"):m({photo:f,...g&&{firstName:e,lastName:t,bio:a},...h&&{username:w}}):O("Please provide your first name")},[f,C,k,I,g,w,h,m]),H=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-edit-profile"},n.a.createElement(Gt.a,{currentAvatarBlobUrl:M,onChange:D,title:"Edit your profile photo",disabled:A}),n.a.createElement(pe.a,{value:C,onChange:x,label:H("FirstName"),disabled:A,error:"Please provide your first name"===E?E:void 0}),n.a.createElement(pe.a,{value:k,onChange:U,label:H("LastName"),disabled:A}),n.a.createElement(pe.a,{value:I,onChange:G,label:H("UserBio"),disabled:A,error:"Bio can' be longer than 70 characters"===E?E:void 0}),n.a.createElement("p",{className:"settings-item-description",dir:H.isRtl?"rtl":void 0},Object(B.a)(H("lng_settings_about_bio"),["br","simple_markdown"]))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:H.isRtl?"rtl":void 0},H("Username")),n.a.createElement(_t,{currentUsername:w||"",isLoading:A,isUsernameAvailable:i,checkUsername:u,onChange:q}),n.a.createElement("p",{className:"settings-item-description",dir:H.isRtl?"rtl":void 0},Object(B.a)(H("UsernameHelp"),["br","simple_markdown"])),w&&n.a.createElement("p",{className:"settings-item-description",dir:H.isRtl?"rtl":void 0},H("lng_username_link"),n.a.createElement("br",null),n.a.createElement("span",{className:"username-link"},"https://t.me/",w)))),n.a.createElement(qt,{isShown:R,onClick:z,disabled:A,ariaLabel:"Save changes"},A?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),Wt=a(125),Yt=a(116);const Zt=Object(_.g)(e=>e(),6e4,!0);var Qt=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a}}=e,{orderedIds:n,byId:c,recommended:r}=e.chatFolders;return{chatsById:t,usersById:a,orderedFolderIds:n,foldersById:c,recommendedChatFolders:r,notifySettings:Object(d.eb)(e),notifyExceptions:Object(d.db)(e)}},(e,t)=>Object(u.l)(t,["loadRecommendedChatFolders","addChatFolder","showError"]))(({onCreateFolder:e,onEditFolder:t,chatsById:a,usersById:c,orderedFolderIds:r,foldersById:s,recommendedChatFolders:o,notifySettings:i,notifyExceptions:d,loadRecommendedChatFolders:u,addChatFolder:h,showError:b})=>{const[g,p]=Object(n.r)(),[v,E]=Object(n.r)(!1),O=Object(n.m)(()=>E(!0),[]);Object(n.n)(()=>{g||Object(Wt.a)("FoldersAll").then(p)},[g]),Object(n.n)(()=>{Zt(()=>{u()})},[u]);const f=Object(n.m)(()=>{Object.keys(s).length>=10?b({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):e()},[s,b,e]),j=Object(F.a)(),C=Object(n.p)(()=>{if(!r)return;const e=Object.keys(a).map(Number);return r.map(t=>{const n=s[t];return{id:n.id,title:n.title,subtitle:Object(m.o)(j,a,c,n,e,i,d)}})},[r,a,s,c,i,d,j]),y=Object(n.m)(e=>{Object.keys(s).length>=10?b({error:{message:"DIALOG_FILTERS_TOO_MUCH"}}):h({folder:e})},[s,h,b]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},g&&n.a.createElement(Yt.a,{id:"settingsFoldersMain",size:l.tb,animationData:g,play:v,noLoop:!0,onLoad:O})),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},j("CreateNewFilterInfo")),n.a.createElement(R.a,{className:"with-icon mb-2",color:"primary",size:"smaller",pill:!0,fluid:!0,onClick:f,isRtl:j.isRtl},n.a.createElement("i",{className:"icon-add"}),j("CreateNewFilter"))),n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3",dir:j.isRtl?"rtl":void 0},j("Filters")),C&&C.length?C.map(e=>n.a.createElement(Ee.a,{className:"mb-2",narrow:!0,multiline:!0,onClick:()=>t(s[e.id])},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.subtitle))):C&&!C.length?n.a.createElement("p",{className:"settings-item-description my-4",dir:"auto"},"You have no folders yet."):n.a.createElement(be.a,null)),o&&!!o.length&&n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3",dir:j.isRtl?"rtl":void 0},j("FilterRecommended")),o.map(e=>n.a.createElement(Ee.a,{className:"mb-2",narrow:!0,onClick:()=>y(e)},n.a.createElement("div",{className:"settings-folders-recommended-item"},n.a.createElement("div",{className:"multiline-item"},n.a.createElement("span",{className:"title"},e.title),n.a.createElement("span",{className:"subtitle"},e.description)),n.a.createElement(R.a,{className:"px-3",color:"primary",size:"tiny",pill:!0,fluid:!0,isRtl:j.isRtl},j("Add")))))))}));a(269);var Xt=({count:e,itemName:t,itemPluralName:a,isLoading:c,onClick:r})=>{const s=Object(F.a)();return n.a.createElement(R.a,{className:"ShowMoreButton",color:"translucent",size:"smaller",isText:!0,isLoading:c,isRtl:s.isRtl,onClick:r},n.a.createElement("i",{className:"icon-down"}),"Show ",e," more ",e>1?a||t+"s":t)};const Jt="Please provide a title for this folder.",ea="Please select at least one chat for this folder.";var ta=Object(n.h)(Object(c.h)(e=>{const{listIds:t}=e.chats;return{loadedActiveChatIds:t.active,loadedArchivedChatIds:t.archived}},(e,t)=>Object(u.l)(t,["editChatFolder","addChatFolder","loadMoreChats"]))(({state:e,dispatch:t,onAddIncludedChats:a,onAddExcludedChats:c,onReset:r,loadedActiveChatIds:s,loadedArchivedChatIds:o,editChatFolder:i,addChatFolder:d,loadMoreChats:h})=>{const[b,g]=Object(n.r)(),[p,v]=Object(n.r)(!1),E=Object(n.m)(()=>v(!0),[]),[O,f]=Object(n.r)(!1),[j,C]=Object(n.r)(!1),{selectedChatIds:y,selectedChatTypes:k}=Ft(e,"included"),{selectedChatIds:N,selectedChatTypes:I}=Ft(e,"excluded");Object(n.n)(()=>{b||Object(Wt.a)("FoldersNew").then(g)},[b]),Object(n.n)(()=>{f(!1),C(!1)},[e.folderId]);const[S,w]=Object(n.p)(()=>{const e=new Set([...s||[],...o||[]]),t=Object(u.f)(y,e),a=Object(u.f)(N,e);return[O?t:t.slice(0,5-k.length),j?a:a.slice(0,5-I.length)]},[N,y,k,I,j,O,s,o]);Object(n.n)(()=>{(S.lengthf(!0):()=>C(!0);return n.a.createElement(n.a.Fragment,null,t.map(t=>function(e,t){const a="included"===t?St.find(({key:t})=>t===e):wt.find(({key:t})=>t===e);if(a)return n.a.createElement(Ee.a,{key:a.key,className:"settings-folders-list-item mb-1",icon:a.icon,narrow:!0,inactive:!0},P(a.title))}(t,e)),a.map(e=>n.a.createElement(Ee.a,{className:"settings-folders-list-item mb-1",narrow:!0,inactive:!0},Object(m.lb)(e)?n.a.createElement(Oe.a,{avatarSize:"small",userId:e}):n.a.createElement(fe.a,{avatarSize:"small",chatId:e}))),!c&&r>0&&n.a.createElement(Xt,{count:r,itemName:"chat",onClick:s}))}return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement("div",{className:"settings-content-icon"},b&&n.a.createElement(Yt.a,{id:"settingsFoldersEdit",size:l.tb,animationData:b,play:p&&String(e.folderId),noLoop:!0,onLoad:E})),"create"===e.mode&&n.a.createElement("p",{className:"settings-item-description mb-3",dir:P.isRtl?"rtl":void 0},P("FilterIncludeInfo")),n.a.createElement(pe.a,{className:"mb-0",label:P("FilterNameHint"),value:e.folder.title,onChange:function(e){const{currentTarget:a}=e;t({type:"setTitle",payload:a.value.trim()})},error:e.error&&e.error===Jt?Jt:void 0})),n.a.createElement("div",{className:"settings-item no-border pt-3"},e.error&&e.error===ea&&n.a.createElement("p",{className:"settings-item-description color-danger mb-2",dir:P.isRtl?"rtl":void 0},e.error),n.a.createElement("h4",{className:"settings-item-header mb-3",dir:P.isRtl?"rtl":void 0},P("FilterInclude")),n.a.createElement(Ee.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:a},P("FilterAddChats")),M("included")),n.a.createElement("div",{className:"settings-item no-border pt-3"},n.a.createElement("h4",{className:"settings-item-header mb-3",dir:P.isRtl?"rtl":void 0},P("FilterExclude")),n.a.createElement(Ee.a,{className:"settings-folders-list-item color-primary mb-0",icon:"add",onClick:c},P("FilterAddChats")),M("excluded"))),n.a.createElement(qt,{isShown:!!e.isTouched,disabled:e.isLoading,onClick:function(){const{title:a}=e.folder;a?y.length||Object.keys(k).length?(t({type:"setIsLoading",payload:!0}),"edit"===e.mode?i({id:e.folderId,folderUpdate:e.folder}):d({folder:e.folder}),setTimeout(()=>{r()},500)):t({type:"setError",payload:ea}):t({type:"setError",payload:Jt})},ariaLabel:"edit"===e.mode?"Save changes":"Create folder"},e.isLoading?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))})),aa=a(46);a(186),a(270);var na=Object(n.h)(({mode:e,chatIds:t,selectedIds:a,selectedChatTypes:c,filterValue:r,onSelectedIdsChange:s,onSelectedChatTypesChange:l,onFilterChange:o,onLoadMore:i})=>{const d=Object(n.q)(null),u="included"===e?St:wt,h=a.length+c.length>10,b=a.length>=100;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{d.current.focus()})},500)},[]);const g=Object(n.m)(e=>{const t=[...a];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),s(t)},[a,s]),p=Object(n.m)(e=>{const t=[...c];t.includes(e)?t.splice(t.indexOf(e),1):t.push(e),l(t)},[c,l]),v=Object(n.m)(e=>{const{value:t}=e.currentTarget;o(t)},[o]),E=Object(F.a)();const[O,f]=Object(ue.a)(i,t,Boolean(r));return n.a.createElement("div",{className:"Picker SettingsFoldersChatsPicker"},n.a.createElement("div",{className:"picker-header custom-scroll"},c.map((function(e){const t=u.find(({key:t})=>e===t);if(t)return n.a.createElement(at.a,{icon:t.icon,title:E(t.title),isMinimized:h,canClose:!0,onClick:p,clickArg:t.key})})),a.map((e,t)=>n.a.createElement(at.a,{chatOrUserId:e,isMinimized:h&&tp(e.key),ripple:!0},n.a.createElement("i",{className:"icon-"+e.icon}),n.a.createElement("h3",{className:"chat-type",dir:"auto"},E(e.title)),n.a.createElement(aa.a,{label:"",checked:c.includes(e.key),round:!0}))})),n.a.createElement("div",{key:"divider",className:"picker-list-divider"}),n.a.createElement("h4",{key:"header2",className:"settings-item-header",dir:E.isRtl?"rtl":void 0},E("FilterChats"))),O&&O.length?O.map((function(e){const t=a.includes(e);return n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable picker-list-item chat-item",onClick:()=>g(e),ripple:!0,disabled:!t&&b},Object(m.lb)(e)?n.a.createElement(Oe.a,{userId:e}):n.a.createElement(fe.a,{chatId:e,withChatType:!0}),n.a.createElement(aa.a,{label:"",checked:t,round:!0}))})):O&&!O.length?n.a.createElement("p",{className:"no-results",key:"no-results"},"Sorry, nothing found."):n.a.createElement(be.a,{key:"loading"})))});var ca=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t,listIds:a,orderedPinnedIds:n}}=e;return{chatsById:t,listIds:a.active,orderedPinnedIds:n.active,archivedPinnedIds:n.archived,archivedListIds:a.archived}},(e,t)=>Object(u.l)(t,["loadMoreChats"]))(({mode:e,state:t,dispatch:a,chatsById:c,listIds:r,orderedPinnedIds:s,archivedListIds:l,archivedPinnedIds:o,loadMoreChats:i})=>{const{chatFilter:d}=t,{selectedChatIds:u,selectedChatTypes:h}=Ft(t,e,!0),b=Object(F.a)(),g=Object(n.p)(()=>{const e=r?Object(m.Ab)(c,r,s,"all"):void 0,t=l?Object(m.Ab)(c,l,o,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[c,r,s,l,o]),p=Object(n.p)(()=>{if(g)return g.filter(e=>!d||Object(me.a)(Object(m.l)(b,e),d)||u.includes(e.id)).map(({id:e})=>e)},[g,d,b,u]),v=Object(n.m)(e=>{a({type:"setChatFilter",payload:e})},[a]),E=Object(n.m)(n=>{a("included"===e?{type:"setIncludeFilters",payload:{...t.includeFilters,includedChatIds:n}}:{type:"setExcludeFilters",payload:{...t.excludeFilters,excludedChatIds:n}})},[e,t,a]),O=Object(n.m)(t=>{const n={};t.forEach(e=>{n[e]=!0}),a("included"===e?{type:"setIncludeFilters",payload:{includedChatIds:u,...n}}:{type:"setExcludeFilters",payload:{excludedChatIds:u,...n}})},[e,u,a]);return p?n.a.createElement(na,{mode:e,chatIds:p,selectedIds:u,selectedChatTypes:h,filterValue:d,onSelectedIdsChange:E,onSelectedChatTypesChange:O,onFilterChange:v,onLoadMore:i}):n.a.createElement(be.a,null)}));a(271);var ra=Object(n.h)(({currentScreen:e,state:t,dispatch:a,onScreenSelect:c,onReset:r})=>{const l=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{a({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?r():"create"===t.mode?c(s.m.FoldersCreateFolder):c(s.m.FoldersEditFolder)},[t.mode,a,e,r,c]),o=Object(n.m)(()=>{a({type:"reset"}),c(s.m.FoldersCreateFolder)},[c,a]),i=Object(n.m)(e=>{a({type:"editFolder",payload:e}),c(s.m.FoldersEditFolder)},[a,c]),d=Object(n.m)(()=>{a({type:"editIncludeFilters"}),c(s.m.FoldersIncludedChats)},[a,c]),m=Object(n.m)(()=>{a({type:"editExcludeFilters"}),c(s.m.FoldersExcludedChats)},[a,c]);switch(e){case s.m.Folders:return n.a.createElement(Qt,{onCreateFolder:o,onEditFolder:i});case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:return n.a.createElement(ta,{state:t,dispatch:a,onAddIncludedChats:d,onAddExcludedChats:m,onReset:l});case s.m.FoldersIncludedChats:return n.a.createElement(ca,{mode:"included",state:t,dispatch:a});case s.m.FoldersExcludedChats:return n.a.createElement(ca,{mode:"excluded",state:t,dispatch:a});default:return}}),sa=a(107);a(272);var la=Object(n.h)(({options:e,range:t,label:a,value:c,disabled:r,onChange:s})=>{const l=Object(F.a)(),o=Object(n.m)(e=>{s(Number(e.currentTarget.value))},[s]),i=Object(ce.a)("RangeSlider",r&&"disabled"),d=Object(n.p)(()=>{if(e)return c/(e.length-1)*100;if(t){const e=(t.max-t.min)/(t.step||1);return(c-t.min)/e*100}return 0},[c,e,t]),[m,u,h]=Object(n.p)(()=>e?[0,e.length-1,1]:t?[t.min,t.max,t.step||1]:[0,0,0],[t,e]);return n.a.createElement("div",{className:i},a&&n.a.createElement("div",{className:"slider-top-row",dir:l.isRtl?"rtl":void 0},n.a.createElement("span",{className:"label",dir:"auto"},a),t&&n.a.createElement("span",{className:"value",dir:"auto"},c)),n.a.createElement("div",{className:"slider-main"},n.a.createElement("div",{className:"slider-fill-track",style:`width: ${d}%`}),n.a.createElement("input",{min:m,max:u,value:c,step:h,type:"range",onChange:o}),e&&n.a.createElement("div",{className:"slider-options"},e.map((e,t)=>n.a.createElement("div",{className:Object(ce.a)("slider-option no-selection",t===c&&"active"),onClick:()=>s(t)},e)))))}),oa=a(126),ia=a(114),da=a(49);var ma=Object(n.h)(({size:e=l.zb,stickerSet:t,observeIntersection:a})=>{const c=Object(n.q)(null),s=Object(sa.b)(c,a),o="stickerSet"+t.id,i=Object(v.a)(o,!s,r.ApiMediaFormat.Lottie),{shouldRenderFullMedia:d,transitionClassNames:m}=Object(ia.a)(i,"slow");return n.a.createElement("div",{ref:c,className:"sticker-set-cover"},!d&&Object(da.c)(t.title,2),d&&i&&n.a.createElement(Yt.a,{id:o,size:e,animationData:i,className:m}))});var ua=Object(n.h)(({stickerSet:e,observeIntersection:t})=>{const a=Object(n.q)(null),c=Object(sa.b)(a,t),r=Object(v.a)(e.hasThumbnail&&"stickerSet"+e.id,!c),{shouldRenderFullMedia:s,transitionClassNames:l}=Object(ia.a)(r,"slow");return n.a.createElement("div",{ref:a,className:"sticker-set-cover"},!s&&Object(da.c)(e.title,2),s&&n.a.createElement("img",{src:r,className:l,alt:""}))});a(273);var ha=Object(n.h)(({sticker:e,size:t,observeIntersection:a,noAnimate:c,title:s,className:l,onClick:o,clickArg:i,onUnfaveClick:d})=>{const m=Object(n.q)(null),u="sticker"+e.id,h="sticker-button-"+e.id,b=Object(sa.b)(m,a),g=e.thumbnail?e.thumbnail.dataUri:void 0,p=Object(v.a)(u+"?size=m",!b,r.ApiMediaFormat.BlobUrl),E=b&&!c,O=Object(v.a)(e.isAnimated&&u,!E,r.ApiMediaFormat.Lottie),[f,j,C]=Object(xe.a)(Boolean(O)),y=f&&E,{shouldRenderThumb:k,shouldRenderFullMedia:N,transitionClassNames:I}=Object(ia.a)(p||y,"slow");Object(n.n)(()=>{E||C()},[C,E]);const S=Object(ce.a)("StickerButton",e.isAnimated&&"animated",h,l),w=k&&g?`background-image: url('${g}');`:"";return n.a.createElement("div",{ref:m,className:S,title:s||e&&e.emoji,style:w,"data-sticker-id":e.id,onClick:function(){o&&o(i)}},N&&!y&&n.a.createElement("img",{src:p,className:I}),E&&O&&n.a.createElement(Yt.a,{id:u,animationData:O,play:!0,size:t,isLowPriority:!0,onLoad:j}),d&&n.a.createElement(R.a,{className:"sticker-unfave-button",color:"dark",round:!0,onClick:function(t){t.stopPropagation(),t.preventDefault(),d(e)}},n.a.createElement("i",{className:"icon-close"})))});a(274);var ba=Object(n.h)(({stickerSet:e,observeIntersection:t,onClick:a})=>{const c=Object(F.a)();if(!e||!e.stickers)return;const r=e.stickers&&e.stickers[0];return e.hasThumbnail||!r?n.a.createElement(Ee.a,{narrow:!0,className:"SettingsStickerSet",inactive:!r,onClick:()=>r&&a(r)},n.a.createElement(R.a,{ariaLabel:e.title,color:"translucent",isRtl:c.isRtl},e.isAnimated?n.a.createElement(ma,{size:l.ub,stickerSet:e,observeIntersection:t}):n.a.createElement(ua,{stickerSet:e,observeIntersection:t})),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i")))):n.a.createElement(Ee.a,{narrow:!0,className:"SettingsStickerSet",onClick:()=>a(r)},n.a.createElement(ha,{sticker:r,size:l.ub,title:e.title,observeIntersection:t}),n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("div",{className:"title"},e.title),n.a.createElement("div",{className:"subtitle"},c("StickerPack.StickerCount",e.count,"i"))))}),ga=a(161);const pa=["Solid and Steady","Nice and Fast","Lots of Stuff"];var va=Object(n.h)(Object(c.h)(e=>({...Object(u.l)(e.settings.byKey,["messageTextSize","animationLevel","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers"]),stickerSetIds:e.stickers.added.setIds,stickerSetsById:e.stickers.setsById}),(e,t)=>Object(u.l)(t,["setSettingOption","loadStickerSets","loadAddedStickers"]))(({onScreenSelect:e,stickerSetIds:t,stickerSetsById:a,messageTextSize:c,animationLevel:r,messageSendKeyCombo:l,shouldAutoDownloadMediaFromContacts:i,shouldAutoDownloadMediaInPrivateChats:d,shouldAutoDownloadMediaInGroups:m,shouldAutoDownloadMediaInChannels:u,shouldAutoPlayGifs:h,shouldAutoPlayVideos:b,shouldSuggestStickers:g,shouldLoopStickers:p,setSettingOption:v,loadStickerSets:E,loadAddedStickers:O})=>{const f=Object(n.q)(null),{observe:j}=Object(sa.a)({rootRef:f}),[C,y,k]=Object(xe.a)(),[N,I]=Object(n.r)(),S=Object(F.a)(),w=o.l?void 0:[{value:"enter",label:S("lng_settings_send_enter"),subLabel:"New line by Shift + Enter"},{value:"ctrl-enter",label:S(o.f?"lng_settings_send_cmdenter":"lng_settings_send_ctrlenter"),subLabel:"New line by Enter"}];Object(n.n)(()=>{E()},[E]),Object(n.n)(()=>{t&&t.length&&O()},[t,O]);const P=Object(n.m)(e=>{pa.forEach((t,a)=>{document.body.classList.toggle("animation-level-"+a,e===a)}),v({animationLevel:e})},[v]),M=Object(n.m)(e=>{document.documentElement.style.setProperty("--message-text-size",e+"px"),v({messageTextSize:e})},[v]),L=Object(n.m)(e=>{I(e),y()},[y]),A=t&&t.map(e=>!!(a&&a[e]&&a[e].installedDate)&&a[e]).filter(Boolean);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("SETTINGS")),n.a.createElement(la,{label:S("TextSize"),range:{min:12,max:20},value:c,onChange:M}),n.a.createElement(Ee.a,{icon:"photo",onClick:()=>e(s.m.GeneralChatBackground)},S("ChatBackground"))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},"Animation Level"),n.a.createElement("p",{className:"settings-item-description",dir:S.isRtl?"rtl":void 0},"Choose the desired animations amount."),n.a.createElement(la,{options:pa,value:r,onChange:P})),w&&n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("Keyboard")),n.a.createElement(oa.a,{name:"keyboard-send-settings",options:w,onChange:e=>v({messageSendKeyCombo:e}),selected:l})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("AutoDownloadMedia")),n.a.createElement(aa.a,{label:S("Contacts"),checked:i,onCheck:e=>v({shouldAutoDownloadMediaFromContacts:e})}),n.a.createElement(aa.a,{label:S("AutodownloadPrivateChats"),checked:d,onCheck:e=>v({shouldAutoDownloadMediaInPrivateChats:e})}),n.a.createElement(aa.a,{label:S("AutodownloadGroupChats"),checked:m,onCheck:e=>v({shouldAutoDownloadMediaInGroups:e})}),n.a.createElement(aa.a,{label:S("FilterChannels"),checked:u,onCheck:e=>v({shouldAutoDownloadMediaInChannels:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("AutoplayMedia")),n.a.createElement(aa.a,{label:S("GifsTab2"),checked:h,onCheck:e=>v({shouldAutoPlayGifs:e})}),n.a.createElement(aa.a,{label:S("VideosTitle"),checked:b,onCheck:e=>v({shouldAutoPlayVideos:e})})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:S.isRtl?"rtl":void 0},S("AccDescrStickers")),n.a.createElement(aa.a,{label:S("SuggestStickers"),checked:g,onCheck:e=>v({shouldSuggestStickers:e})}),n.a.createElement(aa.a,{label:S("LoopAnimatedStickers"),checked:p,onCheck:e=>v({shouldLoopStickers:e})}),n.a.createElement("div",{className:"mt-4",ref:f},A&&A.map(e=>n.a.createElement(ba,{key:e.id,stickerSet:e,observeIntersection:j,onClick:L}))),N&&n.a.createElement(ga.a,{isOpen:C,fromSticker:N,onClose:k})))}));let Ea;function Oa(e="*",t,a=!1){Ea||(Ea=document.createElement("input"),Ea.setAttribute("type","file")),Ea.setAttribute("accept",e),a?Ea.removeAttribute("multiple"):Ea.setAttribute("multiple","multiple"),Ea.onchange=null,Ea.value="",Ea.onchange=t,Ea.click()}var fa=a(13);function ja(e){return[parseInt(e.substring(0,2),16),parseInt(e.substring(2,4),16),parseInt(e.substring(4,6),16)]}function Ca(e){const t=e[0].toString(16),a=e[1].toString(16),n=e[2].toString(16);return(1==t.length?"0"+t:t)+(1==a.length?"0"+a:a)+(1==n.length?"0"+n:n)}function ya([e,t,a]){e/=255,t/=255,a/=255;let n,c,r=Math.max(e,t,a),s=Math.min(e,t,a),l=r,o=r-s;if(c=0==r?0:o/r,r==s)n=0;else{switch(r){case e:n=(t-a)/o+(t.5?Math.max(0,.65*n):Math.max(0,Math.min(1,1-.65*n)),`hsla(${360*t}, ${100*a}%, ${100*n}%, .4)`}var Ia=a(12),Sa=a(162);a(275);var wa=Object(n.h)(({wallpaper:e,theme:t,isSelected:a,onClick:c})=>{const{slug:r,document:o}=e,i="wallpaper"+o.id,d=o.previewBlobUrl,m=Object(v.a)(i+"?size=m"),u=Object(Sa.a)(o.thumbnail&&o.thumbnail.dataUri,Boolean(m),!0),{shouldRenderThumb:h,shouldRenderFullMedia:b,transitionClassNames:g}=Object(ia.a)(m||d,"slow"),[p,O]=Object(n.r)(!1),{mediaData:j,downloadProgress:C}=Object(E.a)(i,!p),y=!1===Object(f.a)(p),{shouldRender:k,transitionClassNames:N}=Object(K.a)(p&&!j||r===s.n,void 0,y,"slow"),I=Object(n.q)();I.current=t;const S=Object(n.m)(()=>{(async()=>{const e=await Object(fa.e)(j);await Ia.d(l.m,I.current,e),c(r)})()},[j,c,r]);Object(n.n)(()=>{j&&S()},[j,S]);const w=Object(n.m)(()=>{j?S():O(e=>!e)},[j,S]),P=Object(ce.a)("WallpaperTile",a&&"selected");return n.a.createElement("div",{className:P,onClick:w},n.a.createElement("div",{className:"media-inner"},h&&n.a.createElement("canvas",{ref:u,className:"thumbnail"}),b&&n.a.createElement("img",{src:m||d,className:"full-media "+g,alt:""}),k&&n.a.createElement("div",{className:Object(ce.a)("spinner-container",N)},n.a.createElement(H.a,{progress:C,onClick:w}))))});a(276);const Pa=Object(_.g)(e=>e(),6e4,!0);var Ma=Object(n.h)(Object(c.h)(e=>{const{theme:t}=e.settings.byKey,{background:a,isBlurred:n}=e.settings.themes[t]||{},{loadedWallpapers:c}=e.settings;return{background:a,isBlurred:n,loadedWallpapers:c,theme:t}},(e,t)=>Object(u.l)(t,["loadWallpapers","uploadWallpaper","setThemeSettings"]))(({onScreenSelect:e,background:t,isBlurred:a,loadedWallpapers:c,theme:r,loadWallpapers:o,uploadWallpaper:i,setThemeSettings:d})=>{const m=Object(n.q)();m.current=r,Object(n.n)(()=>{Pa(()=>{o()})},[o]);const u=Object(n.m)(e=>{const{files:t}=e.target;t&&t.length>0&&i(t[0])},[i]),h=Object(n.m)(()=>{Oa("image/jpeg",u,!0)},[u]),b=Object(n.m)(()=>{e(s.m.GeneralChatBackgroundColor)},[e]),g=Object(n.m)(()=>{d({theme:r,background:void 0,backgroundColor:void 0,isBlurred:!0,patternColor:"dark"===r?l.o:l.t})},[d,r]),p=Object(n.m)(e=>{d({theme:m.current,background:e});const t=c&&c.find(t=>t.slug===e);t&&t.document.thumbnail&&async function(e){const t=[0,0,0];let a,n,c,r,s=-4,l=[0,0,0],o=0;const i=document.createElement("canvas"),d=i.getContext&&i.getContext("2d");if(!d)return t;const m=await Object(fa.g)(e);c=m.naturalHeight||m.offsetHeight||m.height,n=m.naturalWidth||m.offsetWidth||m.width,i.height=c,i.width=n,d.drawImage(m,0,0);try{a=d.getImageData(0,0,n,c)}catch(e){return t}for(r=a.data.length;(s+=20){const t=Na(e),a="#"+Ca(e);d({theme:m.current,backgroundColor:a,patternColor:t})})},[c,d]),v=Object(n.m)(e=>{d({theme:m.current,isBlurred:e.target.checked})},[d]),E=Object(F.a)(),O=c&&c[0]&&c[0].slug===s.n;return n.a.createElement("div",{className:"SettingsGeneralBackground settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(Ee.a,{icon:"camera-add",className:"mb-0",disabled:O,onClick:h},E("UploadImage")),n.a.createElement(Ee.a,{icon:"colorize",className:"mb-0",onClick:b},E("SetColor")),n.a.createElement(Ee.a,{icon:"favorite",onClick:g},E("ThemeResetToDefaults")),n.a.createElement(aa.a,{label:E("BackgroundBlurred"),checked:Boolean(a),onChange:v})),c?n.a.createElement("div",{className:"settings-wallpapers"},c.map(e=>n.a.createElement(wa,{wallpaper:e,theme:r,isSelected:t===e.slug,onClick:p}))):n.a.createElement(be.a,null))}));a(277);const Fa=ya(ja("e6ebee")),La=["#e6ebee","#b2cee1","#008dd0","#c6e7cb","#c4e1a6","#60b16e","#ccd0af","#a6a997","#7a7072","#fdd7af","#fdb76e","#dd8851"];function Aa(e,t){return{colorPosition:[Math.round(e[1]*(t.colorRect.width-1)),Math.round((1-e[2])*(t.colorRect.height-1))],huePosition:Math.round(e[0]*(t.hueRect.width-1))}}function Ta({colorPosition:e,huePosition:t},a){return[t/(a.hueRect.width-1),e[0]/(a.colorRect.width-1),1-e[1]/(a.colorRect.height-1)]}var Ra=Object(n.h)(Object(c.h)(e=>{const{theme:t}=e.settings.byKey,{backgroundColor:a}=e.settings.themes[t]||{};return{backgroundColor:a,theme:t}},(e,t)=>Object(u.l)(t,["setThemeSettings"]))(({theme:e,backgroundColor:t,setThemeSettings:a})=>{const c=Object(n.q)();c.current=e;const r=Object(n.q)(null),s=Object(n.q)(null),l=Object(n.q)(null),o=Object(n.q)(!0),[i,d]=Object(n.r)(function(e){return e&&e.startsWith("#")?ya(ja(e.replace("#",""))):Fa}(t)),m=Object(n.q)(i);Object(n.n)(()=>{m.current=i},[i]);const[b,g,p]=Object(xe.a)(),[v,E]=Object(n.r)(""),[O,f]=Object(n.r)(""),j=Object(n.q)(),C=Object(n.q)();Object(n.n)(()=>{const e={offsetLeft:s.current.offsetLeft,...Object(u.l)(s.current.getBoundingClientRect(),["top","width","height"])},t={offsetLeft:l.current.offsetLeft,...Object(u.l)(l.current.getBoundingClientRect(),["width"])};function a(t){const a=[Math.min(Math.max(0,t.pageX-e.offsetLeft),e.width-1),Math.min(Math.max(0,t.pageY-e.top+r.current.scrollTop),e.height-1)],{huePosition:n}=Aa(m.current,j.current);d(Ta({colorPosition:a,huePosition:n},j.current)),g()}function n(e){const{colorPosition:a}=Aa(m.current,j.current),n=Math.min(Math.max(0,e.pageX-t.offsetLeft),t.width-1);d(Ta({colorPosition:a,huePosition:n},j.current)),g()}j.current={colorRect:e,hueRect:t},Object(h.b)(s.current,{onCapture:a,onDrag:a,onRelease:p,onClick:p,withCursor:!0}),Object(h.b)(l.current,{onCapture:n,onDrag:n,onRelease:p,onClick:p,withCursor:!0})},[g,p]);const{colorPosition:y=[0,0],huePosition:k=0}=j.current?Aa(i,j.current):{},N=Ca(ka(i)),I=i[0],S=Ca(ka([I,1,1]));Object(n.n)(()=>{const e=ka(i),t="#"+Ca(e);if(E(e.join(", ")),f(t),!o.current){const n=Na(e);a({theme:c.current,background:void 0,backgroundColor:t,patternColor:n})}o.current=!1},[i,a]),Object(n.n)(()=>{!function(e,t,a,n){let c,r,s;a.current&&n.current?(c=n.current.colorRect.width,r=n.current.colorRect.height,s=a.current):(c=e.offsetWidth,r=e.offsetHeight,s=e.getContext("2d"),e.width=c,e.height=r,a.current=s);const l=s.createImageData(c,r),o=l.data,i=ka([t,1,1]);let d=0;for(let e=0;e{!function(e){const t=e.offsetWidth;e.width=t,e.height=1;const a=e.getContext("2d"),n=a.createImageData(t,1),c=n.data;let r=0;for(let e=0;e{const t=e.currentTarget.value.replace(/[^\d, ]/g,"").slice(0,13);if(t.match(/^\d{1,3},\s?\d{1,3},\s?\d{1,3}$/)){const e=t.split(",").map(e=>Number(e.trim()));d(ya(e))}e.currentTarget.value=t},[]),P=Object(n.m)(e=>{const t=e.currentTarget.value.replace(/[^0-9a-fA-F]/g,"").slice(0,6);t.match(/^#?[0-9a-fA-F]{6}$/)&&d(ya(ja(t.replace("#","")))),e.currentTarget.value=t},[]),M=Object(n.m)(e=>{d(ya(ja(e.currentTarget.dataset.color.replace("#",""))))},[]),F=Object(ce.a)("SettingsGeneralBackgroundColor settings-content custom-scroll",b&&"is-dragging");return n.a.createElement("div",{ref:r,className:F},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement("div",{ref:s,className:"color-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translate(${y[0]}px, ${y[1]}px); background-color: #${N};`})),n.a.createElement("div",{ref:l,className:"hue-picker"},n.a.createElement("canvas",null),n.a.createElement("div",{className:"handle",style:`transform: translateX(${k}px); background-color: #${S};`})),n.a.createElement("div",{className:"tools"},n.a.createElement(pe.a,{value:O,label:"HEX",onChange:P}),n.a.createElement(pe.a,{value:v,label:"RGB",onChange:w}))),n.a.createElement("div",{className:"predefined-colors"},La.map(e=>n.a.createElement("div",{className:e==="#"+N?"active":void 0,"data-color":e,style:`background-color: ${e};`,onClick:M}))))}));var Da=Object(n.h)(Object(c.h)(e=>({hasPrivateChatsNotifications:Boolean(e.settings.byKey.hasPrivateChatsNotifications),hasPrivateChatsMessagePreview:Boolean(e.settings.byKey.hasPrivateChatsMessagePreview),hasGroupNotifications:Boolean(e.settings.byKey.hasGroupNotifications),hasGroupMessagePreview:Boolean(e.settings.byKey.hasGroupMessagePreview),hasBroadcastNotifications:Boolean(e.settings.byKey.hasBroadcastNotifications),hasBroadcastMessagePreview:Boolean(e.settings.byKey.hasBroadcastMessagePreview),hasContactJoinedNotifications:Boolean(e.settings.byKey.hasContactJoinedNotifications)}),(e,t)=>Object(u.l)(t,["loadNotificationSettings","updateContactSignUpNotification","updateNotificationSettings"]))(({hasPrivateChatsNotifications:e,hasPrivateChatsMessagePreview:t,hasGroupNotifications:a,hasGroupMessagePreview:c,hasBroadcastNotifications:r,hasBroadcastMessagePreview:s,hasContactJoinedNotifications:l,loadNotificationSettings:o,updateContactSignUpNotification:i,updateNotificationSettings:d})=>{Object(n.n)(()=>{o()},[o]);const m=Object(n.m)((n,l,o)=>{const i="contact"===l?!e:!("group"===l?a:r),m="contact"===l?t:"group"===l?c:s;d({peerType:l,..."silent"===o&&{isSilent:!n.target.checked,shouldShowPreviews:m},..."showPreviews"===o&&{shouldShowPreviews:n.target.checked,isSilent:i}})},[s,r,c,a,t,e,d]),u=Object(n.m)(e=>{i({isSilent:!e.target.checked})},[i]),h=Object(F.a)();return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("AutodownloadPrivateChats")),n.a.createElement(aa.a,{label:h("NotificationsForPrivateChats"),subLabel:h(e?"NotificationsEnabled":"NotificationsDisabled"),checked:e,onChange:e=>{m(e,"contact","silent")}}),n.a.createElement(aa.a,{label:h("MessagePreview"),subLabel:h(t?"PreviewEnabled":"PreviewDisabled"),checked:t,onChange:e=>{m(e,"contact","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("FilterGroups")),n.a.createElement(aa.a,{label:h("NotificationsForGroups"),subLabel:h(a?"NotificationsEnabled":"NotificationsDisabled"),checked:a,onChange:e=>{m(e,"group","silent")}}),n.a.createElement(aa.a,{label:h("MessagePreview"),subLabel:h(c?"PreviewEnabled":"PreviewDisabled"),checked:c,onChange:e=>{m(e,"group","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("FilterChannels")),n.a.createElement(aa.a,{label:h("NotificationsForChannels"),subLabel:h(r?"NotificationsEnabled":"NotificationsDisabled"),checked:r,onChange:e=>{m(e,"broadcast","silent")}}),n.a.createElement(aa.a,{label:h("MessagePreview"),subLabel:h(s?"PreviewEnabled":"PreviewDisabled"),checked:s,onChange:e=>{m(e,"broadcast","showPreviews")}})),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:h.isRtl?"rtl":void 0},h("PhoneOther")),n.a.createElement(aa.a,{label:h("ContactJoined"),checked:l,onChange:u})))}));var Ba=Object(n.h)(Object(c.h)(e=>{const{settings:{byKey:{hasPassword:t},privacy:a},blocked:n,activeSessions:c}=e;return{hasPassword:t,blockedCount:n.totalCount,sessionsCount:c.length,visibilityPrivacyPhoneNumber:a.phoneNumber&&a.phoneNumber.visibility,visibilityPrivacyLastSeen:a.lastSeen&&a.lastSeen.visibility,visibilityPrivacyProfilePhoto:a.profilePhoto&&a.profilePhoto.visibility,visibilityPrivacyForwarding:a.forwards&&a.forwards.visibility,visibilityPrivacyGroupChats:a.chatInvite&&a.chatInvite.visibility}},(e,t)=>Object(u.l)(t,["loadBlockedContacts","loadAuthorizations","loadPrivacySettings"]))(({onScreenSelect:e,hasPassword:t,blockedCount:a,sessionsCount:c,visibilityPrivacyPhoneNumber:r,visibilityPrivacyLastSeen:l,visibilityPrivacyProfilePhoto:o,visibilityPrivacyForwarding:i,visibilityPrivacyGroupChats:d,loadPrivacySettings:m,loadBlockedContacts:u,loadAuthorizations:h})=>{Object(n.n)(()=>{u(),h(),m()},[u,h,m]);const b=Object(F.a)();function g(e){switch(e){case"everybody":return b("P2PEverybody");case"contacts":return b("P2PContacts");case"nobody":return b("P2PNobody")}}return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item pt-3"},n.a.createElement(Ee.a,{icon:"delete-user",narrow:!0,onClick:()=>e(s.m.PrivacyBlockedUsers)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("BlockedUsers")),a>0&&n.a.createElement("span",{className:"subtitle",dir:"auto"},b("Users",a)))),n.a.createElement(Ee.a,{icon:"lock",narrow:!0,onClick:()=>e(t?s.m.TwoFaEnabled:s.m.TwoFaDisabled)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("TwoStepVerification")),n.a.createElement("span",{className:"subtitle",dir:"auto"},b(t?"PasswordOn":"PasswordOff")))),n.a.createElement(Ee.a,{icon:"active-sessions",narrow:!0,onClick:()=>e(s.m.PrivacyActiveSessions)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("SessionsTitle")),c>0&&n.a.createElement("span",{className:"subtitle",dir:"auto"},1===c?"1 session":c+" sessions")))),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:b.isRtl?"rtl":void 0},b("PrivacyTitle")),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyPhoneNumber)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyPhoneTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(r)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyLastSeen)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("LastSeenTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(l)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyProfilePhoto)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyProfilePhotoTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(o)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyForwarding)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("PrivacyForwardsTitle")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(i)))),n.a.createElement(Ee.a,{narrow:!0,onClick:()=>e(s.m.PrivacyGroupChats)},n.a.createElement("div",{className:"multiline-menu-item"},n.a.createElement("span",{className:"title"},b("WhoCanAddMe")),n.a.createElement("span",{className:"subtitle",dir:"auto"},g(d))))))})),xa=a(14);var Ua=Object(n.h)(Object(c.h)(e=>({languages:e.settings.byKey.languages,language:e.settings.byKey.language}),(e,t)=>Object(u.l)(t,["loadLanguages","setSettingOption"]))(({languages:e,language:t,loadLanguages:a,setSettingOption:c})=>{const[r,s]=Object(n.r)(t),[l,o,i]=Object(xe.a)();Object(n.n)(()=>{a()},[a]);const d=Object(n.m)(e=>{s(e),o(),Object(xa.c)(e,()=>{i(),c({language:e})})},[o,i,c]),m=Object(n.p)(()=>e?function(e){const t=(window.navigator.language||"en").toLowerCase(),a=t.substr(0,2);return e.map(({langCode:e,nativeName:t,name:a})=>({value:e,label:t,subLabel:a})).sort(e=>!t||e.value!==t&&e.value!==a?0:-1)}(e):void 0,[e]);return n.a.createElement("div",{className:"settings-content settings-item settings-language custom-scroll"},m?n.a.createElement(oa.a,{name:"keyboard-send-settings",options:m,selected:r,loadingOption:l?r:void 0,onChange:d}):n.a.createElement(be.a,null))}));function Ga(e){switch(e){case s.m.PrivacyPhoneNumber:case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return"phoneNumber";case s.m.PrivacyLastSeen:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return"lastSeen";case s.m.PrivacyProfilePhoto:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return"profilePhoto";case s.m.PrivacyForwarding:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return"forwards";case s.m.PrivacyGroupChats:case s.m.PrivacyGroupChatsAllowedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return"chatInvite"}}var qa=Object(n.h)(Object(c.h)((e,{screen:t})=>{let a;const{chats:{byId:n},settings:{privacy:c}}=e;switch(t){case s.m.PrivacyPhoneNumber:a=c.phoneNumber;break;case s.m.PrivacyLastSeen:a=c.lastSeen;break;case s.m.PrivacyProfilePhoto:a=c.profilePhoto;break;case s.m.PrivacyForwarding:a=c.forwards;break;case s.m.PrivacyGroupChats:a=c.chatInvite}return a?{...a,chatsById:n}:{}},(e,t)=>Object(u.l)(t,["setPrivacyVisibility"]))(({screen:e,onScreenSelect:t,visibility:a,allowUserIds:c,allowChatIds:r,blockUserIds:l,blockChatIds:o,chatsById:i,setPrivacyVisibility:d})=>{const m=Object(F.a)(),u=Object(n.p)(()=>{switch(e){case s.m.PrivacyProfilePhoto:case s.m.PrivacyGroupChats:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")}];default:return[{value:"everybody",label:m("P2PEverybody")},{value:"contacts",label:m("P2PContacts")},{value:"nobody",label:m("P2PNobody")}]}},[m,e]),h={shouldShowDenied:"nobody"!==a,shouldShowAllowed:"everybody"!==a},b=Ga(e),g=Object(n.p)(()=>{switch(e){case s.m.PrivacyPhoneNumber:return m("PrivacyPhoneTitle");case s.m.PrivacyLastSeen:return m("LastSeenTitle");case s.m.PrivacyProfilePhoto:return m("PrivacyProfilePhotoTitle");case s.m.PrivacyForwarding:return m("PrivacyForwardsTitle");case s.m.PrivacyGroupChats:return m("WhoCanAddMe");default:return}},[m,e]),p=Object(n.p)(()=>{switch(e){case s.m.PrivacyLastSeen:return m("CustomHelp");default:return}},[m,e]),v=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberAllowedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenAllowedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoAllowedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingAllowedContacts;default:return s.m.PrivacyGroupChatsAllowedContacts}})(),E=(()=>{switch(e){case s.m.PrivacyPhoneNumber:return s.m.PrivacyPhoneNumberDeniedContacts;case s.m.PrivacyLastSeen:return s.m.PrivacyLastSeenDeniedContacts;case s.m.PrivacyProfilePhoto:return s.m.PrivacyProfilePhotoDeniedContacts;case s.m.PrivacyForwarding:return s.m.PrivacyForwardingDeniedContacts;default:return s.m.PrivacyGroupChatsDeniedContacts}})(),O=Object(n.p)(()=>c&&r&&i?r.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),c.length):0,[r,c,i]),f=Object(n.p)(()=>l&&o&&i?o.reduce((e,t)=>e+(i[t]?i[t].membersCount:0),l.length):0,[o,l,i]),j=Object(n.m)(e=>{d({privacyKey:b,visibility:e})},[b,d]);return n.a.createElement("div",{className:"settings-content custom-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header",dir:m.isRtl?"rtl":void 0},g),n.a.createElement(oa.a,{name:"visibility-"+b,options:u,onChange:j,selected:a}),p&&n.a.createElement("p",{className:"settings-item-description-larger",dir:m.isRtl?"rtl":void 0},p)),n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:m.isRtl?"rtl":void 0},m("PrivacyExceptions")),h.shouldShowAllowed&&n.a.createElement(Ee.a,{narrow:!0,icon:"add-user",onClick:()=>{t(v)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},O>0&&n.a.createElement("span",{className:"date",dir:"auto"},"+",O),n.a.createElement("span",{className:"title"},m("AlwaysShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers")))),h.shouldShowDenied&&n.a.createElement(Ee.a,{narrow:!0,icon:"delete-user",onClick:()=>{t(E)}},n.a.createElement("div",{className:"multiline-menu-item full-size"},f>0&&n.a.createElement("span",{className:"date",dir:"auto"},"−",f),n.a.createElement("span",{className:"title"},m("NeverShareWith")),n.a.createElement("span",{className:"subtitle"},m("EditAdminAddUsers"))))))}));function za(e){return[e.region,e.country].filter(Boolean).join(", ")}function Ha(e){return`${e.deviceModel}${e.deviceModel?", ":""} ${e.platform} ${e.systemVersion}`}var $a=Object(n.h)(Object(c.h)(e=>({activeSessions:e.activeSessions}),(e,t)=>Object(u.l)(t,["loadAuthorizations","terminateAuthorization","terminateAllAuthorizations"]))(({activeSessions:e,loadAuthorizations:t,terminateAuthorization:a,terminateAllAuthorizations:c})=>{const[r,s,l]=Object(xe.a)();Object(n.n)(()=>{t()},[t]);const o=Object(n.m)(e=>{a({hash:e})},[a]),i=Object(n.m)(()=>{l(),c()},[l,c]),d=Object(n.p)(()=>e.find(e=>e.isCurrent),[e]),m=Object(n.p)(()=>e.filter(e=>!e.isCurrent),[e]),u=Object(F.a)();function h(e){return n.a.createElement(Ee.a,{key:e.hash,ripple:!0,narrow:!0,contextActions:[{title:"Terminate",icon:"stop",handler:()=>{o(e.hash)}}]},n.a.createElement("div",{className:"multiline-menu-item full-size",dir:"auto"},n.a.createElement("span",{className:"date"},Object(D.g)(u,1e3*e.dateActive)),n.a.createElement("span",{className:"title"},e.appName),n.a.createElement("span",{className:"subtitle black tight"},Ha(e)),n.a.createElement("span",{className:"subtitle"},e.ip," - ",za(e))))}return n.a.createElement("div",{className:"settings-content custom-scroll"},d&&(g=d,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:u.isRtl?"rtl":void 0},u("AuthSessions.CurrentSession")),n.a.createElement(Ee.a,{narrow:!0,inactive:!0},n.a.createElement("div",{className:"multiline-menu-item",dir:"auto"},n.a.createElement("span",{className:"title",dir:"auto"},g.appName),n.a.createElement("span",{className:"subtitle black tight"},Ha(g)),n.a.createElement("span",{className:"subtitle"},g.ip," - ",za(g)))),n.a.createElement(Ee.a,{className:"destructive mb-0",icon:"stop",ripple:!0,narrow:!0,onClick:s},u("TerminateAllSessions")))),m&&(b=m,n.a.createElement("div",{className:"settings-item"},n.a.createElement("h4",{className:"settings-item-header mb-4",dir:u.isRtl?"rtl":void 0},"Other Sessions"),b.map(h))),m&&n.a.createElement(we.a,{isOpen:r,onClose:l,text:"Are you sure you want to terminate all other sessions?",confirmLabel:"Terminate All Other Sessions",confirmHandler:i,confirmIsDestructive:!0}),";");var b,g}));var _a=Object(n.h)(Object(c.h)(e=>{const{chats:{byId:t},users:{byId:a},blocked:{ids:n}}=e;return{chatsByIds:t,usersByIds:a,blockedIds:n}},(e,t)=>Object(u.l)(t,["unblockContact"]))(({chatsByIds:e,usersByIds:t,blockedIds:a,unblockContact:c})=>{const r=Object(n.m)(e=>{c({contactId:e})},[c]),s=Object(F.a)();return n.a.createElement("div",{className:"settings-fab-wrapper"},n.a.createElement("div",{className:"settings-content infinite-scroll"},n.a.createElement("div",{className:"settings-item"},n.a.createElement("p",{className:"settings-item-description-larger mt-0 mb-2",dir:s.isRtl?"rtl":void 0},s("BlockedUsersInfo"))),n.a.createElement("div",{className:"chat-list custom-scroll"},a&&a.length?n.a.createElement("div",{className:"scroll-container"},a.map((a,c)=>function(a,c,o){const i=Object(m.lb)(a),d=i?t[a]:void 0,u=i?void 0:e[a],h=Object(ce.a)("Chat chat-item-clickable blocked-list-item",i?"private":"group");return n.a.createElement(Ee.a,{key:a,className:h,ripple:!0,narrow:!0,contextActions:[{title:"Unblock",icon:"unlock",handler:()=>{r(a)}}],style:`top: ${(o+c)*l.i}px;`},n.a.createElement(x.a,{size:"medium",user:d,chat:u}),n.a.createElement("div",{className:"contact-info",dir:"auto"},n.a.createElement("h3",{dir:"auto"},Object(B.a)((i?Object(m.Z)(d):Object(m.l)(s,u))||"")),d&&d.phoneNumber&&n.a.createElement("div",{className:"contact-phone",dir:"auto"},Object(xt.c)(d.phoneNumber)),d&&!d.phoneNumber&&d.username&&n.a.createElement("div",{className:"contact-username",dir:"auto"},"@",d.username)))}(a,c,0))):a&&!a.length?n.a.createElement("div",{className:"no-results",dir:"auto"},"List is empty"):n.a.createElement(be.a,{key:"loading"}))),n.a.createElement(qt,{isShown:!0,onClick:()=>{},className:"not-implemented",ariaLabel:"Add a blocked user"},n.a.createElement("i",{className:"icon-add"})))})),Va=a(128);var Ka=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Va.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},Object(B.a)(a("EnabledPasswordText"),["br"]))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(Ee.a,{icon:"edit",onClick:()=>t(s.m.TwoFaChangePasswordCurrent)},a("ChangePassword")),n.a.createElement(Ee.a,{icon:"password-off",onClick:()=>t(s.m.TwoFaTurnOff)},a("TurnPasswordOff")),n.a.createElement(Ee.a,{icon:"email",onClick:()=>t(s.m.TwoFaRecoveryEmailCurrentPassword)},a("SetRecoveryEmail"))))})),Wa=a(148),Ya=a(149);var Za=Object(n.h)(({error:e,isLoading:t,expectedPassword:a,placeholder:c="Current Password",hint:r,submitLabel:s,clearError:l,onSubmit:o})=>{const[i,d]=Object(n.r)(""),[m,u]=Object(n.r)(!1),h=Object(n.m)(e=>{a&&e!==a?d("Passwords Should Be Equal"):o(e)},[o,a]),b=Object(n.m)(()=>{l&&l(),d("")},[l]),g=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Wa.a,{isBig:!0,isPasswordVisible:m})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(Ya.a,{error:i||e,hint:r,placeholder:c,submitLabel:s||g("Next"),clearError:b,isLoading:t,isPasswordVisible:m,onChangePasswordVisibility:u,onSubmit:h})))});var Qa=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🔐")}))(({animatedEmoji:e,onStart:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Va.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},a("SetAdditionalPasswordInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(R.a,{onClick:t},a("EditAdminTransferSetPassword"))))}));const Xa=o.g?550:400;var Ja=Object(n.h)(Object(c.h)((e,{icon:t})=>({animatedEmoji:Object(d.c)(e,"email"===t?"💌":"💡")}))(({animatedEmoji:e,type:t="text",isLoading:a,error:c,placeholder:r,shouldConfirm:s,clearError:l,onSubmit:i})=>{const d=Object(n.q)(null),[m,u]=Object(n.r)(""),[h,b,g]=Object(xe.a)(!1);Object(n.n)(()=>{o.l||setTimeout(()=>{d.current.focus()},Xa)},[]);const p=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Va.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement("form",{action:"",onSubmit:e=>{e.preventDefault(),d.current&&i(m)}},n.a.createElement(pe.a,{ref:d,value:m,inputMode:t,label:r,error:c,onChange:e=>{c&&l&&l(),u(e.target.value)}}),m?n.a.createElement(R.a,{type:"submit",isLoading:a,ripple:!0},p("Continue")):n.a.createElement(R.a,{isText:!0,isLoading:a,ripple:!0,onClick:s?b:()=>{i()}},p("YourEmailSkip"))),s&&n.a.createElement(ge.a,{className:"narrow",isOpen:h,title:p("YourEmailSkipWarning"),onClose:g},Object(B.a)(p("YourEmailSkipWarningText"),["br","simple_markdown"]),n.a.createElement("div",{className:"dialog-buttons"},n.a.createElement(R.a,{color:"danger",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:()=>{g(),i()}},p("YourEmailSkip")),n.a.createElement(R.a,{color:"primary",ripple:!0,isText:!0,className:"confirm-dialog-button",onClick:g},p("Cancel"))))))}));var en=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"🥳")}))(({animatedEmoji:e,onScreenSelect:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Va.a,{sticker:e}),n.a.createElement("p",{className:"settings-item-description mb-3",dir:"auto"},a("TwoStepVerificationPasswordSetInfo"))),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(R.a,{onClick:()=>{t(s.m.Privacy)}},a("TwoStepVerificationPasswordReturnSettings"))))}));const tn=o.g?550:400;var an=Object(n.h)(Object(c.h)(e=>({animatedEmoji:Object(d.c)(e,"💌"),codeLength:e.twoFaSettings.waitingEmailCodeLength}))(({animatedEmoji:e,codeLength:t,isLoading:a,error:c,clearError:r,onSubmit:s})=>{const l=Object(n.q)(null),[i,d]=Object(n.r)("");Object(n.n)(()=>{o.l||setTimeout(()=>{l.current.focus()},tn)},[]);const m=Object(F.a)();return n.a.createElement("div",{className:"settings-content two-fa custom-scroll"},n.a.createElement("div",{className:"settings-content-header"},n.a.createElement(Va.a,{sticker:e})),n.a.createElement("div",{className:"settings-item pt-0 no-border"},n.a.createElement(pe.a,{value:i,ref:l,inputMode:"decimal",label:m("YourEmailCode"),error:c,onChange:e=>{c&&r&&r();const a=e.target.value.slice(0,t);a.length===t&&s(a),d(a),e.target.value=a}}),a&&n.a.createElement(be.a,null)))}));var nn=Object(n.h)(Object(c.h)(e=>({...e.twoFaSettings}),(e,t)=>Object(u.l)(t,["updatePassword","updateRecoveryEmail","clearPassword","provideTwoFaEmailCode","checkPassword","clearTwoFaError"]))(({currentScreen:e,state:t,hint:a,isLoading:c,error:r,waitingEmailCodeLength:l,dispatch:o,onScreenSelect:i,updatePassword:d,checkPassword:m,clearTwoFaError:u,updateRecoveryEmail:h,provideTwoFaEmailCode:b,clearPassword:g})=>{Object(n.n)(()=>{l&&(e===s.m.TwoFaNewPasswordEmail?i(s.m.TwoFaNewPasswordEmailCode):e===s.m.TwoFaRecoveryEmail&&i(s.m.TwoFaRecoveryEmailCode))},[e,i,l]);const p=Object(n.m)(()=>{o({type:"reset"}),i(s.m.TwoFaNewPassword)},[o,i]),v=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaNewPasswordConfirm)},[o,i]),E=Object(n.m)(()=>{i(s.m.TwoFaNewPasswordHint)},[i]),O=Object(n.m)(e=>{o({type:"setHint",payload:e}),i(s.m.TwoFaNewPasswordEmail)},[o,i]),f=Object(n.m)(e=>{o({type:"setEmail",payload:e}),d({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),j=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaChangePasswordNew)}})},[m,o,i]),C=Object(n.m)(e=>{o({type:"setPassword",payload:e}),i(s.m.TwoFaChangePasswordConfirm)},[o,i]),y=Object(n.m)(()=>{i(s.m.TwoFaChangePasswordHint)},[i]),k=Object(n.m)(e=>{o({type:"setHint",payload:e}),d({...t,hint:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,d]),N=Object(n.m)(e=>{g({currentPassword:e,onSuccess:()=>{i(s.m.Privacy)}})},[g,i]),I=Object(n.m)(e=>{o({type:"setCurrentPassword",payload:e}),m({currentPassword:e,onSuccess:()=>{i(s.m.TwoFaRecoveryEmail)}})},[m,o,i]),S=Object(n.m)(e=>{o({type:"setEmail",payload:e}),h({...t,email:e,onSuccess:()=>{i(s.m.TwoFaCongratulations)}})},[o,i,t,h]),w=Object(n.m)(e=>{b({code:e})},[b]),P=Object(F.a)();switch(e){case s.m.TwoFaDisabled:return n.a.createElement(Qa,{onStart:p});case s.m.TwoFaNewPassword:return n.a.createElement(Za,{placeholder:P("EnterPassword"),submitLabel:P("Continue"),onSubmit:v});case s.m.TwoFaNewPasswordConfirm:return n.a.createElement(Za,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),submitLabel:P("Continue"),onSubmit:E});case s.m.TwoFaNewPasswordHint:return n.a.createElement(Ja,{icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:O});case s.m.TwoFaNewPasswordEmail:return n.a.createElement(Ja,{icon:"email",type:"email",isLoading:c,error:r,clearError:u,placeholder:P("RecoveryEmailTitle"),shouldConfirm:!0,onSubmit:f});case s.m.TwoFaNewPasswordEmailCode:return n.a.createElement(an,{isLoading:c,error:r,clearError:u,onSubmit:w});case s.m.TwoFaCongratulations:return n.a.createElement(en,{onScreenSelect:i});case s.m.TwoFaEnabled:return n.a.createElement(Ka,{onScreenSelect:i});case s.m.TwoFaChangePasswordCurrent:return n.a.createElement(Za,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:j});case s.m.TwoFaChangePasswordNew:return n.a.createElement(Za,{placeholder:P("PleaseEnterNewFirstPassword"),onSubmit:C});case s.m.TwoFaChangePasswordConfirm:return n.a.createElement(Za,{expectedPassword:t.password,placeholder:P("PleaseReEnterPassword"),onSubmit:y});case s.m.TwoFaChangePasswordHint:return n.a.createElement(Ja,{isLoading:c,error:r,clearError:u,icon:"hint",placeholder:P("PasswordHintPlaceholder"),onSubmit:k});case s.m.TwoFaTurnOff:return n.a.createElement(Za,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:N});case s.m.TwoFaRecoveryEmailCurrentPassword:return n.a.createElement(Za,{isLoading:c,error:r,clearError:u,hint:a,onSubmit:I});case s.m.TwoFaRecoveryEmail:return n.a.createElement(Ja,{icon:"email",type:"email",placeholder:P("RecoveryEmailTitle"),onSubmit:S});case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(an,{isLoading:c,error:r,clearError:u,onSubmit:w});default:return}}));var cn=Object(n.h)(({itemIds:e,selectedIds:t,filterValue:a,filterPlaceholder:c,notFoundText:r,searchInputId:s,isLoading:l,onSelectedIdsChange:o,onFilterChange:i,onLoadMore:d})=>{const u=Object(n.q)(null),h=t.length>10;Object(n.n)(()=>{setTimeout(()=>{requestAnimationFrame(()=>{u.current.focus()})},500)},[]);const b=Object(n.m)(e=>{const a=[...t];a.includes(e)?a.splice(a.indexOf(e),1):a.push(e),o(a),i("")},[t,o,i]),g=Object(n.m)(e=>{const{value:t}=e.currentTarget;i(t)},[i]),[p,v]=Object(ue.a)(d,e,Boolean(a)),E=Object(F.a)();return n.a.createElement("div",{className:"Picker"},n.a.createElement("div",{className:"picker-header custom-scroll",dir:E.isRtl?"rtl":void 0},t.map((e,a)=>n.a.createElement(at.a,{chatOrUserId:e,isMinimized:h&&an.a.createElement(Ee.a,{key:e,className:"chat-item-clickable picker-list-item",onClick:()=>b(e),ripple:!0},n.a.createElement(aa.a,{label:"",checked:t.includes(e)}),Object(m.lb)(e)?n.a.createElement(Oe.a,{userId:e}):n.a.createElement(fe.a,{chatId:e})))):l||!p||p.length?n.a.createElement(be.a,null):n.a.createElement("p",{className:"no-results"},r||"Sorry, nothing found."))});function rn(e,t){const{privacy:a}=e.settings;switch(t){case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyPhoneNumberDeniedContacts:return a.phoneNumber;case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyLastSeenDeniedContacts:return a.lastSeen;case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:return a.profilePhoto;case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyForwardingDeniedContacts:return a.forwards;case s.m.PrivacyGroupChatsDeniedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return a.chatInvite}}var sn=Object(n.h)(Object(c.h)((e,{screen:t})=>{const{chats:{byId:a,listIds:n,orderedPinnedIds:c},currentUserId:r}=e;return{currentUserId:r,chatsById:a,listIds:n.active,orderedPinnedIds:c.active,archivedPinnedIds:c.archived,archivedListIds:n.archived,settings:rn(e,t)}},(e,t)=>Object(u.l)(t,["setPrivacySettings"]))(({currentUserId:e,isAllowList:t,screen:a,settings:c,chatsById:r,listIds:l,orderedPinnedIds:o,archivedListIds:i,archivedPinnedIds:d,setPrivacySettings:u,onScreenSelect:h})=>{const b=Object(F.a)(),g=Object(n.p)(()=>c?t?[...c.allowUserIds,...c.allowChatIds]:[...c.blockUserIds,...c.blockChatIds]:[],[t,c]),[p,v]=Object(n.r)(""),[E,O]=Object(n.r)(!1),[f,j]=Object(n.r)(g),C=Object(n.p)(()=>{const e=l?Object(m.Ab)(r,l,o,"all"):void 0,t=i?Object(m.Ab)(r,i,d,"archived"):void 0;if(e||t)return[...e?[...e.pinnedChats,...e.otherChats]:[],...t?t.otherChats:[]]},[r,l,o,i,d]),y=Object(n.p)(()=>{if(C)return C.filter(t=>(Object(m.lb)(t.id)&&t.id!==e||Object(m.kb)(t))&&(!p||Object(me.a)(Object(m.l)(b,t),p)||g.includes(t.id))).map(({id:e})=>e)},[C,e,b,p,g]),k=Object(n.m)(e=>{j(e),O(!0)},[]),N=Object(n.m)(()=>{u({privacyKey:Ga(a),isAllowList:Boolean(t),contactsIds:f}),h(s.m.Privacy)},[t,f,h,a,u]);return n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(cn,{itemIds:y||[],selectedIds:f,filterValue:p,filterPlaceholder:b(t?"AlwaysShareWithPlaceholder":"NeverShareWithPlaceholder"),searchInputId:"new-group-picker-search",onSelectedIdsChange:k,onFilterChange:v}),n.a.createElement(qt,{isShown:E,onClick:N,ariaLabel:b(t?"AlwaysShareWithTitle":"NeverShareWithTitle")},n.a.createElement("i",{className:"icon-arrow-right"})))}));a(278);const ln=Object.keys(s.m).length/2;var on=Object(n.h)(({currentScreen:e,onScreenSelect:t,onReset:a})=>{const[c,r]=It(Tt,At),[l,i]=It(Dt,Rt),d=Object(n.m)(()=>{e!==s.m.FoldersCreateFolder&&e!==s.m.FoldersEditFolder||setTimeout(()=>{r({type:"reset"})},200),e!==s.m.FoldersIncludedChats&&e!==s.m.FoldersExcludedChats?a():"create"===c.mode?t(s.m.FoldersCreateFolder):t(s.m.FoldersEditFolder)},[c.mode,r,e,a,t]),m=Object(n.m)(()=>{r({type:"saveFilters"}),d()},[r,d]);function u(){return n.a.createElement(n.a.Fragment,null,n.a.createElement(Bt,{currentScreen:e,onReset:d,onSaveFilter:m,editedFolderId:c.folderId}),function(){switch(e){case s.m.Main:return n.a.createElement(Ut,{onScreenSelect:t});case s.m.EditProfile:return n.a.createElement(Kt,null);case s.m.General:return n.a.createElement(va,{onScreenSelect:t});case s.m.Notifications:return n.a.createElement(Da,null);case s.m.Privacy:return n.a.createElement(Ba,{onScreenSelect:t});case s.m.Language:return n.a.createElement(Ua,null);case s.m.GeneralChatBackground:return n.a.createElement(Ma,{onScreenSelect:t});case s.m.GeneralChatBackgroundColor:return n.a.createElement(Ra,{onScreenSelect:t});case s.m.PrivacyActiveSessions:return n.a.createElement($a,null);case s.m.PrivacyBlockedUsers:return n.a.createElement(_a,null);case s.m.PrivacyPhoneNumber:case s.m.PrivacyLastSeen:case s.m.PrivacyProfilePhoto:case s.m.PrivacyForwarding:case s.m.PrivacyGroupChats:return n.a.createElement(qa,{screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberAllowedContacts:case s.m.PrivacyLastSeenAllowedContacts:case s.m.PrivacyProfilePhotoAllowedContacts:case s.m.PrivacyForwardingAllowedContacts:case s.m.PrivacyGroupChatsAllowedContacts:return n.a.createElement(sn,{isAllowList:!0,screen:e,onScreenSelect:t});case s.m.PrivacyPhoneNumberDeniedContacts:case s.m.PrivacyLastSeenDeniedContacts:case s.m.PrivacyProfilePhotoDeniedContacts:case s.m.PrivacyForwardingDeniedContacts:case s.m.PrivacyGroupChatsDeniedContacts:return n.a.createElement(sn,{screen:e,onScreenSelect:t});case s.m.Folders:case s.m.FoldersCreateFolder:case s.m.FoldersEditFolder:case s.m.FoldersIncludedChats:case s.m.FoldersExcludedChats:return n.a.createElement(ra,{currentScreen:e,state:c,dispatch:r,onScreenSelect:t,onReset:d});case s.m.TwoFaDisabled:case s.m.TwoFaNewPassword:case s.m.TwoFaNewPasswordConfirm:case s.m.TwoFaNewPasswordHint:case s.m.TwoFaNewPasswordEmail:case s.m.TwoFaNewPasswordEmailCode:case s.m.TwoFaCongratulations:case s.m.TwoFaEnabled:case s.m.TwoFaChangePasswordCurrent:case s.m.TwoFaChangePasswordNew:case s.m.TwoFaChangePasswordConfirm:case s.m.TwoFaChangePasswordHint:case s.m.TwoFaTurnOff:case s.m.TwoFaRecoveryEmailCurrentPassword:case s.m.TwoFaRecoveryEmail:case s.m.TwoFaRecoveryEmailCode:return n.a.createElement(nn,{currentScreen:e,state:l,dispatch:i,onScreenSelect:t});default:return}}())}return n.a.createElement(T.a,{id:"Settings",name:o.g?"slide-layers":"push-slide",activeKey:e,renderCount:ln},u)});const dn=Object(_.g)(e=>e(),6e4,!0);var mn=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users;return{usersById:a,contactIds:t}},(e,t)=>Object(u.l)(t,["loadContactList","openChat"]))(({filter:e,usersById:t,contactIds:a,loadContactList:c,openChat:r})=>{Object(n.n)(()=>{dn(()=>{c()})});const s=Object(n.m)(e=>{r({id:e})},[r]),l=Object(n.p)(()=>{if(!a)return;const n=e?a.filter(a=>{const n=t[a];if(!n)return!1;const c=Object(m.Z)(n);return c&&Object(me.a)(c,e)}):a;return Object(m.Eb)(n,t)},[e,t,a]),[i,d]=Object(ue.a)(void 0,l,Boolean(e));return n.a.createElement(ve.a,{items:i,onLoadMore:d,className:"chat-list custom-scroll"},i&&i.length?i.map(e=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable",onClick:()=>s(e),ripple:!o.g},n.a.createElement(Oe.a,{userId:e,forceShowSelf:!0,avatarSize:"large"}))):i&&!i.length?n.a.createElement("p",{className:"no-results",key:"no-results",dir:"auto"},e.length?"No contacts matched your search.":"Contact list is empty."):n.a.createElement(be.a,{key:"loading"}))}));const un=Object(_.g)(e=>e(),6e4,!0);var hn=Object(n.h)(Object(c.h)(e=>{const{userIds:t}=e.contactList||{},{byId:a}=e.users,{byId:n}=e.chats,{currentUserId:c}=e,{query:r,fetchingStatus:s,globalResults:l,localResults:o}=e.globalSearch,{userIds:i}=l||{},{userIds:d}=o||{};return{currentUserId:c,usersById:a,chatsById:n,localContactIds:t,searchQuery:r,isSearching:s&&s.chats,globalUserIds:i,localUserIds:d}},(e,t)=>Object(u.l)(t,["loadContactList","setGlobalSearchQuery"]))(({isChannel:e,selectedMemberIds:t,onSelectedMemberIdsChange:a,onNextStep:c,onReset:r,currentUserId:s,usersById:l,chatsById:o,localContactIds:i,searchQuery:d,isSearching:h,localUserIds:b,globalUserIds:g,loadContactList:p,setGlobalSearchQuery:v})=>{Object(n.n)(()=>{un(()=>{p()})});const E=Object(n.m)(e=>{v({query:e})},[v]),O=Object(n.p)(()=>{const e=i?Object(m.Db)(i.filter(e=>e!==s),o):[];if(!d)return e;const a=e.filter(e=>{const t=l[e];if(!t)return!1;const a=Object(m.Z)(t);return a&&Object(me.a)(a,d)});return Object(m.Db)(Object(u.o)([...a,...b||[],...g||[]]),o,!1,t)},[i,d,b,g,l,o,t,s]),f=Object(n.m)(()=>{(t.length||e)&&(v({query:""}),c())},[t.length,e,v,c]),j=Object(F.a)();return n.a.createElement("div",{className:"NewChat step-1"},n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:r,ariaLabel:"Return to Chat List"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,j("GroupAddMembers"))),n.a.createElement("div",{className:"NewChat-inner step-1"},n.a.createElement(cn,{itemIds:O,selectedIds:t,filterValue:d,filterPlaceholder:j("SendMessageTo"),searchInputId:"new-group-picker-search",isLoading:h,onSelectedIdsChange:a,onFilterChange:E}),n.a.createElement(qt,{isShown:Boolean(t.length||e),onClick:f,ariaLabel:e?"Continue To Channel Info":"Continue To Group Info"},n.a.createElement("i",{className:"icon-arrow-right"}))))}));var bn=Object(n.h)(Object(c.h)(e=>{const{progress:t,error:a}=e.chatCreation||{};return{creationProgress:t,creationError:a}},(e,t)=>Object(u.l)(t,["createGroupChat","createChannel"]))(({isChannel:e,memberIds:t,onReset:a,creationProgress:c,creationError:r,createGroupChat:l,createChannel:o})=>{const i=Object(F.a)(),[d,m]=Object(n.r)(""),[u,h]=Object(n.r)(""),[b,g]=Object(n.r)(),[p,v]=Object(n.r)(),E=c===s.a.InProgress,O=Object(n.m)(e=>{const{value:t}=e.currentTarget,a=t.replace(/^\s+/,"");m(a),a!==t&&(e.currentTarget.value=a)},[]),f=Object(n.m)(e=>{h(e.currentTarget.value)},[]),j=Object(n.m)(()=>{d.length?t.length>199?v("Sorry, creating supergroups is not yet supported"):l({title:d,photo:b,memberIds:t}):v("Chat title can't be empty")},[d,t,l,b,"Chat title can't be empty","Sorry, creating supergroups is not yet supported"]),C=Object(n.m)(()=>{d.length?o({title:d,about:u,photo:b,memberIds:t}):v("Channel title can't be empty")},[d,o,u,b,t,"Channel title can't be empty"]);Object(n.n)(()=>{c===s.a.Complete&&a(!0)},[c,a]);const y=r||("Chat title can't be empty"!==p&&"Channel title can't be empty"!==p?p:void 0);return n.a.createElement("div",{className:"NewChat"},n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:()=>a(),ariaLabel:"Return to member selection"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,i(e?"NewChannel":"NewGroup"))),n.a.createElement("div",{className:"NewChat-inner step-2"},n.a.createElement(Gt.a,{onChange:g,title:i("AddPhoto")}),n.a.createElement(pe.a,{value:d,onChange:O,label:i(e?"EnterChannelName":"GroupName"),error:"Chat title can't be empty"===p||"Channel title can't be empty"===p?p:void 0}),e&&n.a.createElement(n.a.Fragment,null,n.a.createElement(pe.a,{value:u,onChange:f,label:i("DescriptionOptionalPlaceholder")}),n.a.createElement("p",{className:"note"},i("DescriptionInfo"))),y&&n.a.createElement("p",{className:"error"},y),t.length>0&&n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",{className:"chat-members-heading"},i("GroupInfo.ParticipantCount",t.length,"i")),n.a.createElement("div",{className:"chat-members-list custom-scroll"},t.map(e=>n.a.createElement(Ee.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Oe.a,{userId:e})))))),n.a.createElement(qt,{isShown:0!==d.length,onClick:e?C:j,disabled:E,ariaLabel:e?i("ChannelIntro.CreateChannel"):"Create Group"},E?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-arrow-right"})))}));a(279);const gn=Object.keys(s.d).length/2;var pn=Object(n.h)(({isChannel:e=!1,content:t,onContentChange:a,onReset:c})=>{const[r,l]=Object(n.r)([]),i=Object(n.m)(()=>{a(e?s.d.NewChannelStep2:s.d.NewGroupStep2)},[e,a]);return n.a.createElement(T.a,{id:"NewChat",name:o.g?"slide-layers":"push-slide",renderCount:gn,activeKey:t},()=>{switch(t){case s.d.NewChannelStep1:case s.d.NewGroupStep1:return n.a.createElement(hn,{isChannel:e,selectedMemberIds:r,onSelectedMemberIdsChange:l,onNextStep:i,onReset:c});case s.d.NewChannelStep2:case s.d.NewGroupStep2:return n.a.createElement(bn,{isChannel:e,memberIds:r,onReset:c});default:return}})}),vn=a(189);a(280);var En=Object(n.h)(({isActive:e,onReset:t})=>{const a=Object(F.a)();return n.a.createElement("div",{className:"ArchivedChats"},n.a.createElement("div",{className:"left-header"},n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:t,ariaLabel:"Return to chat list"},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement("h3",null,a("ArchivedChats"))),n.a.createElement(vn.a,{folderType:"archived",noChatsText:"Archive is empty.",isActive:e}))});const On={Down:!0,ArrowDown:!0,Up:!0,ArrowUp:!0,Left:!0,ArrowLeft:!0,Right:!0,ArrowRight:!0," ":!0,PageUp:!0,PageDown:!0,End:!0,Home:!0,Tab:!0},fn=e=>{e.preventDefault()};function jn(e){On[e.key]&&fn(e)}function Cn(){document.addEventListener("wheel",fn,{passive:!1}),window.ontouchmove=fn,document.onkeydown=jn}function yn(){document.removeEventListener("wheel",fn),window.ontouchmove=null,document.onkeydown=null}var kn=a(54),Nn=a(153);function In(e,t){return e?"lng_context_copy_selected":t?"lng_context_copy_text":"Copy"}var Sn=a(173),wn=a(53);a(281);var Pn=({isOpen:e,message:t,anchor:a,canSendNow:c,canReschedule:s,canReply:l,canEdit:o,canPin:i,canUnpin:d,canDelete:u,canForward:h,canFaveSticker:b,canUnfaveSticker:g,canCopy:p,canCopyLink:v,canSelect:E,onReply:O,onEdit:f,onPin:C,onUnpin:y,onForward:k,onDelete:N,onFaveSticker:I,onUnfaveSticker:S,onSelect:w,onSend:P,onReschedule:M,onClose:L,onCloseAnimationEnd:A,onCopyLink:T})=>{Object(n.n)(()=>{Object(j.b)(200)},[e]);const R=function(e,t,a){const n=[],c=Object(m.O)(e),s=Object(m.G)(e),l=Object(m.D)(e,"inline"),o=s&&l&&Nn.a,i=window.getSelection();if(o&&n.push({label:"lng_context_copy_image",handler:()=>{kn.b(l,r.ApiMediaFormat.BlobUrl).then(Nn.b),t&&t()}}),c){const e=Boolean(i&&i.anchorNode&&i.anchorNode.parentNode&&i.anchorNode.parentNode.closest(".Message .content-inner")&&""!==i.toString().replace(/(?:\r\n|\r|\n)/g,""));n.push({label:In(e,o),handler:()=>{const a=e&&i?i.toString():c;Object(Nn.c)(a),t&&t()}})}return a&&n.push({label:"lng_context_copy_message_link",handler:()=>{a(),t&&t()}}),n}(t,L,v?T:void 0),D=Object(n.m)(()=>document.querySelector(`.active > .MessageList div[data-message-id="${t.id}"]`),[t.id]),B=Object(n.m)(()=>document.querySelector(".active > .MessageList"),[]),x=Object(n.m)(()=>document.querySelector(".MessageContextMenu .bubble"),[]),{positionX:U,positionY:G,style:q}=Object(Sn.a)(a,D,B,x,10,document.querySelector(".MiddleHeader").offsetHeight),H=Object(F.a)();return n.a.createElement(wn.a,{isOpen:e,positionX:U,positionY:G,style:q,className:"MessageContextMenu fluid",onClose:L,onCloseAnimationEnd:A},c&&n.a.createElement(z.a,{icon:"send-outline",onClick:P},H("MessageScheduleSend")),s&&n.a.createElement(z.a,{icon:"schedule",onClick:M},H("MessageScheduleEditTime")),l&&n.a.createElement(z.a,{icon:"reply",onClick:O},H("Reply")),o&&n.a.createElement(z.a,{icon:"edit",onClick:f},H("Edit")),b&&n.a.createElement(z.a,{icon:"favorite",onClick:I},H("AddToFavorites")),g&&n.a.createElement(z.a,{icon:"favorite",onClick:S},H("Stickers.RemoveFromFavorites")),p&&R.map(e=>n.a.createElement(z.a,{key:e.label,icon:"copy",onClick:e.handler},H(e.label))),i&&n.a.createElement(z.a,{icon:"pin",onClick:C},H("DialogPin")),d&&n.a.createElement(z.a,{icon:"unpin",onClick:y},H("DialogUnpin")),h&&n.a.createElement(z.a,{icon:"forward",onClick:k},H("Forward")),E&&n.a.createElement(z.a,{icon:"select",onClick:w},H("Common.Select")),u&&n.a.createElement(z.a,{destructive:!0,icon:"delete",onClick:N},H("Delete")))};var Mn=Object(n.h)(Object(c.h)((e,{message:t,messageListType:a})=>{const{threadId:n}=Object(d.y)(e)||{},{noOptions:c,canReply:r,canPin:s,canUnpin:l,canDelete:o,canEdit:i,canForward:m,canFaveSticker:u,canUnfaveSticker:h,canCopy:b,canCopyLink:g,canSelect:p}=n&&Object(d.b)(e,t,n)||{},v="pinned"===a,E="scheduled"===a;return{noOptions:c,canSendNow:E,canReschedule:E,canReply:!v&&!E&&r,canPin:!E&&s,canUnpin:!E&&l,canDelete:o,canEdit:!v&&i,canForward:!E&&m,canFaveSticker:!E&&u,canUnfaveSticker:!E&&h,canCopy:b,canCopyLink:!E&&g,canSelect:p}},(e,t)=>Object(u.l)(t,["setReplyingToId","setEditingId","pinMessage","openForwardMenu","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink"]))(({isOpen:e,messageListType:t,message:a,album:c,anchor:r,onClose:s,onCloseAnimationEnd:l,noOptions:o,canSendNow:i,canReschedule:d,canReply:m,canPin:u,canUnpin:h,canDelete:b,canEdit:g,canForward:p,canFaveSticker:v,canUnfaveSticker:E,canCopy:O,canCopyLink:f,canSelect:j,setReplyingToId:C,setEditingId:y,pinMessage:k,openForwardMenu:N,faveSticker:I,unfaveSticker:S,toggleMessageSelection:w,sendScheduledMessages:P,rescheduleMessage:M,loadMessageLink:F})=>{const{transitionClassNames:L}=Object(K.a)(e,l,void 0,!1),[A,T]=Object(n.r)(!0),[R,B]=Object(n.r)(!1),[x,U]=Object(n.r)(!1),[G,q,z]=Object(xe.a)(),H=Object(n.m)(()=>{T(!1),B(!0)},[]),$=Object(n.m)(()=>{T(!1),s()},[s]),_=Object(n.m)(()=>{B(!1),s()},[s]),V=Object(n.m)(()=>{U(!1),s()},[s]),W=Object(n.m)(()=>{z(),s()},[z,s]),Y=Object(n.m)(()=>{C({messageId:a.id}),$()},[C,a.id,$]),Z=Object(n.m)(()=>{y({messageId:a.id}),$()},[y,a.id,$]),Q=Object(n.m)(()=>{T(!1),U(!0)},[]),X=Object(n.m)(()=>{k({messageId:a.id,isUnpin:!0}),$()},[k,a.id,$]),J=Object(n.m)(()=>{if($(),c&&c.messages){const e=c.messages.map(({id:e})=>e);N({fromChatId:a.chatId,messageIds:e})}else N({fromChatId:a.chatId,messageIds:[a.id]})},[N,a,$,c]),ee=Object(n.m)(()=>{$(),I({sticker:a.content.sticker})},[$,a.content.sticker,I]),te=Object(n.m)(()=>{$(),S({sticker:a.content.sticker})},[$,a.content.sticker,S]),ae=Object(n.m)(()=>{const e=c&&c.messages?{messageId:a.id,childMessageIds:c.messages.map(({id:e})=>e),withShift:!1}:{messageId:a.id,withShift:!1};w(e),$()},[$,a.id,w,c]),ne=Object(n.m)(()=>{P({chatId:a.chatId,id:a.id}),$()},[$,a.chatId,a.id,P]),ce=Object(n.m)(()=>{T(!1),q()},[q]),re=Object(n.m)(e=>{M({chatId:a.chatId,messageId:a.id,scheduledAt:Math.round(e.getTime()/1e3)})},[a.chatId,a.id,M]),se=Object(n.m)(()=>{F({messageId:a.id,chatId:a.chatId}),$()},[$,F,a.chatId,a.id]);if(Object(n.n)(()=>(Cn(),yn),[]),o)return void $();const le=new Date;return le.setFullYear(le.getFullYear()+1),n.a.createElement("div",{className:["ContextMenuContainer",L].join(" ")},n.a.createElement(Pn,{message:a,isOpen:A,anchor:r,canSendNow:i,canReschedule:d,canReply:m,canDelete:b,canPin:u,canUnpin:h,canEdit:g,canForward:p,canFaveSticker:v,canUnfaveSticker:E,canCopy:O,canCopyLink:f,canSelect:j,onReply:Y,onEdit:Z,onPin:Q,onUnpin:X,onForward:J,onDelete:H,onFaveSticker:ee,onUnfaveSticker:te,onSelect:ae,onSend:ne,onReschedule:ce,onClose:$,onCopyLink:se}),n.a.createElement(Re,{isOpen:R,isSchedule:"scheduled"===t,onClose:_,album:c,message:a}),n.a.createElement(De,{isOpen:x,messageId:a.id,chatId:a.chatId,onClose:V}),n.a.createElement(Ae,{isOpen:G,withTimePicker:!0,selectedAt:1e3*a.date,maxAt:Object(D.k)(le),isFutureMode:!0,onClose:W,onSubmit:re}))}));a(282);var Fn=Object(n.h)(Object(c.h)((e,{fromSticker:t})=>({stickerSet:Object(d.xb)(e,t.stickerSetId)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet","sendMessage"]))(({isOpen:e,fromSticker:t,stickerSet:a,onClose:c,loadStickers:r,toggleStickerSet:s,sendMessage:o})=>{const i=Object(n.q)(null),d=Object(F.a)(),{observe:m}=Object(sa.a)({rootRef:i,throttleMs:200,isDisabled:!e});Object(n.n)(()=>{if(e){const{stickerSetId:e,stickerSetAccessHash:a}=t;r({stickerSetId:e,stickerSetAccessHash:a})}},[e,t,r]);const u=Object(n.m)(e=>{e={...e,isPreloadedGlobally:!0},o({sticker:e}),c()},[c,o]),h=Object(n.m)(()=>{s({stickerSetId:t.stickerSetId}),c()},[t.stickerSetId,c,s]);return n.a.createElement(ge.a,{className:"StickerSetModal",isOpen:e,onClose:c,hasCloseButton:!0,title:a?a.title:d("AccDescrStickerSet")},a&&a.stickers?n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{ref:i,className:"stickers custom-scroll"},a.stickers.map(e=>n.a.createElement(ha,{sticker:e,size:l.xb,observeIntersection:m,onClick:u,clickArg:e}))),n.a.createElement("div",{className:"button-wrapper"},n.a.createElement(R.a,{size:"smaller",fluid:!0,color:a.installedDate?"danger":"primary",onClick:h},d(a.installedDate?"StickerPack.RemoveStickerCount":"StickerPack.AddStickerCount",a.count,"i")))):n.a.createElement(be.a,null))})),Ln=a(122);a(283);var An=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t);return!a||a.isRestricted?{}:{chat:a,isMuted:a.isMuted,isPrivate:Object(m.lb)(a.id),canDeleteChat:Object(m.d)(a)}},(e,t)=>Object(u.l)(t,["updateChatMutedState","enterMessageSelectMode"]))(({chatId:e,isOpen:t,anchor:a,isChannel:c,canSubscribe:r,canSearch:s,canMute:l,canSelect:i,canLeave:d,chat:m,isPrivate:u,isMuted:h,canDeleteChat:b,onSubscribeChannel:g,onSearchClick:p,onClose:v,onCloseAnimationEnd:E,updateChatMutedState:O,enterMessageSelectMode:f})=>{const[j,C]=Object(n.r)(!0),[y,k]=Object(n.r)(!1),{x:N,y:I}=a;Object(K.a)(t,E,void 0,!1);const S=Object(n.m)(()=>{C(!1),k(!0)},[]),w=Object(n.m)(()=>{C(!1),v()},[v]),P=Object(n.m)(()=>{k(!1),v()},[v]),M=Object(n.m)(()=>{O({chatId:e,isMuted:!h}),w()},[e,w,h,O]),L=Object(n.m)(()=>{g(),w()},[w,g]),A=Object(n.m)(()=>{p(),w()},[w,p]),T=Object(n.m)(()=>{f(),w()},[w,f]);Object(n.n)(()=>(Cn(),yn),[]);const R=Object(F.a)();return n.a.createElement(Ln.a,null,n.a.createElement("div",{className:"HeaderMenuContainer"},n.a.createElement(wn.a,{isOpen:j,positionX:"right",style:`left: ${N}px;top: ${I}px;`,onClose:w},o.g&&r&&n.a.createElement(z.a,{icon:c?"channel":"group",onClick:L},R(c?"Subscribe":"Join Group")),o.g&&s&&n.a.createElement(z.a,{icon:"search",onClick:A},R("Search")),l&&n.a.createElement(z.a,{icon:h?"unmute":"mute",onClick:M},R(h?"ChatsUnmute":"ChatsMute")),i&&n.a.createElement(z.a,{icon:"select",onClick:T},R("ReportSelectMessages")),d&&n.a.createElement(z.a,{destructive:!0,icon:"delete",onClick:S},R(u?"Delete":b?"GroupInfo.DeleteAndExit":c?"LeaveChannel":"Group.LeaveGroup"))),m&&n.a.createElement(Ve.a,{isOpen:y,onClose:P,chat:m})))})),Tn=a(154);a(284);const Rn=Object(_.a)(e=>e(),200,!1);var Dn=Object(n.h)(Object(c.h)(e=>{const t=Object(d.r)(e);if(!t)return{};const{query:a,results:n}=Object(d.A)(e)||{},{totalCount:c,foundIds:r}=n||{};return{chat:t,query:a,totalCount:c,foundIds:r,isHistoryCalendarOpen:Boolean(e.historyCalendarSelectedAt)}},(e,t)=>Object(u.l)(t,["setLocalTextSearchQuery","searchTextMessagesLocal","focusMessage","closeLocalTextSearch","openHistoryCalendar"]))(({isActive:e,chat:t,query:a,totalCount:c,foundIds:r,isHistoryCalendarOpen:s,setLocalTextSearchQuery:l,searchTextMessagesLocal:o,focusMessage:i,closeLocalTextSearch:d,openHistoryCalendar:m})=>{const u=Object(n.q)(null),[h,b]=Object(n.r)(0);Object(n.n)(()=>{const{visualViewport:e}=window;if(!e)return;const t=document.getElementById("Main"),a=()=>{const{activeElement:a}=document;if(a&&a===u.current){const{pageTop:a,height:n}=e;t.style.transform=`translateY(${a}px)`,t.style.height=n+"px",document.documentElement.scrollTop=a}else t.style.transform="",t.style.height=""};return e.addEventListener("resize",a),()=>{e.removeEventListener("resize",a)}},[]),Object(n.n)(()=>{t&&r&&r.length?(i({chatId:t.id,messageId:r[r.length-1]}),b(0)):b(-1)},[t,i,r]),Object(n.n)(()=>{Array.from(document.querySelectorAll("input")).forEach(t=>{t.disabled=Boolean(e&&t!==u.current)}),Array.from(document.querySelectorAll("div[contenteditable]")).forEach(t=>{t.contentEditable=e?"false":"true"})},[e]),Object(n.n)(()=>{e||u.current.blur()},[e]),Object(n.o)(()=>{document.querySelector("#MobileSearch input").blur()},[s]);const g=Object(n.m)(e=>{l({query:e}),e.length&&Rn(o)},[o,l]),p=Object(n.m)(()=>{if(t&&r){const e=h+1;i({chatId:t.id,messageId:r[r.length-1-e]}),b(e)}},[t,h,i,r]),v=Object(n.m)(()=>{if(t&&r){const e=h-1;i({chatId:t.id,messageId:r[r.length-1-e]}),b(e)}},[t,h,i,r]);return n.a.createElement("div",{id:"MobileSearch",className:e?"active":""},n.a.createElement("div",{className:"header"},n.a.createElement(R.a,{size:"smaller",round:!0,color:"translucent",onClick:d},n.a.createElement("i",{className:"icon-arrow-left"})),n.a.createElement(Tn.a,{ref:u,value:a,onChange:g})),n.a.createElement("div",{className:"footer"},n.a.createElement("div",{className:"counter"},a?r&&r.length?`${h+1} of ${c}`:r&&!r.length?"No results":"":n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:()=>m({selectedAt:Object(D.k)(Date.now())}),ariaLabel:"Search messages by date"},n.a.createElement("i",{className:"icon-calendar"}))),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:p,disabled:!r||!r.length||h===r.length-1},n.a.createElement("i",{className:"icon-up"})),n.a.createElement(R.a,{round:!0,size:"smaller",color:"translucent",onClick:v,disabled:!r||!r.length||0===h},n.a.createElement("i",{className:"icon-down"}))))})),Bn=a(59),xn=a(190),Un=a(182),Gn=a(179),qn=a(184);function zn(e,t,a=0,n=!1,c=!1,r=!1){const s=e[r?"scrollLeft":"scrollTop"],l=s+e[r?"offsetWidth":"offsetHeight"],o="string"==typeof t?e.querySelectorAll(t):t,{length:i}=o,d=[];let m=!1;for(let e=0;e=s-a&&u<=l+a:i<=l+a&&u>=s-a)d.push(e),m=!0;else if(m&&!n)break}return{allElements:o,visibleIndexes:d}}var Hn=function(e,t,a=!1){const n=e[a?"scrollLeft":"scrollTop"],c=n+e[a?"offsetWidth":"offsetHeight"],r=t[a?"offsetLeft":"offsetTop"],s=r+t[a?"offsetWidth":"offsetHeight"];return r>n&&s{const l=Object(n.q)(null),{shouldRender:o,transitionClassNames:i}=Object(K.a)(e,void 0,void 0,!1),d=Object(n.m)(e=>{if(!s)return-1;const t=s.length;return Object(_n.a)(t,e)},[s]),[m,u]=Object(n.r)(-1),h=Object(n.m)((e,t)=>{t.preventDefault(),u(t=>d(t+e))},[u,d]),b=Object(n.m)((e,t=!1)=>{const a=r&&r[e];a&&c(a,t)},[r,c]),g=Object(n.m)(e=>{if(s&&s.length&&m>-1){const t=s[m];t&&(e.preventDefault(),b(t.userId,!0))}},[s,m,b]);Object(n.n)(()=>e?Object(Ue.a)({onEsc:a,onUp:e=>h(-1,e),onDown:e=>h(1,e),onEnter:g,onTab:g}):void 0,[e,a,h,g]),Object(n.n)(()=>{s&&!s.length&&a()},[s,a]),Object(n.n)(()=>{u(0)},[t]),Object(n.n)(()=>{!function(e,t){const a=t.current;if(!a||e<0)return;const{visibleIndexes:n,allElements:c}=zn(a,".chat-item-clickable",8,!0,!0);if(!c.length||!c[e])return;const r=n[0];if(!n.includes(e)||e===r&&!Hn(a,c[r])){const t=e>n[n.length-1]?"start":"end";Object($n.a)(a,c[e],t,10)}}(m,l)},[m]);const p=Object(f.a)(s&&s.length?s:void 0,o),v=s&&!s.length?p:s;if(!o||v&&!v.length)return;const E=Object(ce.a)("MentionTooltip composer-tooltip custom-scroll",i);return n.a.createElement("div",{className:E,ref:l},v&&v.map(({userId:e},t)=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable scroll-item",onClick:()=>b(e),focus:m===t},n.a.createElement(Oe.a,{userId:e,avatarSize:"small",withUsername:!0}))))}),Kn=a(183);a(286);var Wn=Object(n.h)(({attachments:e,caption:t,canSuggestMembers:a,groupChatMembers:c,currentUserId:r,usersById:s,recentEmojis:o,language:i,onCaptionUpdate:d,addRecentEmoji:m,loadEmojiKeywords:u,onSend:h,onFileAppend:g,onClear:p})=>{const v=Object(n.q)(null),E=Object(f.a)(e),O=e.length?e:E,j=Boolean(e.length),[C,y,k]=Object(xe.a)(),N=O&&O.every(e=>e.quick),I=Object(F.a)(),{isMentionTooltipOpen:S,mentionFilter:w,closeMentionTooltip:P,insertMention:M,mentionFilteredMembers:L}=Object(xn.a)(a&&j,t,d,l.w,c,r,s),{isEmojiTooltipOpen:A,closeEmojiTooltip:T,filteredEmojis:D,insertEmoji:B}=Object(Un.a)(j,t,o,l.w,d);Object(n.n)(()=>j?Object(b.a)(p):void 0,[j,p]);const x=Object(n.m)(()=>{j&&h()},[j,h]),U=Object(n.m)(e=>{e.preventDefault(),k();const{dataTransfer:{files:t}}=e;if(t&&t.length){const e=N?Array.from(t).filter(e=>e.type&&l.l.includes(e.type)):Array.from(t);g(e,!1)}},[N,g,k]);if(!O)return;const G=O.every(e=>e.mimeType.startsWith("image/")),q=O.every(e=>e.mimeType.startsWith("video/"));let z="";return z=I(G?"PreviewSender.SendPhoto":q?"PreviewSender.SendVideo":"PreviewSender.SendFile",O.length,"i"),n.a.createElement(ge.a,{isOpen:j,onClose:p,header:function(){if(O)return n.a.createElement("div",{className:"modal-header-condensed",dir:I.isRtl?"rtl":void 0},n.a.createElement(R.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel attachments",onClick:p},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},z),n.a.createElement(R.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:x},I("Send")))}(),className:"AttachmentModal "+(C?"hovered":"")},n.a.createElement("div",{className:"drop-target",onDragEnter:y,onDrop:U,onDragOver:function(e){e.preventDefault(),e.stopPropagation(),v.current&&window.clearTimeout(v.current)},onDragLeave:e=>{const{relatedTarget:t,target:a}=e;a.matches(".drop-target")&&!t&&(v.current=window.setTimeout(k,150)),a&&a.closest(".AttachmentModal.hovered")||(t&&e.stopPropagation(),k())},"data-attach-description":I("Preview.Dragging.AddItems",10)},N?n.a.createElement("div",{className:"media-wrapper custom-scroll"},O.map(e=>e.mimeType.startsWith("image/")?n.a.createElement("img",{src:e.blobUrl,alt:""}):n.a.createElement("video",{src:e.blobUrl,autoPlay:!0,muted:!0,loop:!0}))):n.a.createElement("div",{className:"document-wrapper custom-scroll"},O.map(e=>n.a.createElement(Gn.a,{name:e.filename,extension:Object(Bn.d)(e.filename,e.mimeType),previewData:e.previewBlobUrl,size:e.size,smaller:!0}))),n.a.createElement("div",{className:"attachment-caption-wrapper"},n.a.createElement(Vn,{isOpen:S,onClose:P,filter:w,onInsertUserName:M,filteredChatMembers:L,usersById:s}),n.a.createElement(Kn.a,{isOpen:A,emojis:D,onClose:T,language:i,onEmojiSelect:B,addRecentEmoji:m,loadEmojiKeywords:u}),n.a.createElement(qn.a,{id:"caption-input-text",html:t,editableInputId:l.w,placeholder:I("Caption"),onUpdate:d,onSend:h,shouldSetFocus:j}))))}),Yn=a(138);a(287);var Zn=Object(n.h)(({isOpen:e,onSend:t,onClear:a})=>{const c=Object(n.q)(null),r=Object(n.q)(null),s=Object(n.q)(null),[l,o]=Object(n.r)(""),[i,d]=Object(n.r)([""]),[m,u]=Object(n.r)(!0),[h,g]=Object(n.r)(!1),[p,v]=Object(n.r)(!1),[E,O]=Object(n.r)(),[f,j]=Object(n.r)(),[C,y]=Object(n.r)(!1),k=Object(F.a)(),N=Object(n.m)(t=>{e&&t.current&&t.current.focus()},[e]);Object(n.n)(()=>e?Object(b.a)(a):void 0,[e,a]),Object(n.n)(()=>{e||(o(""),d([""]),u(!0),g(!1),v(!1),O(""),j(""),y(!1))},[e]),Object(n.n)(()=>N(c),[N,e]),Object(n.o)(()=>{const e=s.current;e&&E!==e.innerHTML&&(e.innerHTML=E)},[E]);const I=Object(n.m)((e=[])=>{d([...e,""]),requestAnimationFrame(()=>{const e=r.current;e&&(e.classList.toggle("overflown",e.scrollHeight>320),e.scrollTo({top:e.scrollHeight,behavior:"smooth"}))})},[]),S=Object(n.m)(()=>{if(y(!1),!e)return;const a=l.trim().substring(0,255),n=i.map(e=>e.trim().substring(0,100)).filter(e=>e.length);if(!a||n.length<2)return o(a),n.length?n.length<2?I(n):d(n):I(),void y(!0);if(p&&(!f||!n[Number(f)]))return void y(!0);const c={summary:{question:a,answers:n.map((e,t)=>({text:e.trim(),option:String(t),...String(t)===f&&{correct:!0}})),...!m&&{isPublic:!0},...h&&{multipleChoice:!0},...p&&{quiz:!0}}};if(p){const{text:e,entities:t}=E&&Object(Yn.a)(E.substring(0,200))||{};c.quiz={correctAnswers:[f],...e&&{solution:e},...t&&{solutionEntities:t}}}t(c)},[e,l,i,p,f,m,h,t,I,E]),w=Object(n.m)((e,t)=>{const a=[...i];a[e]=t,a[a.length-1].trim().length&&a.length<10?I(a):d(a)},[i,I]),P=Object(n.m)(e=>{const t=[...i];t.splice(e,1),d(t),requestAnimationFrame(()=>{r.current&&r.current.classList.toggle("overflown",r.current.scrollHeight>320)})},[i]),M=Object(n.m)(e=>{j(e)},[j]),L=Object(n.m)(e=>{u(e.target.checked)},[]),A=Object(n.m)(e=>{g(e.target.checked)},[]),T=Object(n.m)(e=>{v(e.target.checked)},[]),D=Object(n.m)(e=>{13===e.keyCode&&S()},[S]),B=Object(n.m)(()=>{if(C&&!l.trim().length)return k("lng_polls_choose_question")},[C,k,l]),x=Object(n.m)(e=>{const t=i.map(e=>e.trim()).filter(e=>e.length);if(C&&t.length<2&&!i[e].trim().length)return k("lng_polls_choose_answers")},[C,k,i]);function U(){return i.map((e,t)=>n.a.createElement("div",{className:"option-wrapper"},n.a.createElement(pe.a,{label:t!==i.length-1||10===i.length?k("OptionHint"):k("CreatePoll.AddOption"),error:x(t),value:e,onChange:e=>w(t,e.currentTarget.value),onKeyPress:D}),t!==i.length-1&&n.a.createElement(R.a,{className:"option-remove-button",round:!0,color:"translucent",size:"smaller",ariaLabel:k("Delete"),onClick:()=>P(t)},n.a.createElement("i",{className:"icon-close"}))))}return n.a.createElement(ge.a,{isOpen:e,onClose:a,header:n.a.createElement("div",{className:"modal-header-condensed"},n.a.createElement(R.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:"Cancel poll creation",onClick:a},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("div",{className:"modal-title"},k("NewPoll")),n.a.createElement(R.a,{color:"primary",size:"smaller",className:"modal-action-button",onClick:S},k("Create"))),className:"PollModal"},n.a.createElement(pe.a,{ref:c,label:k("AskAQuestion"),value:l,error:B(),onChange:e=>o(e.currentTarget.value),onKeyPress:D}),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"options-list custom-scroll",ref:r},n.a.createElement("h3",{className:"options-header"},"Options"),C&&function(){const e=i.map(e=>e.trim()).filter(e=>e.length);return p&&(!f||!e[Number(f)])&&n.a.createElement("p",{className:"error"},k("lng_polls_choose_correct"))}(),p?n.a.createElement(oa.a,{name:"correctOption",options:U().map((e,t)=>({value:String(t),label:e,hidden:t===i.length-1})),onChange:M}):U()),n.a.createElement("div",{className:"options-divider"}),n.a.createElement("div",{className:"quiz-mode"},n.a.createElement(aa.a,{label:k("PollAnonymous"),checked:m,onChange:L}),n.a.createElement(aa.a,{label:k("PollMultiple"),checked:h,disabled:p,onChange:A}),n.a.createElement(aa.a,{label:k("PollQuiz"),checked:p,disabled:h,onChange:T}),p&&n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",{className:"options-header"},"Solution"),n.a.createElement("div",{ref:s,className:"form-control",contentEditable:!0,dir:"auto",onChange:e=>O(e.currentTarget.innerHTML)}),n.a.createElement("div",{className:"note"},k("CreatePoll.ExplanationInfo")))))});let Qn;function Xn(e,t,a=250){const c=Object(n.q)(!1);Object(n.n)(()=>{Qn&&(clearTimeout(Qn),Qn=void 0),e&&!o.l&&(Qn=window.setTimeout(()=>{c.current||t()},2*a))},[e,a,t]);return[Object(n.m)(()=>{c.current=!0},[]),Object(n.m)(()=>{c.current=!1,Qn&&(clearTimeout(Qn),Qn=void 0),Qn=window.setTimeout(()=>{c.current||t()},a)},[a,t])]}var Jn=a(65),ec=a(142);a(288);var tc=Object(n.h)(({emoji:e,focus:t,onClick:a})=>{const c=Object(n.m)(t=>{t.preventDefault(),a(e.native,e.id)},[e,a]);return n.a.createElement("div",{className:"EmojiButton "+(t?"focus":""),onMouseDown:c,title:`:${e.names[0]}:`},o.d?n.a.createElement("span",{className:"font-emoji"},e.native):n.a.createElement("img",{src:`./img-apple-64/${e.image}.png`,alt:"",loading:"lazy"}))});var ac=Object(n.h)(({category:e,index:t,allEmojis:a,observeIntersection:c,shouldRender:r,onEmojiSelect:s})=>{const l=Object(n.q)(null);Object(sa.c)(l,c);const{transitionClassNames:i}=Object(K.a)(r,void 0,void 0,"slow"),d=Object(F.a)(),m=o.g?Math.floor((y.a.get().width-8)/44):9,u=44*Math.ceil(e.emojis.length/m);return n.a.createElement("div",{ref:l,key:e.id,id:"emoji-category-"+t,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name",dir:"auto"},d("recent"===e.id?"RecentStickers":"Emoji"+t)),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",i),style:`height: ${u}px;`,dir:d.isRtl?"rtl":void 0},r&&e.emojis.map(e=>{const t=a[e],c="id"in t?t:t[1];return n.a.createElement(tc,{key:c.id,emoji:c,onClick:s})})))});a(289);const nc={recent:"icon-recent",people:"icon-smile",nature:"icon-animals",foods:"icon-eats",activity:"icon-sport",places:"icon-car",objects:"icon-lamp",symbols:"icon-language",flags:"icon-flag"},cc=[];let rc,sc,lc;var oc=Object(n.h)(Object(c.h)(e=>Object(u.l)(e,["recentEmojis"]))(({className:e,onEmojiSelect:t,recentEmojis:c})=>{const r=Object(n.q)(null),s=Object(n.q)(null),[i,d]=Object(n.r)(),[m,u]=Object(n.r)(),[h,b]=Object(n.r)(0),{observe:g}=Object(sa.a)({rootRef:r,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("emoji-category-"))return;const a=Number(t.replace("emoji-category-",""));cc[a]=e.isIntersecting});const t=cc.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&b(t[Math.floor(t.length/2)].index)});Object(We.a)(s,!o.g),Object(n.n)(()=>{if(!i)return;const e=s.current;if(!e)return;const t=42*h-e.offsetWidth/2+21;Object(ec.a)(e,t)},[i,h]);const p=Object(F.a)(),v=Object(n.p)(()=>{if(!i)return He.a;const e=[...i];return c&&c.length&&e.unshift({id:"recent",name:p("RecentStickers"),emojis:c}),e},[i,p,c]);Object(n.n)(()=>{setTimeout(()=>{const e=()=>{d(lc.categories),u(lc.emojis)};lc?e():async function(){rc||(rc=a.e(1).then(a.t.bind(null,314,3)),sc=(await rc).default,lc=Object(Jn.b)(sc));return rc}().then(e)},200)},[]);const E=Object(n.m)(e=>{b(e);const t=document.getElementById("emoji-category-"+e);Object($n.a)(r.current,t,"start",50,800)},[]),O=Object(n.m)((e,a)=>{t(e,a)},[t]),f=Object(ot.a)([],l.T);const j=Object(ce.a)("EmojiPicker",e);return m&&f?n.a.createElement("div",{className:j},n.a.createElement("div",{ref:s,className:"EmojiPicker-header",dir:p.isRtl?"rtl":""},v.map((function(e,t){const a=nc[e.id];return a&&n.a.createElement(R.a,{className:"symbol-set-button "+(t===h?"activated":""),round:!0,faded:!0,color:"translucent",onClick:()=>E(t),ariaLabel:e.name},n.a.createElement("i",{className:a}))}))),n.a.createElement("div",{ref:r,className:"EmojiPicker-main no-selection no-scrollbar"},v.map((e,t)=>n.a.createElement(ac,{category:e,index:t,allEmojis:m,observeIntersection:g,shouldRender:h>=t-1&&h<=t+1,onEmojiSelect:O})))):n.a.createElement("div",{className:j},n.a.createElement(be.a,null))}));const ic=o.g?8:16;var dc=Object(n.h)(({stickerSet:e,loadAndPlay:t,index:a,observeIntersection:c,shouldRender:r,onStickerSelect:s,onStickerUnfave:i})=>{const d=Object(n.q)(null);Object(sa.c)(d,c);const{transitionClassNames:m}=Object(K.a)(r,void 0,void 0,"slow"),u=o.g?Math.floor((y.a.get().width-8)/(l.yb+ic)):5,h=Math.ceil(e.count/u)*(l.yb+ic);return n.a.createElement("div",{ref:d,key:e.id,id:"sticker-set-"+a,className:"symbol-set"},n.a.createElement("p",{className:"symbol-set-name"},e.title),n.a.createElement("div",{className:Object(ce.a)("symbol-set-container",m),style:`height: ${h}px;`},r&&e.stickers&&e.stickers.map(a=>n.a.createElement(ha,{key:a.id,sticker:a,size:l.yb,observeIntersection:c,noAnimate:!t,onClick:s,clickArg:a,onUnfaveClick:"favorite"===e.id?i:void 0}))))});a(290);const mc=[];var uc=Object(n.h)(Object(c.h)(e=>{const{setsById:t,added:a,recent:n,favorite:c}=e.stickers;return{recentStickers:n.stickers,favoriteStickers:c.stickers,stickerSetsById:t,addedSetIds:a.setIds,shouldPlay:e.settings.byKey.shouldLoopStickers}},(e,t)=>Object(u.l)(t,["loadStickerSets","loadRecentStickers","loadFavoriteStickers","loadAddedStickers","addRecentSticker","unfaveSticker"]))(({className:e,loadAndPlay:t,canSendStickers:a,recentStickers:c,favoriteStickers:r,addedSetIds:s,stickerSetsById:o,shouldPlay:i,onStickerSelect:d,loadStickerSets:m,loadRecentStickers:u,loadFavoriteStickers:h,loadAddedStickers:b,addRecentSticker:g,unfaveSticker:p})=>{const v=Object(n.q)(null),E=Object(n.q)(null),[O,f]=Object(n.r)(0),{observe:j}=Object(sa.a)({rootRef:v,throttleMs:200},e=>{e.forEach(e=>{const{id:t}=e.target;if(!t||!t.startsWith("sticker-set-"))return;const a=Number(t.replace("sticker-set-",""));mc[a]=e.isIntersecting});const t=mc.map((e,t)=>({index:t,isIntersecting:e})).filter(({isIntersecting:e})=>e);t.length&&f(t[Math.floor(t.length/2)].index)}),{observe:C}=Object(sa.a)({rootRef:E}),y=Object(F.a)(),k=Boolean(s),N=Object(n.p)(()=>s?[{id:"recent",title:y("RecentStickers"),stickers:c,count:c.length},{id:"favorite",title:y("FavoriteStickers"),stickers:r,count:r.length},...s.map(e=>o[e]).filter(Boolean)]:He.a,[s,y,c,r,o]),I=Object(n.p)(()=>k&&0===N.filter(e=>e.stickers&&e.stickers.length).length,[N,k]);Object(n.n)(()=>{t&&(m(),u(),h())},[t,h,u,m]),Object(n.n)(()=>{s&&s.length&&b()},[s,b]),Object(We.a)(E),Object(n.n)(()=>{if(!k)return;const e=E.current;if(!e)return;const t=52*O-(e.offsetWidth/2-26);Object(ec.a)(e,t)},[k,O]);const S=Object(n.m)(e=>{f(e);const t=document.getElementById("sticker-set-"+e);Object($n.a)(v.current,t,"start",void 0,500)},[]),w=Object(n.m)(e=>{d(e),g({sticker:e})},[g,d]),P=Object(n.m)(e=>{p({sticker:e})},[p]),M=Object(ot.a)([],l.pb);const L=Object(ce.a)("StickerPicker",e);return k&&M&&!I&&a?n.a.createElement("div",{className:L},n.a.createElement("div",{ref:E,className:"StickerPicker-header no-selection no-scrollbar"},N.map((function(e,t){const a=e.stickers&&e.stickers[0],c=Object(ce.a)("symbol-set-button sticker-set-button",t===O&&"activated");return"recent"===e.id||"favorite"===e.id||e.hasThumbnail||!a?n.a.createElement(R.a,{key:e.id,className:c,ariaLabel:e.title,round:!0,faded:"recent"===e.id||"favorite"===e.id,color:"translucent",onClick:()=>S(t)},"recent"===e.id?n.a.createElement("i",{className:"icon-recent"}):"favorite"===e.id?n.a.createElement("i",{className:"icon-favorite"}):e.isAnimated?n.a.createElement(ma,{stickerSet:e,observeIntersection:C}):n.a.createElement(ua,{stickerSet:e,observeIntersection:C})):n.a.createElement(ha,{key:e.id,sticker:a,size:l.zb,title:e.title,className:c,observeIntersection:C,onClick:S,clickArg:t})}))),n.a.createElement("div",{ref:v,className:"StickerPicker-main no-scrollbar"},N.map((e,a)=>n.a.createElement(dc,{key:e.id,stickerSet:e,loadAndPlay:Boolean(i&&t),index:a,observeIntersection:j,shouldRender:O>=a-1&&O<=a+1,onStickerSelect:w,onStickerUnfave:P})))):n.a.createElement("div",{className:L},a?I?n.a.createElement("div",{className:"picker-disabled"},"You have no saved Stickers."):n.a.createElement(be.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending stickers is not allowed in this chat."))}));a(291);function hc(){return(hc=Object.assign||function(e){for(var t=1;t{const s=Object(n.q)(null),l=Object(n.q)(null),o=e.thumbnail&&!!e.thumbnail.dataUri,i="gif"+e.id,d=Object(sa.b)(s,t)&&!a,m=Object(v.a)(i+"?size=m",!d,r.ApiMediaFormat.BlobUrl),u=Object(Sa.a)(e.thumbnail&&e.thumbnail.dataUri,Boolean(m)),h=Object(v.a)(i,!d,r.ApiMediaFormat.BlobUrl),b=Boolean(d&&h),{transitionClassNames:g}=Object(ia.a)(o||m||h,"slow"),{isBuffered:p,bufferingHandlers:E}=Object(W.a)(!0),O=d&&!p;Object(Z.a)(l,[b]);const f=Object(n.m)(()=>c({...e,blobUrl:h}),[c,e,h]),j=Object(ce.a)("GifButton",e.width&&e.height&&e.width({savedGifs:e.gifs.saved.gifs}),(e,t)=>Object(u.l)(t,["loadSavedGifs"]))(({className:e,loadAndPlay:t,canSendGifs:a,savedGifs:c,onGifSelect:r,loadSavedGifs:s})=>{const o=Object(n.q)(null),{observe:i}=Object(sa.a)({rootRef:o,debounceMs:300});Object(n.n)(()=>{t&&s()},[t,s]);const d=Object(ot.a)([],l.pb);return n.a.createElement("div",{ref:o,className:Object(ce.a)("GifPicker no-scrollbar",e)},a?d&&c&&c.length?c.map(e=>n.a.createElement(bc,{key:e.id,gif:e,observeIntersection:i,isDisabled:!t,onClick:r})):d&&c?n.a.createElement("div",{className:"picker-disabled"},"No saved GIFs."):n.a.createElement(be.a,null):n.a.createElement("div",{className:"picker-disabled"},"Sending GIFs is not allowed in this chat."))}));let pc;!function(e){e[e.Emoji=0]="Emoji",e[e.Stickers=1]="Stickers",e[e.GIFs=2]="GIFs"}(pc||(pc={}));const vc=Object.values(pc).filter(e=>"string"==typeof e),Ec={[pc.Emoji]:"icon-smile",[pc.Stickers]:"icon-stickers",[pc.GIFs]:"icon-gifs"};var Oc=Object(n.h)(({activeTab:e,onSwitchTab:t,onRemoveSymbol:a,onSearchOpen:c})=>{const r=Object(F.a)();function s(a){return n.a.createElement(R.a,{className:"symbol-tab-button "+(e===a?"activated":""),onClick:()=>t(a),ariaLabel:vc[a],round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:Ec[a]}))}const l=Object(n.m)(()=>{c(e===pc.Stickers?"stickers":"gifs")},[e,c]);return n.a.createElement("div",{className:"SymbolMenu-footer",onClick:function(e){e.stopPropagation()},dir:r.isRtl?"rtl":void 0},e!==pc.Emoji&&n.a.createElement(R.a,{className:"symbol-search-button",ariaLabel:e===pc.Stickers?"Search Stickers":"Search GIFs",round:!0,faded:!0,color:"translucent",onClick:l},n.a.createElement("i",{className:"icon-search"})),s(pc.Emoji),s(pc.Stickers),s(pc.GIFs),e===pc.Emoji&&n.a.createElement(R.a,{className:"symbol-delete-button",onClick:a,ariaLabel:"Remove Symbol",round:!0,faded:!0,color:"translucent"},n.a.createElement("i",{className:"icon-delete-left"})))});a(293);let fc=!1;var jc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onLoad:a,onClose:c,onEmojiSelect:r,onStickerSelect:s,onGifSelect:l,onRemoveSymbol:i,onSearchOpen:d,addRecentEmoji:m})=>{const[u,h]=Object(n.r)(0),[b,g]=Object(n.r)([]),[p,v]=Xn(e,c),{shouldRender:E,transitionClassNames:O}=Object(K.a)(e,c,!1,!1);!fc&&e&&(fc=!0),Object(n.n)(()=>{a()},[a]),Object(n.o)(()=>{if(o.g)return e&&(document.body.classList.add("enable-symbol-menu-transforms"),document.body.classList.add("is-symbol-menu-open")),()=>{e&&Object(_.b)(()=>{document.body.classList.remove("is-symbol-menu-open"),setTimeout(()=>{document.body.classList.remove("enable-symbol-menu-transforms")},350)})}},[e]);const f=Object(n.q)(b);f.current=b,Object(n.n)(()=>{f.current.length&&(f.current.forEach(e=>{m({emoji:e})}),g([]))},[e,u,m]);const j=Object(n.m)((e,t)=>{g(e=>[...e,t]),r(e)},[r]),C=Object(n.m)(e=>{c(),d(e)},[c,d]),y=Object(F.a)(),{canSendStickers:k,canSendGifs:N}=t;function I(t,a){switch(u){case pc.Emoji:return n.a.createElement(oc,{className:"picker-tab",onEmojiSelect:j});case pc.Stickers:return n.a.createElement(uc,{className:"picker-tab",loadAndPlay:!!k&&(e&&(t||a)),canSendStickers:k,onStickerSelect:s});case pc.GIFs:return n.a.createElement(gc,{className:"picker-tab",loadAndPlay:!!N&&(e&&(t||a)),canSendGifs:N,onGifSelect:l})}}const S=n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"SymbolMenu-main",onClick:function(e){e.stopPropagation()}},fc&&n.a.createElement(T.a,{name:"slide",activeKey:u,renderCount:vc.length},I)),o.g&&n.a.createElement(R.a,{round:!0,faded:!0,color:"translucent",ariaLabel:y("Close"),className:"symbol-close-button",size:"tiny",onClick:c},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(Oc,{activeTab:u,onSwitchTab:h,onRemoveSymbol:i,onSearchOpen:C}));if(o.g){if(!E)return;const e=Object(ce.a)("SymbolMenu mobile-menu",O);return n.a.createElement(Ln.a,null,n.a.createElement("div",{className:e},S))}return n.a.createElement(wn.a,{isOpen:e,positionX:"left",positionY:"bottom",onClose:c,className:"SymbolMenu",onCloseAnimationEnd:c,onMouseEnter:o.l?void 0:p,onMouseLeave:o.l?void 0:v,noCloseOnBackdrop:!o.l},S)});a(294);var Cc=Object(n.h)(({isOpen:e,allowedAttachmentOptions:t,onFileSelect:a,onPollCreate:c,onClose:r})=>{const[s,i]=Xn(e,r),d=Object(n.m)((e,t)=>{const{files:n}=e.target;n&&n.length>0&&a(Array.from(n),t)},[a]),m=Object(n.m)(()=>{Oa(l.l,e=>d(e,!0))},[d]),u=Object(n.m)(()=>{Oa("*",e=>d(e,!1))},[d]),h=Object(F.a)(),{canAttachMedia:b,canAttachPolls:g}=t;return n.a.createElement(wn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:r,className:"AttachMenu fluid",onCloseAnimationEnd:r,onMouseEnter:o.l?void 0:s,onMouseLeave:o.l?void 0:i,noCloseOnBackdrop:!o.l},!b&&n.a.createElement(z.a,{className:"media-disabled",disabled:!0},"Posting media content is not allowed in this group."),b&&n.a.createElement(n.a.Fragment,null,n.a.createElement(z.a,{icon:"photo",onClick:m},h("AttachmentMenu.PhotoOrVideo")),n.a.createElement(z.a,{icon:"document",onClick:u},h("AttachDocument"))),g&&n.a.createElement(z.a,{icon:"poll",onClick:c},h("Poll")))});a(295);var yc=Object(n.h)(Object(c.h)(e=>{const{stickers:t}=e.stickers.forEmoji;return{stickers:t}},(e,t)=>Object(u.l)(t,["clearStickersForEmoji"]))(({isOpen:e,onStickerSelect:t,stickers:a,clearStickersForEmoji:c})=>{const r=Object(n.q)(null),{shouldRender:s,transitionClassNames:i}=Object(K.a)(e,void 0,void 0,!1),d=Object(f.a)(a,!0),m=a||d,{observe:u}=Object(sa.a)({rootRef:r,throttleMs:200});Object(n.n)(()=>e?Object(b.a)(c):void 0,[e,c]);const h=Object(ce.a)("StickerTooltip composer-tooltip custom-scroll",i,!(m&&m.length)&&"hidden");return n.a.createElement("div",{ref:r,className:h,onMouseEnter:o.l?void 0:()=>{document.body.classList.add("no-select")},onMouseLeave:o.l?void 0:()=>{document.body.classList.remove("no-select")}},s&&m?m.map(e=>n.a.createElement(ha,{key:e.id,sticker:e,size:l.yb,observeIntersection:u,onClick:t,clickArg:e})):s?n.a.createElement(be.a,null):void 0)}));a(296);var kc=Object(n.h)(Object(c.h)((e,{messageId:t})=>{const{chatId:a}=Object(d.y)(e)||{};return a?{message:Object(d.k)(e,a,t)}:{}},(e,t)=>Object(u.l)(t,["clickInlineButton"]))(({isOpen:e,message:t,onClose:a,clickInlineButton:c})=>{const[r,s]=Xn(e,a);if(t&&t.keyboardButtons)return n.a.createElement(wn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",onClose:a,className:"KeyboardMenu",onCloseAnimationEnd:a,onMouseEnter:o.l?void 0:r,onMouseLeave:o.l?void 0:s,noCloseOnBackdrop:!o.l},n.a.createElement("div",{className:"content"},t.keyboardButtons.map(e=>n.a.createElement("div",{className:"row"},e.map(e=>n.a.createElement(R.a,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>c({button:e})},e.text))))))}));a(297);var Nc=Object(n.h)(({isOpen:e,onSilentSend:t,onScheduleSend:a,onClose:c,onCloseAnimationEnd:r})=>{const[s,l]=Xn(e,c),i=Object(F.a)();return n.a.createElement(wn.a,{isOpen:e,autoClose:!0,positionX:"right",positionY:"bottom",className:"CustomSendMenu",onClose:c,onCloseAnimationEnd:r,onMouseEnter:o.l?void 0:s,onMouseLeave:o.l?void 0:l,noCloseOnBackdrop:!o.l},t&&n.a.createElement(z.a,{icon:"mute",onClick:t},i("SendWithoutSound")),a&&n.a.createElement(z.a,{icon:"schedule",onClick:a},i("ScheduleMessage")))}),Ic=a(139),Sc=a(164),wc=a(175);a(298);var Pc=Object(n.h)(({isOpen:e,language:t,emojis:a,onClose:c,onEmojiSelect:r,addRecentEmoji:s,loadEmojiKeywords:l})=>{const i=Object(n.q)(null),{shouldRender:d,transitionClassNames:m}=Object(K.a)(e,void 0,void 0,!1),u=Object(wc.a)(a.length?a:void 0,350)||[],[h,b]=Object(n.r)(-1);Object(n.n)(()=>{l({language:t})},[l,t]),Object(n.n)(()=>{b(0)},[a]),Object(n.n)(()=>{!function(e,t){const a=t.current;if(!a)return;const{visibleIndexes:n,allElements:c}=zn(a,".EmojiButton",8,!0,!0,!0);if(!c.length||!c[e])return;const r=n[0];if(!n.includes(e)||e===r&&!Hn(a,c[r],!0)){const t="start"===(e>n[n.length-1]?"start":"end")?44*e:0;Object(ec.a)(a,t)}}(h,i)},[h]);const g=Object(n.m)(e=>{if(!a.length)return-1;const t=a.length;return Object(_n.a)(t,e)},[a]),p=Object(n.m)((e,t)=>{t.preventDefault(),b(t=>g(t+e))},[b,g]),v=Object(n.m)(e=>{if(a.length&&h>-1){const t=a[h];t&&(e.preventDefault(),r(t.native),s({emoji:t.id}))}},[s,a,r,h]);Object(n.n)(()=>e?Object(Ue.a)({onEsc:c,onLeft:e=>p(-1,e),onRight:e=>p(1,e),onEnter:v}):void 0,[p,v,e,c]);const E=Object(ce.a)("EmojiTooltip composer-tooltip custom-scroll-x",m);return n.a.createElement("div",{ref:i,className:E,onMouseEnter:o.l?void 0:()=>{document.body.classList.add("no-select")},onMouseLeave:o.l?void 0:()=>{document.body.classList.remove("no-select")}},d&&u?u.map((e,t)=>n.a.createElement(tc,{key:e.id,emoji:e,focus:h===t,onClick:r})):d?n.a.createElement(be.a,null):void 0)}),Mc=a(171);a(299);var Fc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),n=a&&Object(d.m)(e,a.id);if(!a||!n)return{};const{query:c,results:r}=Object(d.A)(e)||{},{totalCount:s,foundIds:l}=r||{};return{chat:a,messagesById:n,query:c,totalCount:s,foundIds:l}},(e,t)=>Object(u.l)(t,["searchTextMessagesLocal","focusMessage"]))(({chatId:e,threadId:t,chat:a,messagesById:r,query:s,totalCount:l,foundIds:o,searchTextMessagesLocal:i,focusMessage:h})=>{const b=Object(F.a)(),g=Object(n.p)(()=>{if(!(s&&o&&o.length&&r))return He.a;const n=o.map(n=>{const s=r[n];if(!s)return;const l=s.senderId?Object(d.Gb)(Object(c.e)(),s.senderId):void 0;let o;if(a&&Object(m.jb)(a))o=a;else if(s.forwardInfo){const{isChannelPost:e,fromChatId:t}=s.forwardInfo;o=e&&t?Object(d.f)(Object(c.e)(),t):void 0}else o=s.senderId?Object(d.f)(Object(c.e)(),s.senderId):void 0;return{message:s,senderUser:l,senderChat:o,onClick:()=>h({chatId:e,threadId:t,messageId:n})}}).filter(Boolean);return Object(u.k)(n,({message:e})=>e.date,"desc")},[e,t,h,o,a,r,s]),p=Object(n.q)(null),v=Object(he.a)(p,!0,e=>{g&&g[e]&&g[e].onClick()},".ListItem-button",!0);return n.a.createElement(ve.a,{className:"RightSearch custom-scroll",items:g,preloadBackwards:0,onLoadMore:i,noFastList:!0,onKeyDown:v,ref:p},n.a.createElement("p",{className:"helper-text",dir:"auto"},s?0!==l&&g.length?1===l?"1 message found":(g.length&&(l||g.length))+" messages found":b("lng_search_no_results"):b("lng_dlg_search_for_messages")),g.map(({message:e,senderUser:t,senderChat:a,onClick:c})=>{const r=a?Object(m.l)(b,a):Object(m.Z)(t),l=Object(m.N)(b,e);return n.a.createElement(Ee.a,{className:"chat-item-clickable search-result-message m-0",onClick:c},n.a.createElement(x.a,{chat:a,user:t}),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},n.a.createElement("h3",{dir:"auto"},r&&Object(B.a)(r)),n.a.createElement(Mc.a,{message:e})),n.a.createElement("div",{className:"subtitle",dir:"auto"},Object(B.a)(l,["emoji","highlight"],{highlight:s}))))}))})),Lc=a(51);var Ac=Object(n.h)(Object(c.h)((e,{stickerSetId:t})=>({set:Object(d.xb)(e,t),shouldPlay:Object(d.wb)(e)}),(e,t)=>Object(u.l)(t,["loadStickers","toggleStickerSet"]))(({stickerSetId:e,observeIntersection:t,set:a,shouldPlay:c,loadStickers:r,toggleStickerSet:s,isSomeModalOpen:o,onModalToggle:i})=>{const d=Object(F.a)(),m=a&&Boolean(a.installedDate),u=Boolean(a&&a.stickers),[h,b,g]=Object(xe.a)();Object(Lc.a)(()=>{i(h)},[h,i]);const p=Object(n.p)(()=>{if(!a)return[];const e=(a.covers||[]).map(({id:e})=>e),t=a.stickers?a.stickers.filter(({id:t})=>!e.includes(t)):[];return[...a.covers||[],...t].slice(0,5)},[a]);Object(n.n)(()=>{!u&&p.length<5&&r({stickerSetId:e})},[u,p.length,r,e]);const v=Object(n.m)(()=>{s({stickerSetId:e})},[s,e]);if(!a)return;const E=p.length>0;return n.a.createElement("div",{key:a.id,className:"sticker-set",dir:d.isRtl?"rtl":void 0},n.a.createElement("div",{className:"sticker-set-header"},n.a.createElement("div",{className:"title-wrapper"},n.a.createElement("h3",{className:"title",dir:"auto"},a.title),n.a.createElement("p",{className:"count",dir:"auto"},d("Stickers",a.count,"i"))),n.a.createElement(R.a,{className:m?"is-added":void 0,color:"primary",size:"tiny",pill:!0,fluid:!0,onClick:v},d(m?"Stickers.Installed":"Stickers.Install"))),n.a.createElement("div",{className:"sticker-set-main"},!E&&n.a.createElement(L.a,null),E&&p.map(e=>n.a.createElement(ha,{sticker:e,size:l.Ab,observeIntersection:t,noAnimate:!c||h||o,onClick:b}))),E&&n.a.createElement(ga.a,{isOpen:h,fromSticker:p[0],onClose:g}))}));a(300);const Tc=Object(_.g)(e=>e(),6e4,!0);var Rc=Object(n.h)(Object(c.h)(e=>{const t=Object(d.z)(e),{query:a,resultIds:n}=t||{},{featured:c}=e.stickers;return{query:a,featuredIds:c.setIds,resultIds:n}},(e,t)=>Object(u.l)(t,["loadFeaturedStickers"]))(({query:e,featuredIds:t,resultIds:a,loadFeaturedStickers:c})=>{const r=Object(n.q)(null),s=Object(F.a)(),[l,o]=Object(n.r)(!1),{observe:i}=Object(sa.a)({rootRef:r,throttleMs:200});return Object(n.n)(()=>{Tc(()=>{c()})}),n.a.createElement("div",{ref:r,className:"StickerSearch custom-scroll",dir:s.isRtl?"rtl":void 0},function(){if(void 0!==e)return!e&&t?t.map(e=>n.a.createElement(Ac,{key:e,stickerSetId:e,observeIntersection:i,isSomeModalOpen:l,onModalToggle:o})):a?a.length?a.map(e=>n.a.createElement(Ac,{key:e,stickerSetId:e,observeIntersection:i,isSomeModalOpen:l,onModalToggle:o})):n.a.createElement("p",{className:"helper-text",dir:"auto"},"Nothing found."):n.a.createElement(be.a,null)}())}));a(301);var Dc=Object(n.h)(Object(c.h)(e=>{const t=Object(d.s)(e),{query:a,results:n}=t||{},{chatId:c}=Object(d.y)(e)||{},r=c?Object(d.f)(e,c):void 0;return{query:a,results:n,chat:r,isChatWithBot:r?Object(d.O)(e,r):void 0}},(e,t)=>Object(u.l)(t,["searchMoreGifs","sendMessage","setGifSearchQuery"]))(({query:e,results:t,chat:a,isChatWithBot:c,searchMoreGifs:r,sendMessage:s,setGifSearchQuery:l})=>{const i=Object(n.q)(null),{observe:d}=Object(sa.a)({rootRef:i,debounceMs:300}),{canSendGifs:u}=Object(m.c)(a,c),h=Object(n.m)(e=>{u&&s({gif:e}),o.l&&l({query:void 0})},[u,s,l]),b=Object(F.a)();const g=Boolean(void 0!==e&&t&&t.length);return n.a.createElement("div",{className:"GifSearch",dir:b.isRtl?"rtl":void 0},n.a.createElement(ve.a,{ref:i,className:Object(ce.a)("gif-container custom-scroll",g&&"grid"),items:t,itemSelector:".GifButton",preloadBackwards:96,noFastList:!0,onLoadMore:r},function(){if(void 0!==e)return t?t.length?t.map(e=>n.a.createElement(bc,{key:e.id,gif:e,observeIntersection:d,onClick:h})):n.a.createElement("p",{className:"helper-text",dir:"auto"},b("NoGIFsFound")):n.a.createElement(be.a,null)}()))}));a(302);var Bc=Object(n.h)(Object(c.h)((e,{answer:t})=>{const{voters:a,offsets:n}=e.pollResults;return{voters:a&&a[t.option],offset:n&&n[t.option]||""}},(e,t)=>Object(u.l)(t,["loadPollOptionResults","openChat","closePollResults"]))(({chat:e,message:t,answer:a,answerVote:c,totalVoters:r,voters:s,offset:l,loadPollOptionResults:o,openChat:i,closePollResults:d})=>{const m=Object(f.a)(c.votersCount),[u,h]=Object(n.r)(!0),b=Boolean(s),{option:g,text:p}=a,v=Object(F.a)();Object(n.n)(()=>{b&&m===c.votersCount||o({chat:e,messageId:t.id,option:g,offset:l,limit:4,shouldResetVoters:!0})},[c.votersCount,b]);const E=Object(n.m)(()=>{h(!0),o({chat:e,messageId:t.id,option:g,offset:l,limit:50})},[e,o,t.id,l,g]);Object(n.n)(()=>{h(!1)},[s]);const O=Object(n.m)(e=>{i({id:e}),d()},[d,i]);return n.a.createElement("div",{className:"PollAnswerResults"},n.a.createElement("div",{className:"poll-voters"},s?s.map(e=>n.a.createElement(Ee.a,{key:e,className:"chat-item-clickable",onClick:()=>O(e)},n.a.createElement(Oe.a,{avatarSize:"tiny",userId:e,forceShowSelf:!0,noStatusOrTyping:!0}))):n.a.createElement(be.a,null),s&&function(){const e=c.votersCount-s.length;return c.votersCount>4&&e>0&&n.a.createElement(Xt,{count:e,itemName:"voter",isLoading:u,onClick:E})}()),n.a.createElement("div",{className:"answer-head",dir:v.isRtl?"rtl":void 0},n.a.createElement("span",{className:"answer-title",dir:"auto"},p),n.a.createElement("span",{className:"answer-percent",dir:v.isRtl?"auto":void 0},(j=c.votersCount,(C=r)>0?(j/C*100).toFixed():0),"%")));var j,C}));a(303);var xc=Object(n.h)(Object(c.h)(e=>{const{pollResults:{chatId:t,messageId:a},lastSyncTime:n}=e;if(!t||!a)return{};return{chat:Object(d.f)(e,t),message:Object(d.k)(e,t,a),lastSyncTime:n}})(({chat:e,message:t,lastSyncTime:a})=>{const c=Object(F.a)();if(!t||!e)return n.a.createElement(be.a,null);const{summary:r,results:s}=Object(m.H)(t);if(!s.results)return;const l=Object(u.c)(s.results,"option");return n.a.createElement("div",{className:"PollResults",dir:c.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"poll-question",dir:"auto"},r.question),n.a.createElement("div",{className:"poll-results-list custom-scroll"},a&&r.answers.map(a=>n.a.createElement(Bc,{key:`${t.id}-${a.option}`,chat:e,message:t,answer:a,answerVote:l[a.option],totalVoters:s.totalVoters})),!a&&n.a.createElement(be.a,null)))}));a(166);var Uc=Object(n.h)(Object(c.h)((e,{userId:t})=>{const a=Object(d.Gb)(e,t),n=Object(d.f)(e,t),{progress:c}=e.management;return{user:a,chat:n,progress:c}},(e,t)=>Object(u.l)(t,["updateContact","deleteUser","closeManagement","openChat","deleteHistory"]))(({userId:e,user:t,chat:a,progress:c,updateContact:r,deleteUser:l,deleteHistory:o,closeManagement:i,openChat:d})=>{const[m,u,h]=Object(xe.a)(),[b,g]=Object(n.r)(!1),[p,v]=Object(n.r)(),E=Object(F.a)(),O=t&&t.firstName||"",f=t&&t.lastName||"",j=a?a.isMuted:void 0,[C,y]=Object(n.r)(O),[k,N]=Object(n.r)(f),[I,S]=Object(n.r)(!j);Object(n.n)(()=>{S(!j)},[j]),Object(n.n)(()=>{g(!1),h()},[h,e]),Object(n.n)(()=>{y(O),N(f)},[O,f,t]),Object(n.n)(()=>{c===s.f.Complete&&(g(!1),v(void 0),h())},[h,c]);const w=Object(n.m)(e=>{y(e.target.value),g(!0)},[]),P=Object(n.m)(e=>{N(e.target.value),g(!0)},[]),M=Object(n.m)(e=>{S(e.target.checked),g(!0)},[]),A=Object(n.m)(()=>{const t=C.trim(),a=k.trim();t.length||v("Please provide first name"),r({userId:e,isMuted:!I,firstName:t,lastName:a})},[C,k,r,e,I]),T=Object(n.m)(()=>{o({chatId:a.id,shouldDeleteForAll:!1}),l({userId:e}),h(),i(),d({id:void 0})},[a.id,h,i,o,l,d,e]);if(!t)return;const R=c===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Oe.a,{userId:t.id,avatarSize:"jumbo",status:"original name",withFullInfo:!0}),n.a.createElement(pe.a,{id:"user-first-name",label:E("UserInfo.FirstNamePlaceholder"),onChange:w,value:C,error:"Please provide first name"===p?p:void 0}),n.a.createElement(pe.a,{id:"user-last-name",label:E("UserInfo.LastNamePlaceholder"),onChange:P,value:k}),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(aa.a,{checked:I,label:E("Notifications"),subLabel:E(I?"UserInfo.NotificationsEnabled":"UserInfo.NotificationsDisabled"),onChange:M}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:u},E("DeleteContact")))),n.a.createElement(qt,{isShown:b,onClick:A,disabled:R,ariaLabel:E("Save")},R?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:m,onClose:h,text:E("AreYouSureDeleteContact"),confirmLabel:E("DeleteContact"),confirmHandler:T,confirmIsDestructive:!0}))}));var Gc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management,c=Boolean(a.fullInfo&&a.fullInfo.linkedChatId);return{chat:a,progress:n,isBasicGroup:Object(m.ib)(a),hasLinkedChannel:c,canChangeInfo:Object(m.q)(a,"changeInfo"),canBanUsers:Object(m.q)(a,"banUsers")}},(e,t)=>Object(u.l)(t,["togglePreHistoryHidden","updateChat","closeManagement","deleteHistory","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isBasicGroup:c,hasLinkedChannel:l,canChangeInfo:o,canBanUsers:i,onScreenSelect:d,togglePreHistoryHidden:u,updateChat:h,deleteHistory:b,leaveChannel:g,deleteChannel:p,closeManagement:E,openChat:O})=>{const[f,j,C]=Object(xe.a)(),y=t.title,k=t.fullInfo&&t.fullInfo.about||"",[N,I]=Object(n.r)(!1),[S,w]=Object(n.r)(y),[P,M]=Object(n.r)(k),[A,T]=Object(n.r)(),[R,D]=Object(n.r)(),x=Object(m.f)(t),U=Object(v.a)(x,!1,r.ApiMediaFormat.BlobUrl),G=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(I(!1),D(void 0))},[a]);const q=Object(n.m)(()=>{d(s.g.ChatPrivacyType)},[d]),z=Object(n.m)(()=>{d(s.g.Discussion)},[d]),H=Object(n.m)(()=>{d(s.g.GroupPermissions)},[d]),$=Object(n.m)(()=>{d(s.g.ChatAdministrators)},[d]),_=Object(n.m)(e=>{T(e),I(!0)},[]),V=Object(n.m)(e=>{w(e.target.value),I(!0)},[]),K=Object(n.m)(e=>{M(e.target.value),I(!0)},[]),W=Object(n.m)(()=>{const t=S.trim(),a=P.trim();t.length?h({chatId:e,title:t,about:a,photo:A}):D("Group title can't be empty")},[P,e,A,S,h]),Y=Object(n.m)(()=>{d(s.g.GroupMembers)},[d]),Z=Object(n.m)(()=>{if(!t.fullInfo)return;const{isPreHistoryHidden:e}=t.fullInfo;u({chatId:t.id,isEnabled:!e})},[t,u]),Q=Object(n.p)(()=>{if(!t.defaultBannedRights)return 0;let e=["sendMessages","sendMedia","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages"].filter(e=>!t.defaultBannedRights[e]).length;const{sendStickers:a,sendGifs:n}=t.defaultBannedRights;return a||n||(e+=1),e},[t]),X=t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,J=Object(n.m)(()=>{c?b({chatId:t.id,shouldDeleteForAll:!1}):t.isCreator?p({chatId:t.id}):g({chatId:t.id}),C(),E(),O({id:void 0})},[c,t.isCreator,t.id,C,E,b,g,p,O]);if(t.isRestricted)return;const ee=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Gt.a,{currentAvatarBlobUrl:U,onChange:_,disabled:!o}),n.a.createElement(pe.a,{id:"group-title",label:G("GroupName"),onChange:V,value:S,error:"Group title can't be empty"===R?R:void 0,disabled:!o}),n.a.createElement(pe.a,{id:"group-about",className:"mb-2",label:G("DescriptionPlaceholder"),onChange:K,value:P,disabled:!o}),t.isCreator&&n.a.createElement(Ee.a,{icon:"lock",multiline:!0,ripple:!0,onClick:q},n.a.createElement("span",{className:"title"},G("GroupType")),n.a.createElement("span",{className:"subtitle"},t.username?G("TypePublic"):G("TypePrivate"))),l&&n.a.createElement(Ee.a,{icon:"message",multiline:!0,ripple:!0,onClick:z},n.a.createElement("span",{className:"title"},G("LinkedChannel")),n.a.createElement("span",{className:"subtitle"},G("DiscussionUnlink"))),n.a.createElement(Ee.a,{icon:"permissions",multiline:!0,ripple:!0,onClick:H,disabled:!i},n.a.createElement("span",{className:"title"},G("ChannelPermissions")),n.a.createElement("span",{className:"subtitle",dir:"auto"},Q,"/",8)),n.a.createElement(Ee.a,{icon:"admin",multiline:!0,ripple:!0,onClick:$},n.a.createElement("span",{className:"title"},G("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},Object(da.a)(X)))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"group",multiline:!0,ripple:!0,onClick:Y},n.a.createElement("span",{className:"title"},G("GroupMembers")),n.a.createElement("span",{className:"subtitle"},Object(da.a)(t.membersCount))),t.fullInfo&&n.a.createElement("div",{className:"ListItem narrow no-selection"},n.a.createElement(aa.a,{checked:!t.fullInfo.isPreHistoryHidden,label:G("ChatHistory"),onChange:Z,disabled:!i}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},G("DeleteMega")))),n.a.createElement(qt,{isShown:N,onClick:W,disabled:ee,ariaLabel:G("Save")},ee?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:f,onClose:C,textParts:Object(B.a)(c||!t.isCreator?G("AreYouSureDeleteAndExit"):G("AreYouSureDeleteThisChatWithGroup",t.title),["br","simple_markdown"]),confirmLabel:c||!t.isCreator?G("DeleteMega"):G("DeleteGroupForAll"),confirmHandler:J,confirmIsDestructive:!0}))}));var qc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t),currentUserId:e.currentUserId}),(e,t)=>Object(u.l)(t,["updateChatDefaultBannedRights"]))(({onScreenSelect:e,onChatMemberSelect:t,chat:a,currentUserId:c,updateChatDefaultBannedRights:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),h=Object(F.a)(),b=Object(n.m)(()=>{e(s.g.GroupRemovedUsers)},[e]),g=Object(n.m)(()=>{e(s.g.GroupUserPermissionsCreate)},[e]),p=Object(n.m)(a=>{t(a.userId,a.promotedByUserId===c),e(s.g.GroupUserPermissions)},[c,t,e]);Object(n.n)(()=>{o(a&&a.defaultBannedRights||{}),d(!1),setTimeout(()=>{u(!1)},250)},[a]);const v=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),E=Object(n.m)(()=>{a&&(u(!0),r({chatId:a.id,bannedRights:l}))},[a,l,r]),O=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.kickedMembers?a.fullInfo.kickedMembers.length:0,[a]),f=Object(n.p)(()=>a&&a.fullInfo&&a.fullInfo.members?a.fullInfo.members.filter(({bannedRights:e})=>!!e):[],[a]),j=Object(n.m)(e=>{const{bannedRights:t}=e;if(!t||!a)return;const{defaultBannedRights:n}=a;return Object.keys(t).reduce((e,a)=>{if(!t[a]||n&&n[a]||"sendInline"===a||"viewMessages"===a||"sendGames"===a)return e;const c=function(e){switch(e){case"sendMessages":return"UserRestrictionsNoSend";case"sendMedia":return"UserRestrictionsNoSendMedia";case"sendStickers":return"UserRestrictionsNoSendStickers";case"embedLinks":return"UserRestrictionsNoEmbedLinks";case"sendPolls":return"UserRestrictionsNoSendPolls";case"changeInfo":return"UserRestrictionsNoChangeInfo";case"inviteUsers":return"UserRestrictionsInviteUsers";case"pinMessages":return"UserRestrictionsPinMessages";default:return}}(a);if(!c)return e;const r=h(c);return`${e}${e.length?", "+r:r}`},"")},[a,h]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading",dir:"auto"},h("ChannelPermissionsHeader")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendMessages",checked:!l.sendMessages,label:h("UserRestrictionsSend"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendMedia",checked:!l.sendMedia,label:h("UserRestrictionsSendMedia"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:h("UserRestrictionsSendStickers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendPolls",checked:!l.sendPolls,label:h("UserRestrictionsSendPolls"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"embedLinks",checked:!l.embedLinks,label:h("UserRestrictionsEmbedLinks"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"inviteUsers",checked:!l.inviteUsers,label:h("UserRestrictionsInviteUsers"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"pinMessages",checked:!l.pinMessages,label:h("UserRestrictionsPinMessages"),blocking:!0,onChange:v})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!l.changeInfo,label:h("UserRestrictionsChangeInfo"),blocking:!0,onChange:v}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete-user",multiline:!0,ripple:!0,narrow:!0,onClick:b},n.a.createElement("span",{className:"title"},h("ChannelBlockedUsers")),n.a.createElement("span",{className:"subtitle"},O))),n.a.createElement("div",{className:"section"},n.a.createElement("h3",{className:"section-heading",dir:"auto"},h("PrivacyExceptions")),n.a.createElement(Ee.a,{icon:"add-user",ripple:!0,onClick:g},h("ChannelAddException")),f.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable exceptions-member",ripple:!0,onClick:()=>p(e)},n.a.createElement(Oe.a,{userId:e.userId,status:j(e)}))))),n.a.createElement(qt,{isShown:i,onClick:E,ariaLabel:h("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var zc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,usersById:n}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,usersById:t,updateChatMemberBannedRights:a})=>{const c=Object(F.a)(),r=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.kickedMembers?e.fullInfo.kickedMembers:[],[e]),s=Object(n.m)(e=>{if(!e.kickedByUserId)return;const a=t[e.kickedByUserId];return a?c("UserRemovedBy",Object(m.Z)(a)):void 0},[c,t]),l=Object(n.m)(t=>{if(e)return[{title:c("Unblock"),icon:"delete",destructive:!0,handler:()=>a({chatId:e.id,userId:t.userId,bannedRights:{}})}]},[c,e,a]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",dir:c.isRtl?"rtl":void 0},n.a.createElement("p",{className:"text-muted"},c("NoBlockedGroup2")),r.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,contextActions:l(e)},n.a.createElement(Oe.a,{userId:e.userId,status:s(e)}))))))}));var Hc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{progress:n}=e.management;return{chat:a,progress:n,isSignaturesShown:Boolean(a&&a.isSignaturesShown),canChangeInfo:Object(m.q)(a,"changeInfo")}},(e,t)=>Object(u.l)(t,["toggleSignatures","updateChat","closeManagement","leaveChannel","deleteChannel","openChat"]))(({chatId:e,chat:t,progress:a,isSignaturesShown:c,canChangeInfo:l,onScreenSelect:o,updateChat:i,toggleSignatures:d,closeManagement:u,leaveChannel:h,deleteChannel:b,openChat:g})=>{const p=t&&t.title||"",E=t&&t.fullInfo&&t.fullInfo.about||"",O=t&&t.fullInfo&&t.fullInfo.linkedChatId,[f,j,C]=Object(xe.a)(),[y,k]=Object(n.r)(!1),[N,I]=Object(n.r)(p),[S,w]=Object(n.r)(E),[P,M]=Object(n.r)(),[A,T]=Object(n.r)(),R=t&&Object(m.f)(t),D=Object(v.a)(R,!1,r.ApiMediaFormat.BlobUrl),B=Object(F.a)();Object(n.n)(()=>{a===s.f.Complete&&(k(!1),T(void 0))},[a]);const x=t&&t.fullInfo&&t.fullInfo.adminMembers&&t.fullInfo.adminMembers.length||0,U=Object(n.m)(()=>{o(s.g.ChatPrivacyType)},[o]),G=Object(n.m)(()=>{o(s.g.Discussion)},[o]),q=Object(n.m)(()=>{o(s.g.ChatAdministrators)},[o]),z=Object(n.m)(e=>{M(e),k(!0)},[]),H=Object(n.m)(e=>{I(e.target.value),k(!0)},[]),$=Object(n.m)(e=>{w(e.target.value),k(!0)},[]),_=Object(n.m)(()=>{const t=N.trim(),a=S.trim();t.length?i({chatId:e,title:t,about:a,photo:P}):T("Channel title can't be empty")},[S,e,P,N,i]),V=Object(n.m)(()=>{d({chatId:e,isEnabled:!c})},[e,c,d]),K=Object(n.m)(()=>{o(s.g.ChannelSubscribers)},[o]),W=Object(n.m)(()=>{t.isCreator?b({chatId:t.id}):h({chatId:t.id}),C(),u(),g({id:void 0})},[t.isCreator,t.id,C,u,h,b,g]);if(t.isRestricted)return;const Y=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Gt.a,{currentAvatarBlobUrl:D,onChange:z,disabled:!l}),n.a.createElement(pe.a,{id:"channel-title",label:B("EnterChannelName"),onChange:H,value:N,error:"Channel title can't be empty"===A?A:void 0,disabled:!l}),n.a.createElement(pe.a,{id:"channel-about",className:"mb-2",label:B("DescriptionPlaceholder"),onChange:$,value:S,disabled:!l}),t.isCreator&&n.a.createElement(Ee.a,{icon:"lock",ripple:!0,multiline:!0,onClick:U},n.a.createElement("span",{className:"title"},B("ChannelType")),n.a.createElement("span",{className:"subtitle"},t.username?B("TypePublic"):B("TypePrivate"))),n.a.createElement(Ee.a,{icon:"message",multiline:!0,ripple:!0,onClick:G,disabled:!l},n.a.createElement("span",{className:"title"},B("Discussion")),n.a.createElement("span",{className:"subtitle"},B(O?"DiscussionUnlink":"Add"))),n.a.createElement(Ee.a,{icon:"admin",multiline:!0,ripple:!0,onClick:q},n.a.createElement("span",{className:"title"},B("ChannelAdministrators")),n.a.createElement("span",{className:"subtitle"},x)),n.a.createElement("div",{className:"ListItem no-selection narrow"},n.a.createElement(aa.a,{checked:c,label:B("ChannelSignMessages"),onChange:V}))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"group",multiline:!0,ripple:!0,onClick:K},n.a.createElement("span",{className:"title",dir:"auto"},B("ChannelSubscribers")),n.a.createElement("span",{className:"subtitle",dir:"auto"},B("Subscribers",t.membersCount,"i")))),n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},t.isCreator?B("ChannelDelete"):B("LeaveChannel")))),n.a.createElement(qt,{isShown:y,onClick:_,disabled:Y,ariaLabel:B("Save")},Y?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:f,onClose:C,text:t.isCreator?B("ChannelDeleteAlert"):B("ChannelLeaveAlert"),confirmLabel:t.isCreator?B("ChannelDelete"):B("LeaveChannel"),confirmHandler:W,confirmIsDestructive:!0}))})),$c=a(57);var _c=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{isUsernameAvailable:n}=Object(d.Z)(e,t);return{chat:a,isChannel:Object(m.jb)(a),progress:e.management.progress,isUsernameAvailable:n}},(e,t)=>Object(u.l)(t,["checkPublicLink","updatePublicLink","updatePrivateLink"]))(({chat:e,isChannel:t,progress:a,isUsernameAvailable:c,checkPublicLink:r,updatePublicLink:l,updatePrivateLink:o})=>{const i=Boolean(e.username),d=e.fullInfo&&e.fullInfo.inviteLink,[m,u]=Object(n.r)(i?"public":"private"),[h,b]=Object(n.r)(),[g,p,v]=Object(xe.a)(),E="public"===m&&h&&c||"private"===m&&i;Object(n.n)(()=>{m&&!d&&o()},[m,d,o]);const O=Object(n.m)(e=>{u(e)},[]),f=Object(n.m)(()=>{l({username:"public"===m?h:""})},[m,l,h]),j=Object(n.m)(()=>{v(),o()},[v,o]),C=Object(F.a)(),y=t?"Channel":"Mega",k=t?"Channel":"Group",N=[{value:"private",label:C(y+"Private"),subLabel:C(y+"PrivateInfo")},{value:"public",label:C(y+"Public"),subLabel:C(y+"PublicInfo")}],I=a===s.f.InProgress;return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",dir:C.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"section-heading"},C(k+"Type")),n.a.createElement(oa.a,{selected:m,name:"channel-type",options:N,onChange:O})),"private"===m?n.a.createElement("div",{className:"section",dir:C.isRtl?"rtl":void 0},d?n.a.createElement(n.a.Fragment,null,n.a.createElement($c.a,{url:d,className:"group-link",text:d}),n.a.createElement("p",{className:"section-info",dir:C.isRtl?"rtl":void 0},C(y+"PrivateLinkHelp")),n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:p},C("RevokeLink")),n.a.createElement(we.a,{isOpen:g,onClose:v,text:C("RevokeAlert"),confirmLabel:C("RevokeButton"),confirmHandler:j,confirmIsDestructive:!0})):n.a.createElement(be.a,null)):n.a.createElement("div",{className:"section no-border"},n.a.createElement(_t,{asLink:!0,currentUsername:e.username,isLoading:I,isUsernameAvailable:c,checkUsername:r,onChange:b}),n.a.createElement("p",{className:"section-info",dir:"auto"},C(k+".Username.CreatePublicLinkHelp")))),n.a.createElement(qt,{isShown:E,disabled:I,ariaLabel:C("Save"),onClick:f},I?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})))}));var Vc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{forDiscussionIds:n,byId:c}=e.chats;return{chat:a,chatsByIds:c,forDiscussionIds:n,linkedChat:a&&a.fullInfo&&a.fullInfo.linkedChatId?Object(d.f)(e,a.fullInfo.linkedChatId):void 0,isChannel:a&&Object(m.jb)(a)}},(e,t)=>Object(u.l)(t,["loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup"]))(({chat:e,chatId:t,chatsByIds:a,linkedChat:c,forDiscussionIds:r,isChannel:o,onScreenSelect:i,loadGroupsForDiscussion:d,linkDiscussionGroup:m,unlinkDiscussionGroup:u})=>{const[h,b]=Object(n.r)(),[g,p]=Object(n.r)(),[v,E]=Object(n.r)(!1),O=Object(n.m)(()=>E(!0),[]),[f,j,C]=Object(xe.a)(),[y,k,N]=Object(xe.a)(),I=Object(F.a)(),S=c&&c.id;Object(n.n)(()=>{d()},[d]),Object(n.n)(()=>{g||Object(Wt.a)("DiscussionGroups").then(p)},[g]);const w=Object(n.m)(()=>{C(),u({channelId:o?t:S}),o||i(s.g.Initial)},[C,u,o,t,S,i]),P=Object(n.m)(()=>{N(),m({channelId:t,chatId:h})},[N,m,t,h]);function M(){const e=a[h];if(e)return n.a.createElement("div",{className:"modal-header"},n.a.createElement(x.a,{size:"tiny",chat:e}),n.a.createElement("div",{className:"modal-title"},I("Channel.DiscussionGroup.LinkGroup")))}function L(){const t=a[h];if(t)return t.hasPrivateLink?Object(B.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?`,["br","simple_markdown"]):Object(B.a)(`Do you want to make **${t.title}** the discussion board for **${e.title}**?\n\nAnyone from the channel will be able to see messages in this group.`,["br","simple_markdown"])}return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement("div",{className:"section-icon"},g&&n.a.createElement(Yt.a,{id:"discussionGroupsDucks",size:l.sb,animationData:g,play:v,noLoop:!0,onLoad:O})),c&&n.a.createElement("div",null,n.a.createElement(Ee.a,{className:"chat-item-clickable",inactive:!0},n.a.createElement(fe.a,{chatId:c.id})),n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:j},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel")),n.a.createElement(we.a,{isOpen:f,onClose:C,header:n.a.createElement("div",{className:"modal-header"},n.a.createElement(x.a,{size:"tiny",chat:c}),n.a.createElement("div",{className:"modal-title"},I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"))),textParts:Object(B.a)(I(o?"DiscussionUnlinkChannelAlert":"DiscussionUnlinkGroupAlert",c.title),["br","simple_markdown"]),confirmLabel:I(o?"DiscussionUnlinkGroup":"DiscussionUnlinkChannel"),confirmHandler:w,confirmIsDestructive:!0})),!c&&n.a.createElement("div",null,n.a.createElement("p",{className:"section-help",dir:"auto"},I("DiscussionChannelHelp")),n.a.createElement("div",{teactFastList:!0},n.a.createElement(Ee.a,{key:"create-group",icon:"group",ripple:!0,teactOrderKey:0,className:"not-implemented"},I("DiscussionCreateGroup")),r?r.map((e,t)=>n.a.createElement(Ee.a,{key:e,teactOrderKey:t+1,className:"chat-item-clickable scroll-item",onClick:()=>{b(e),k()}},n.a.createElement(fe.a,{chatId:e}))):n.a.createElement(tt.a,{key:"nothing-found",teactOrderKey:0,text:"No discussion groups found"})),n.a.createElement("p",{className:"mt-4 mb-0 section-help",dir:"auto"},I("DiscussionChannelHelp2")),n.a.createElement(we.a,{isOpen:y,onClose:N,header:M(),textParts:L(),confirmLabel:I("DiscussionLinkGroup"),confirmHandler:P,isButtonsInOneRow:!0})))))}));var Kc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t);return{chat:n,isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatMemberBannedRights"]))(({chat:e,selectedChatMemberId:t,onScreenSelect:a,updateChatMemberBannedRights:c,isFormFullyDisabled:r})=>{const[l,o]=Object(n.r)({}),[i,d]=Object(n.r)(!1),[m,u]=Object(n.r)(!1),[h,b,g]=Object(xe.a)(),p=Object(F.a)(),v=Object(n.p)(()=>{if(e&&e.fullInfo&&e.fullInfo.members)return e.fullInfo.members.find(({userId:e})=>e===t)},[e,t]);Object(n.n)(()=>{e&&e.fullInfo&&t&&!v&&a(s.g.GroupPermissions)},[e,a,v,t]),Object(n.n)(()=>{o(v&&v.bannedRights||e&&e.defaultBannedRights||{}),d(!1),u(!1)},[e,v]);const E=Object(n.m)(e=>{const{name:t}=e.target;function a(e){return!e||void 0}o(e=>({...e,[t]:a(e[t]),..."sendStickers"===t&&{sendGifs:a(e[t])}})),d(!0)},[]),O=Object(n.m)(()=>{e&&t&&(u(!0),c({chatId:e.id,userId:t,bannedRights:l}))},[e,t,l,c]),f=Object(n.m)(()=>{e&&t&&c({chatId:e.id,userId:t,bannedRights:{viewMessages:!0}})},[e,t,c]),j=Object(n.m)(t=>!!r||!(!e||!e.defaultBannedRights)&&e.defaultBannedRights[t],[e,r]);if(v)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Oe.a,{userId:v.userId})),n.a.createElement("h3",{className:"section-heading mt-4",dir:"auto"},p("UserRestrictionsCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendMessages",checked:!l.sendMessages,label:p("UserRestrictionsSend"),blocking:!0,disabled:j("sendMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendMedia",checked:!l.sendMedia,label:p("UserRestrictionsSendMedia"),blocking:!0,disabled:j("sendMedia"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendStickers",checked:!l.sendStickers&&!l.sendGifs,label:p("UserRestrictionsSendStickers"),blocking:!0,disabled:j("sendStickers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"sendPolls",checked:!l.sendPolls,label:p("UserRestrictionsSendPolls"),blocking:!0,disabled:j("sendPolls"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"embedLinks",checked:!l.embedLinks,label:p("UserRestrictionsEmbedLinks"),blocking:!0,disabled:j("embedLinks"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"inviteUsers",checked:!l.inviteUsers,label:p("UserRestrictionsInviteUsers"),blocking:!0,disabled:j("inviteUsers"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"pinMessages",checked:!l.pinMessages,label:p("UserRestrictionsPinMessages"),blocking:!0,disabled:j("pinMessages"),onChange:E})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!l.changeInfo,label:p("UserRestrictionsChangeInfo"),blocking:!0,disabled:j("changeInfo"),onChange:E}))),!r&&n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"delete-user",ripple:!0,destructive:!0,onClick:b},p("UserRestrictionsBlock")))),n.a.createElement(qt,{isShown:i,onClick:O,ariaLabel:p("Save"),disabled:m},m?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:h,onClose:g,text:"Are you sure you want to ban and remove this user from the group?",confirmLabel:"Remove",confirmHandler:f,confirmIsDestructive:!0}))}));var Wc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{chat:a,currentUserId:e.currentUserId,isChannel:Object(m.jb)(a),usersById:n}})(({chat:e,isChannel:t,currentUserId:a,usersById:c,onScreenSelect:r,onChatMemberSelect:l})=>{const o=Object(F.a)();const i=Object(n.p)(()=>e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),d=Object(n.m)(e=>{l(e.userId,e.promotedByUserId===a),r(s.g.ChatAdminRights)},[a,l,r]),u=Object(n.m)(e=>{if(e.isOwner)return o("ChannelCreator");const t=e.promotedByUserId?c[e.promotedByUserId]:void 0;return t?o("EditAdminPromotedBy",Object(m.Z)(t)):o("ChannelAdmin")},[o,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{icon:"recent",multiline:!0,ripple:!0,onClick:function(){r(s.g.GroupRecentActions)}},n.a.createElement("span",{className:"title"},o("EventLog")),n.a.createElement("span",{className:"subtitle"},o(t?"EventLogInfoDetailChannel":"EventLogInfoDetail")))),n.a.createElement("div",{className:"section",dir:o.isRtl?"rtl":void 0},n.a.createElement("p",{className:"text-muted",dir:"auto"},t?"You can add administrators to help you manage your channel.":"You can add administrators to help you manage your group."),i.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable",ripple:!0,onClick:()=>d(e)},n.a.createElement(Oe.a,{userId:e.userId,status:u(e),forceShowSelf:!0}))))))}));var Yc=Object(n.h)(Object(c.h)((e,{chatId:t})=>({chat:Object(d.f)(e,t)}))(({chat:e})=>{const t=Object(F.a)(),a=Object(n.p)(()=>e&&e.fullInfo&&e.fullInfo.adminMembers?e.fullInfo.adminMembers.sort((e,t)=>e.isOwner?-1:t.isOwner?1:0):[],[e]),c=Object(n.m)(e=>e.isOwner?t("ChannelCreator"):t("ChannelAdmin"),[t]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section not-implemented",dir:t.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"section-heading",dir:"auto"},"Actions"),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogAllEvents"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewAdmins"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterNewMembers"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterChannelInfo"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterDeletedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterEditedMessages"),onChange:void 0})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogFilterLeavingMembers"),onChange:void 0}))),n.a.createElement("div",{className:"section not-implemented",dir:t.isRtl?"rtl":void 0},n.a.createElement("h3",{className:"section-heading",dir:"auto"},t("Channel.Management.Title")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!0,label:t("EventLogAllAdmins"),onChange:void 0})),a.map(e=>n.a.createElement(Ee.a,{key:e.userId,className:"chat-item-clickable picker-list-item",onClick:void 0,ripple:!0},n.a.createElement(aa.a,{label:"",checked:!0}),n.a.createElement(Oe.a,{userId:e.userId,status:c(e),forceShowSelf:!0}))))))}));var Zc=Object(n.h)(Object(c.h)((e,{chatId:t,isPromotedByCurrentUser:a})=>{const n=Object(d.f)(e,t),{byId:c}=e.users,{currentUserId:r}=e;return{chat:n,usersById:c,currentUserId:r,isChannel:Object(m.jb)(n),isFormFullyDisabled:!(n.isCreator||a)}},(e,t)=>Object(u.l)(t,["updateChatAdmin"]))(({selectedChatMemberId:e,onScreenSelect:t,chat:a,usersById:c,currentUserId:r,isChannel:l,isFormFullyDisabled:o,updateChatAdmin:i})=>{const[d,u]=Object(n.r)({}),[h,b]=Object(n.r)(!1),[g,p]=Object(n.r)(!1),[v,E,O]=Object(xe.a)(),[f,j]=Object(n.r)(""),C=Object(F.a)(),y=Object(n.p)(()=>{if(a.fullInfo&&a.fullInfo.adminMembers)return a.fullInfo.adminMembers.find(({userId:t})=>t===e)},[a,e]);Object(n.n)(()=>{a&&a.fullInfo&&e&&!y&&t(s.g.ChatAdministrators)},[a,t,y,e]),Object(n.n)(()=>{u(y&&y.adminRights||{}),j((y&&y.customTitle||"").substr(0,16)),b(!1),p(!1)},[y]);const k=Object(n.m)(e=>{const{name:t}=e.target;u(e=>{return{...e,[t]:(a=e[t],!a||void 0)};var a}),b(!0)},[]),N=Object(n.m)(()=>{e&&(p(!0),i({chatId:a.id,userId:e,adminRights:d,customTitle:f}))},[a,e,d,f,i]),I=Object(n.m)(()=>{e&&(i({chatId:a.id,userId:e,adminRights:{}}),O())},[a.id,O,e,i]),S=Object(n.m)(e=>!Object(m.ib)(a)&&(!(!o&&a.adminRights)||!a.adminRights[e]),[a,o]),w=Object(n.p)(()=>{if(!y)return;if(y.isOwner)return C("ChannelCreator");const e=y.promotedByUserId?c[y.promotedByUserId]:void 0;return e?C("EditAdminPromotedBy",Object(m.Z)(e)):C("ChannelAdmin")},[y,c,C]),P=Object(n.m)(e=>{const{value:t}=e.target;j(t),b(!0)},[]);if(y)return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section"},n.a.createElement(Ee.a,{inactive:!0,className:"chat-item-clickable"},n.a.createElement(Oe.a,{userId:y.userId,status:w,forceShowSelf:!0})),n.a.createElement("h3",{className:"section-heading mt-4",dir:"auto"},C("EditAdminWhatCanDo")),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"changeInfo",checked:!!d.changeInfo,label:C(l?"EditAdminChangeChannelInfo":"EditAdminChangeGroupInfo"),blocking:!0,disabled:S("changeInfo"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"postMessages",checked:!!d.postMessages,label:C("EditAdminPostMessages"),blocking:!0,disabled:S("postMessages"),onChange:k})),l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"editMessages",checked:!!d.editMessages,label:C("EditAdminEditMessages"),blocking:!0,disabled:S("editMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"deleteMessages",checked:!!d.deleteMessages,label:C(l?"EditAdminDeleteMessages":"EditAdminGroupDeleteMessages"),blocking:!0,disabled:S("deleteMessages"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"banUsers",checked:!!d.banUsers,label:C("EditAdminBanUsers"),blocking:!0,disabled:S("banUsers"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"inviteUsers",checked:!!d.inviteUsers,label:C("EditAdminAddUsers"),blocking:!0,disabled:S("inviteUsers"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"pinMessages",checked:!!d.pinMessages,label:C("EditAdminPinMessages"),blocking:!0,disabled:S("pinMessages"),onChange:k})),n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"addAdmins",checked:!!d.addAdmins,label:C("EditAdminAddAdmins"),blocking:!0,disabled:S("addAdmins"),onChange:k})),!l&&n.a.createElement("div",{className:"ListItem no-selection"},n.a.createElement(aa.a,{name:"anonymous",checked:!!d.anonymous,label:C("EditAdminSendAnonymously"),blocking:!0,disabled:S("anonymous"),onChange:k})),o&&n.a.createElement("p",{className:"section-info mb-4",dir:"auto"},C("Channel.EditAdmin.CannotEdit")),!l&&n.a.createElement(pe.a,{id:"admin-title",label:C("EditAdminRank"),onChange:P,value:f,disabled:o,maxLength:16}),r!==e&&!o&&n.a.createElement(Ee.a,{icon:"delete",ripple:!0,destructive:!0,onClick:E},C("EditAdminRemoveAdmin")))),n.a.createElement(qt,{isShown:h,onClick:N,ariaLabel:C("Save"),disabled:g},g?n.a.createElement(L.a,{color:"white"}):n.a.createElement("i",{className:"icon-check"})),n.a.createElement(we.a,{isOpen:v,onClose:O,text:"Are you sure you want to dismiss this admin?",confirmLabel:"Dismiss",confirmHandler:I,confirmIsDestructive:!0}))}));var Qc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.jb)(a)}},(e,t)=>Object(u.l)(t,["openUserInfo"]))(({members:e,usersById:t,isChannel:a,openUserInfo:c})=>{const r=Object(n.p)(()=>{if(e&&t)return Object(m.Eb)(e.map(({userId:e})=>e),t)},[e,t]),s=Object(n.m)(e=>{c({id:e})},[c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},r?r.map((e,t)=>n.a.createElement(Ee.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>s(e)},n.a.createElement(Oe.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(tt.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var Xc=Object(n.h)(Object(c.h)((e,{chatId:t})=>{const a=Object(d.f)(e,t),{byId:n}=e.users;return{members:a&&a.fullInfo&&a.fullInfo.members,usersById:n,isChannel:a&&Object(m.jb)(a)}})(({usersById:e,members:t,isChannel:a,onScreenSelect:c,onChatMemberSelect:r})=>{const l=Object(n.p)(()=>{if(t&&e)return Object(m.Eb)(t.filter(e=>!e.isOwner).map(({userId:e})=>e),e)},[t,e]),o=Object(n.m)(e=>{r(e),c(s.g.GroupUserPermissions)},[r,c]);return n.a.createElement("div",{className:"Management"},n.a.createElement("div",{className:"custom-scroll"},n.a.createElement("div",{className:"section",teactFastList:!0},l?l.map((e,t)=>n.a.createElement(Ee.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>o(e)},n.a.createElement(Oe.a,{userId:e,forceShowSelf:!0}))):n.a.createElement(tt.a,{teactOrderKey:0,key:"nothing-found",text:a?"No subscribers found":"No members found"}))))}));var Jc=Object(n.h)(Object(c.h)(e=>({managementType:Object(d.u)(e)}))(({chatId:e,currentScreen:t,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r,onChatMemberSelect:l,managementType:o})=>{switch(t){case s.g.Initial:switch(o){case"user":return n.a.createElement(Uc,{key:e,userId:e});case"group":return n.a.createElement(Gc,{key:e,chatId:e,onScreenSelect:r});case"channel":return n.a.createElement(Hc,{key:e,chatId:e,onScreenSelect:r})}break;case s.g.ChatPrivacyType:return n.a.createElement(_c,{chatId:e});case s.g.Discussion:return n.a.createElement(Vc,{chatId:e,onScreenSelect:r});case s.g.GroupPermissions:return n.a.createElement(qc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRemovedUsers:return n.a.createElement(zc,{chatId:e});case s.g.GroupUserPermissionsCreate:return n.a.createElement(Xc,{chatId:e,onChatMemberSelect:l,onScreenSelect:r});case s.g.GroupUserPermissions:return n.a.createElement(Kc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChatAdministrators:return n.a.createElement(Wc,{chatId:e,onScreenSelect:r,onChatMemberSelect:l});case s.g.GroupRecentActions:return n.a.createElement(Yc,{chatId:e});case s.g.ChatAdminRights:return n.a.createElement(Zc,{chatId:e,selectedChatMemberId:a,isPromotedByCurrentUser:c,onScreenSelect:r});case s.g.ChannelSubscribers:case s.g.GroupMembers:return n.a.createElement(Qc,{chatId:e})}}));const er={USD:"$",EUR:"€",GBP:"£",JPY:"¥",RUB:"₽",UAH:"₴",INR:"₹",AED:"د.إ"};function tr(e){return e&&er[e]||""}const ar=/^4[0-9]{12}(?:[0-9]{1,3})?$/,nr=/^5[1-5][0-9]{11,14}$/,cr=/^2[2-7][0-9]{11,14}$/;let rr;!function(e){e[e.Default=0]="Default",e[e.Visa=1]="Visa",e[e.Mastercard=2]="Mastercard"}(rr||(rr={}));const sr={[rr.Default]:"",[rr.Visa]:"visa",[rr.Mastercard]:"mastercard"};function lr(e){return e=e.replace(/\s/g,""),ar.test(e)?rr.Visa:nr.test(e)||cr.test(e)?rr.Mastercard:rr.Default}var or=a(60);const ir={streetLine1:"",streetLine2:"",city:"",state:"",countryIso2:"",postCode:"",fullName:"",email:"",phone:"",shipping:"",cardNumber:"",cardholder:"",expiry:"",cvv:"",billingCountry:"",billingZip:"",saveInfo:!0,saveCredentials:!1,formErrors:{}},dr=(e,t)=>{switch(t.type){case"changeAddress1":return{...e,streetLine1:t.payload,formErrors:{...e.formErrors,streetLine1:void 0}};case"changeAddress2":return{...e,streetLine2:t.payload,formErrors:{...e.formErrors,streetLine2:void 0}};case"changeCity":return{...e,city:t.payload,formErrors:{...e.formErrors,city:void 0}};case"changeState":return{...e,state:t.payload,formErrors:{...e.formErrors,state:void 0}};case"changeCountry":return{...e,countryIso2:t.payload,billingCountry:mr(t.payload),formErrors:{...e.formErrors,countryIso2:void 0}};case"changePostCode":return{...e,postCode:t.payload,formErrors:{...e.formErrors,postCode:void 0}};case"changeFullName":return{...e,fullName:t.payload,formErrors:{...e.formErrors,fullName:void 0}};case"changeEmail":return{...e,email:t.payload,formErrors:{...e.formErrors,email:void 0}};case"changePhone":return{...e,phone:t.payload,formErrors:{...e.formErrors,phone:void 0}};case"changeShipping":return{...e,shipping:t.payload};case"changeCardNumber":return{...e,cardNumber:t.payload,formErrors:{...e.formErrors,cardNumber:void 0}};case"changeCardholder":return{...e,cardholder:t.payload,formErrors:{...e.formErrors,cardholder:void 0}};case"changeExpiryDate":return{...e,expiry:t.payload,formErrors:{...e.formErrors,expiry:void 0}};case"changeCvvCode":return{...e,cvv:t.payload,formErrors:{...e.formErrors,cvv:void 0}};case"changeBillingCountry":return{...e,billingCountry:t.payload,formErrors:{...e.formErrors,billingCountry:void 0}};case"changeBillingZip":return{...e,billingZip:t.payload,formErrors:{...e.formErrors,billingZip:void 0}};case"changeSaveInfo":return{...e,saveInfo:t.payload};case"changeSaveCredentials":return{...e,saveCredentials:t.payload};case"updateUserInfo":return t.payload.countryIso2?{...e,...t.payload,billingCountry:mr(t.payload.countryIso2)}:{...e,...t.payload};case"setFormErrors":return{...e,formErrors:{...e.formErrors,...t.payload}};default:return e}};function mr(e){const t=xt.a.find(({id:t})=>t===e);return t?t.name:""}function ur(e,t=400){Object(n.n)(()=>{o.l||setTimeout(()=>{Object(_.b)(()=>{e.current&&e.current.focus()})},t)},[e,t])}var hr=Object(n.h)(e=>{const{id:t,value:a,label:c,hasArrow:r,error:s,ref:l,placeholder:o,onChange:i,children:d}=e,m=s||c,u=Object(ce.a)("input-group",a&&"touched",s&&"error",m&&"with-label",r&&"with-arrow","input-group");return n.a.createElement("div",{className:u},n.a.createElement("select",{className:"form-control",id:t,value:a||"",onChange:i,placeholder:o||c,ref:l},d),m&&t&&n.a.createElement("label",{htmlFor:t},m))});a(304);var br=Object(n.h)(({state:e,needEmail:t,needPhone:a,needName:c,needAddress:r,dispatch:s})=>{const l=Object(n.q)(null),o=Object(n.q)(null),i=Object(n.q)(null);Object(n.n)(()=>{i.current&&i.current.value!==e.countryIso2&&(i.current.value=e.countryIso2)},[e.countryIso2]);const d=Object(F.a)();ur(l);const m=Object(n.m)(e=>{s({type:"changeAddress1",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeAddress2",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeCity",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeState",payload:e.target.value})},[s]),g=Object(n.m)(e=>{s({type:"changeCountry",payload:e.target.value})},[s]),p=Object(n.m)(e=>{s({type:"changePostCode",payload:e.target.value})},[s]),v=Object(n.m)(e=>{s({type:"changeFullName",payload:e.target.value})},[s]),E=Object(n.m)(e=>{s({type:"changeEmail",payload:e.target.value})},[s]),O=Object(n.m)(e=>{let{value:t}=e.target;t="+"+t.replace(/\D/g,""),o.current&&(o.current.value=t),s({type:"changePhone",payload:t})},[s]),f=Object(n.m)(e=>{s({type:"changeSaveInfo",payload:e.target.value})},[s]),{formErrors:j}=e;return n.a.createElement("div",{className:"ShippingInfo"},n.a.createElement("form",null,r?n.a.createElement("div",null,n.a.createElement("h5",null,d("PaymentShippingAddress")),n.a.createElement(pe.a,{ref:l,label:"Address1 (Street)",onChange:m,value:e.streetLine1,inputMode:"text",error:j.streetLine1}),n.a.createElement(pe.a,{label:"Address2 (Street)",onChange:u,value:e.streetLine2,inputMode:"text",error:j.streetLine2}),n.a.createElement(pe.a,{label:"City",onChange:h,value:e.city,inputMode:"text",error:j.city}),n.a.createElement(pe.a,{label:"State",onChange:b,value:e.state,inputMode:"text",error:j.state}),n.a.createElement(hr,{label:"Country",placeholder:"Country",onChange:g,value:e.countryIso2,hasArrow:Boolean(!0),id:"shipping-country",error:j.countryIso2,ref:i},xt.a.map(({name:e,id:t})=>n.a.createElement("option",{value:t,className:"county-item"},e))),n.a.createElement(pe.a,{label:"Post Code",onChange:p,value:e.postCode,inputMode:"text",error:j.postCode})):void 0,c||t||a?n.a.createElement("h5",null,d("PaymentShippingReceiver")):void 0,c&&n.a.createElement(pe.a,{label:"Full name",onChange:v,value:e.fullName,inputMode:"text",error:j.fullName}),t&&n.a.createElement(pe.a,{label:"Email",onChange:E,value:e.email,inputMode:"email",error:j.email}),a&&n.a.createElement(pe.a,{label:"Phone number",onChange:O,value:e.phone,inputMode:"tel",error:j.phone,ref:o}),n.a.createElement(aa.a,{label:d("PaymentShippingSave"),subLabel:d("PaymentShippingSaveInfo"),checked:Boolean(e.saveInfo),onChange:f})))});a(305);var gr=Object(n.h)(({state:e,shippingOptions:t,currency:a,dispatch:c})=>{Object(n.n)(()=>{t&&!e.shipping&&c({type:"changeShipping",payload:t[0].id})},[t,e.shipping,c]);const r=Object(n.m)(e=>{c({type:"changeShipping",payload:e})},[c]),s=Object(n.p)(()=>t.map(({id:e,title:t,amount:n})=>({label:t,subLabel:`${a} ${String(n/100)}`,value:e})),[t,a]);return n.a.createElement("div",{className:"Shipping"},n.a.createElement("form",null,n.a.createElement("p",null,"Select shipping method"),n.a.createElement(oa.a,{name:"shipping-options",options:s,onChange:r,selected:e.shipping})))});a(306);function pr(e,t,a,c=!1){return n.a.createElement("div",{className:"price-info-item "+(c?"price-info-item-main":"")},n.a.createElement("div",{className:"title"},e),n.a.createElement("div",{className:"value"},`${a||""} ${(t/100).toFixed(2)}`))}function vr(e,t,a){return n.a.createElement("div",{className:"checkout-info-item"},n.a.createElement("i",{className:e}," "),n.a.createElement("div",{className:"info"},n.a.createElement("div",{className:"title"},t),n.a.createElement("p",{className:"data"},a)))}var Er=Object(n.h)(({invoiceContent:e,prices:t,shippingPrices:a,checkoutInfo:c,currency:r,totalPrice:s})=>{const{photoUrl:l,title:o,text:i}=e||{},{paymentMethod:d,paymentProvider:m,shippingAddress:u,name:h,phone:b,shippingMethod:g}=c||{};return n.a.createElement("div",{className:"Checkout"},n.a.createElement("div",{className:"description has-image"},l&&n.a.createElement("img",{src:l,alt:""}),n.a.createElement("div",{className:"text"},n.a.createElement("h5",null,o),n.a.createElement("p",null,i))),n.a.createElement("div",{className:"price-info"},t&&t.map(e=>pr(e.label,e.amount,r,!1)),a&&a.map(e=>pr(e.label,e.amount,r,!1)),void 0!==s&&pr("Total",s,r,!0)),n.a.createElement("div",{className:"invoice-info"},d&&vr("icon-card",d,"Payment method"),m&&vr("stripe-provider",m,"Payment provider"),u&&vr("icon-location",u,"Shipping address"),h&&vr("icon-user",h,"Name"),b&&vr("icon-phone",b,"Phone number"),g&&vr("icon-truck",g,"Shipping method")))});var Or=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null),r=Object(n.m)(t=>{if("Backspace"===t.key&&"/"===e.charAt(e.length-1)){const t=e.slice(0,e.length-1);c.current&&(c.current.value=t)}},[e]),s=Object(n.m)(e=>{a(function(e){const t=(e=e.replace(/[^\d]/g,"").slice(0,4)).match(/.{1,2}/g);return t&&t[0]&&Number(t[0])>12&&(t[0]="12"),t&&t[0]&&2===t[0].length&&!t[1]&&(t[1]=""),t?t.join("/"):""}(e.target.value))},[a]);return n.a.createElement(pe.a,{label:"Expiry date",ref:c,onChange:s,onKeyDown:r,value:e,error:t,inputMode:"numeric",maxLength:5})}),fr=(a(307),a.p+"mastercard.4216118edafe23cc2dec7b8807ba4622.svg"),jr=a.p+"visa.e5a7c336e1deb4b92a636e2e053878c4.svg";var Cr=Object(n.h)(({value:e,error:t,onChange:a})=>{const c=Object(n.q)(null);ur(c);const[r,s]=Object(n.r)(rr.Default);Object(n.n)(()=>{const t=lr(e);s(t)},[]);const l=Object(n.m)(e=>{const t=function(e){const t=(e=e.replace(/[^\d]/g,"")).match(/.{1,4}/g);return t?t.join(" "):""}(e.target.value),n=lr(e.target.value);s(n),a(t),c.current&&(c.current.value=t)},[a,c]),o=function(e){switch(e){case rr.Mastercard:return n.a.createElement("img",{src:fr,alt:""});case rr.Visa:return n.a.createElement("img",{src:jr,alt:""});default:return}}(r);return n.a.createElement("div",{className:"CardInput"},n.a.createElement("span",{className:"left-addon"},o),n.a.createElement(pe.a,{ref:c,label:"Card number",onChange:l,value:e,inputMode:"numeric",className:r?"has-left-addon":"",error:t,maxLength:23}))});a(308);var yr=Object(n.h)(({state:e,canSaveCredentials:t,needCardholderName:a,needCountry:c,needZip:r,dispatch:s})=>{const l=Object(n.q)(null);Object(n.n)(()=>{l.current&&l.current.value!==e.billingCountry&&(l.current.value=e.billingCountry)},[e.billingCountry]);const o=Object(n.m)(e=>{s({type:"changeCardNumber",payload:e})},[s]),i=Object(n.m)(e=>{s({type:"changeCardholder",payload:e.target.value.toUpperCase()})},[s]),d=Object(n.m)(e=>{s({type:"changeExpiryDate",payload:e})},[s]),m=Object(n.m)(e=>{s({type:"changeCvvCode",payload:e.target.value})},[s]),u=Object(n.m)(e=>{s({type:"changeBillingCountry",payload:e.target.value})},[s]),h=Object(n.m)(e=>{s({type:"changeBillingZip",payload:e.target.value})},[s]),b=Object(n.m)(e=>{s({type:"changeSaveCredentials",payload:e.target.value})},[s]),g=Object(F.a)(),{formErrors:p={}}=e;return n.a.createElement("div",{className:"PaymentInfo"},n.a.createElement("form",null,n.a.createElement("h5",null,g("PaymentCardTitle")),n.a.createElement(Cr,{onChange:o,value:e.cardNumber,error:p.cardNumber}),a&&n.a.createElement(pe.a,{label:"Name on card",onChange:i,value:e.cardholder,inputMode:"text",error:p.cardholder}),n.a.createElement("section",{className:"inline-inputs"},n.a.createElement(Or,{value:e.expiry,onChange:d,error:p.expiry}),n.a.createElement(pe.a,{label:"CVV code",onChange:m,value:e.cvv,inputMode:"numeric",maxLength:3,error:p.cvv})),c||r?n.a.createElement("h5",null,g("PaymentBillingAddress")):void 0,c&&n.a.createElement(hr,{label:"Country",placeholder:"Country",onChange:u,value:e.billingCountry,hasArrow:Boolean(!0),id:"billing-country",error:p.billingCountry,ref:l},xt.a.map(({name:e})=>n.a.createElement("option",{value:e,className:"county-item"},e))),r&&n.a.createElement(pe.a,{label:"Post Code",onChange:h,value:e.billingZip,inputMode:"text",error:p.billingZip}),t&&n.a.createElement(aa.a,{label:g("PaymentCardSavePaymentInformation"),checked:e.saveCredentials,onChange:b})))});a(187);var kr=Object(n.h)(Object(c.h)(e=>{const{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,invoice:r,invoiceContent:s,nativeProvider:l,nativeParams:o,passwordMissing:i,error:d}=e.payment,m=Boolean(r&&(!l||"stripe"!==l)),{needCardholderName:u,needCountry:h,needZip:b}=o||{},{nameRequested:g,phoneRequested:p,emailRequested:v,shippingAddressRequested:E,flexible:O,phoneToProvider:f,emailToProvider:j,currency:C,prices:y}=r||{};return{step:t,shippingOptions:a,savedInfo:n,canSaveCredentials:c,nativeProvider:l,passwordMissing:i,nameRequested:g,shippingAddressRequested:E,phoneRequested:p,emailRequested:v,flexible:O,phoneToProvider:f,emailToProvider:j,currency:C,prices:y,isProviderError:m,invoiceContent:s,needCardholderName:u,needCountry:h,needZip:b,error:d,globalErrors:e.errors}},(e,t)=>Object(u.l)(t,["validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError"]))(({isOpen:e,onClose:t,step:a,shippingOptions:c,savedInfo:r,canSaveCredentials:l,nameRequested:o,shippingAddressRequested:i,phoneRequested:d,emailRequested:m,phoneToProvider:u,emailToProvider:h,currency:b,passwordMissing:g,isProviderError:p,invoiceContent:v,nativeProvider:E,prices:O,needCardholderName:f,needCountry:j,needZip:C,error:y,globalErrors:k,validateRequestedInfo:N,sendPaymentForm:I,setPaymentStep:S,sendCredentialsInfo:w,clearPaymentError:P})=>{const[M,A]=It(dr,ir),D=tr(b),[B,x]=Object(n.r)(!1),U=Object(F.a)();Object(n.n)(()=>{(a||y||k)&&x(!1)},[a,y,k]),Object(n.n)(()=>{if(y&&y.field)A({type:"setFormErrors",payload:{[y.field]:y.fieldError}});else if(k&&k.length){const e=Object(or.a)(k);A({type:"setFormErrors",payload:{...e}})}},[y,k,A]),Object(n.n)(()=>{if(r){const{name:e,phone:t,email:a,shippingAddress:n}=r;A({type:"updateUserInfo",payload:{fullName:e,phone:t&&"+"!==t.charAt(0)?"+"+t:t,email:a,...n||{}}})}},[r,A]);const G=Object(n.m)(()=>{P()},[P]),q=Object(n.p)(()=>a!==s.i.Checkout?0:function(e=[],t,a){const n=t?Ir(t,a):[];let c=0;const r=e.concat(n||[]);return c=r.reduce((e,t)=>e+t.amount,c),c}(O,c,M.shipping),[a,M.shipping,O,c]),z=Object(n.p)(()=>{if(a===s.i.Checkout)return function(e,t,a){const n=`${function(e){const t=lr(e);return sr[t]||""}(e.cardNumber)} *${e.cardNumber.slice(-4)}`,c=e.streetLine1?`${e.streetLine1}, ${e.city}, ${e.countryIso2}`:void 0,{phone:r,fullName:s}=e,l=t?Nr(t,e.shipping):void 0,o=l?l.title:void 0;return{paymentMethod:n,paymentProvider:a,shippingAddress:c,name:s,phone:r,shippingMethod:o}}(M,c,E||"")},[a,M,c,E]);const H=Object(n.m)(()=>{const{saveInfo:e}=M,t=function(e){const{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s,fullName:l,phone:o,email:i}=e;return{name:l,phone:o,email:i,shippingAddress:{streetLine1:t,streetLine2:a,city:n,state:c,countryIso2:r,postCode:s}}}(M);N({requestInfo:t,saveInfo:e})},[N,M]),$=Object(n.m)(()=>{const e=function(e){const{cardNumber:t,cardholder:a,expiry:n,cvv:c,billingCountry:r,billingZip:s}=e,[l,o]=n.split("/");return{data:{cardNumber:t,cardholder:a,expiryMonth:l,expiryYear:o,cvv:c,country:r,zip:s}}}(M);w({credentials:e})},[w,M]),_=Object(n.m)(()=>{I({shippingOptionId:M.shipping,saveCredentials:M.saveCredentials})},[I,M]),V=Object(n.m)(e=>{S({step:e})},[S]),K=Object(n.m)(()=>{switch(x(!0),a){case s.i.ShippingInfo:return H();case s.i.Shipping:return V(s.i.PaymentInfo);case s.i.PaymentInfo:return $();case s.i.Checkout:return _();default:return()=>{}}},[a,H,V,$,_]),W=Object(n.p)(()=>{switch(a){case s.i.ShippingInfo:return U("PaymentShippingInfo");case s.i.Shipping:return U("PaymentShippingMethod");case s.i.PaymentInfo:return U("PaymentCardInfo");case s.i.Checkout:return U("PaymentCheckout");default:return""}},[a,U]),Y=Object(n.p)(()=>{switch(a){case s.i.Checkout:return U("Checkout.PayPrice",`${D}${(q/100).toFixed(2)}`);default:return U("Next")}},[a,U,D,q]);return p?n.a.createElement(ge.a,{className:"error",isOpen:e,onClose:t},n.a.createElement("p",null,"Sorry, Telegram T doesn't support payments with this provider yet. ",n.a.createElement("br",null),"Please use one of our mobile apps to do this."),n.a.createElement(R.a,{isText:!0,onClick:t},U("OK"))):n.a.createElement(ge.a,{className:"PaymentModal",isOpen:e,onClose:t},n.a.createElement("div",{className:"header",dir:U.isRtl?"rtl":void 0},n.a.createElement(R.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null,W)),void 0!==a?n.a.createElement(T.a,{name:"slide",activeKey:a},()=>n.a.createElement("div",{className:"content custom-scroll"},function(e){switch(e){case s.i.ShippingInfo:return n.a.createElement(br,{state:M,dispatch:A,needAddress:Boolean(i),needEmail:Boolean(m||h),needPhone:Boolean(d||u),needName:Boolean(o)});case s.i.Shipping:return n.a.createElement(gr,{state:M,dispatch:A,shippingOptions:c||[],currency:D});case s.i.PaymentInfo:return n.a.createElement(yr,{state:M,dispatch:A,canSaveCredentials:Boolean(!g&&l),needCardholderName:f,needCountry:j,needZip:C});case s.i.Checkout:return n.a.createElement(Er,{prices:O,shippingPrices:M.shipping&&c?Ir(c,M.shipping):void 0,totalPrice:q,invoiceContent:v,checkoutInfo:z,currency:D});default:return}}(a))):n.a.createElement("div",{className:"empty-content"},n.a.createElement(L.a,{color:"gray"})),n.a.createElement("div",{className:"footer"},n.a.createElement(R.a,{type:"submit",onClick:K,disabled:B,isLoading:B},Y)),y&&!y.field&&function(){if(y)return n.a.createElement(ge.a,{className:"error",isOpen:Boolean(y),onClose:G},n.a.createElement("h4",null,y.description||"Error"),n.a.createElement("p",null,y.description||"Error"),n.a.createElement(R.a,{isText:!0,onClick:P},U("OK")))}())}));function Nr(e,t){return e.find(({id:e})=>e===t)}function Ir(e,t){const a=Nr(e,t);return a?a.prices:void 0}var Sr=Object(n.h)(Object(c.h)(e=>{const{receipt:t}=e.payment,{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}=t||{};return{currency:a,prices:n,info:c,totalAmount:r,credentialsTitle:s,shippingPrices:l,shippingMethod:o,photoUrl:i,text:d,title:m}})(({isOpen:e,onClose:t,prices:a,shippingPrices:c,totalAmount:r,currency:s,info:l,photoUrl:o,text:i,title:d,credentialsTitle:m,shippingMethod:u})=>{const h=Object(F.a)(),b=tr(s),g=Object(n.p)(()=>function(e,t,a){if(!t)return{paymentMethod:e};const{shippingAddress:n}=t,c=n&&n.streetLine1?`${n.streetLine1}, ${n.city}, ${n.countryIso2}`:void 0,{phone:r,name:s}=t;return{paymentMethod:e,paymentProvider:"Stripe",shippingAddress:c,name:s,phone:r,shippingMethod:a}}(m,l,u),[l,u,m]);return n.a.createElement(ge.a,{className:"PaymentModal PaymentModal-receipt",isOpen:e,onClose:t},n.a.createElement("div",null,n.a.createElement("div",{className:"header",dir:h.isRtl?"rtl":void 0},n.a.createElement(R.a,{className:"close-button",color:"translucent",round:!0,size:"smaller",onClick:t,ariaLabel:"Close"},n.a.createElement("i",{className:"icon-close"})),n.a.createElement("h3",null," ",h("PaymentReceipt")," ")),n.a.createElement("div",{className:"receipt-content custom-scroll"},n.a.createElement(Er,{prices:a,shippingPrices:c,totalPrice:r,invoiceContent:{photoUrl:o,text:i,title:d},checkoutInfo:g,currency:b}))))}))},,,,,,,,,,,,,,,,,,,,,,function(e,t,a){"use strict";a.d(t,"a",(function(){return s}));var n=a(5),c=a(54);const r={MonkeyIdle:a.p+"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs",MonkeyTracking:a.p+"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs",MonkeyClose:a.p+"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs",MonkeyPeek:a.p+"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs",FoldersAll:a.p+"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs",FoldersNew:a.p+"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs",DiscussionGroups:a.p+"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs"};function s(e){const t=r[e].replace(window.location.origin,"");return c.b("file"+t,n.ApiMediaFormat.Lottie)}},,,,,function(e,t,a){"use strict";var n=a(0),c=a(8),r=a(1),s=a(13),l=a(25),o=a(32),i=a(110),d=a(16);a(151);const m={type:"blob",quality:.8,format:"jpeg",circle:!1};let u,h,b;var g=Object(n.h)(({file:e,onChange:t,onClose:c})=>{const[g,p]=Object(n.r)(!1);Object(n.n)(()=>{e&&(g?async function(e){try{const t=document.getElementById("avatar-crop");if(!t)return;const{offsetWidth:a,offsetHeight:n}=t;b=new u(t,{enableZoom:!0,boundary:{width:a,height:n},viewport:{width:a-16,height:n-16,type:"circle"}});const c=await Object(s.a)(e);await b.bind({url:c})}catch(e){r.p&&console.error(e)}}(e):async function(){return h||(h=Promise.all([a.e(6),a.e(8)]).then(a.bind(null,315)),u=(await h).default),h}().then(()=>p(!0)))},[e,g]);const v=Object(l.a)();return n.a.createElement(i.a,{isOpen:Boolean(e),onClose:c,title:"Drag to reposition",className:"CropModal",hasCloseButton:!0},g?n.a.createElement("div",{id:"avatar-crop"}):n.a.createElement(d.a,null),n.a.createElement(o.a,{className:"confirm-button",round:!0,color:"primary",onClick:async function(){if(!b)return;const e=await b.result(m),a="string"==typeof e?e:Object(s.b)(e,"avatar.jpg");t(a)},ariaLabel:v("CropImage")},n.a.createElement("i",{className:"icon-check"})))});a(152);t.a=Object(n.h)(({title:e="Change your profile picture",disabled:t,currentAvatarBlobUrl:a,onChange:r})=>{const[s,l]=Object(n.r)(),[o,i]=Object(n.r)(a);Object(n.n)(()=>{i(a)},[a]);const d=Object(c.a)(o&&"filled",t&&"disabled");return n.a.createElement("div",{className:"AvatarEditable"},n.a.createElement("label",{className:d,role:"button",tabIndex:0,title:e},n.a.createElement("input",{type:"file",onChange:function(e){const t=e.target;t&&t.files&&t.files[0]&&(l(t.files[0]),t.value="")},accept:"image/png, image/jpeg"}),n.a.createElement("i",{className:"icon-camera-add"}),o&&n.a.createElement("img",{src:o,alt:"Avatar"})),n.a.createElement(g,{file:s,onClose:function(){l(void 0)},onChange:function(e){l(void 0),r(e),o&&URL.revokeObjectURL(o),i(URL.createObjectURL(e))}}))})},,,,,,,,,,function(e,t,a){},,,,,,,,function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(125),l=a(116);a(140);const o=[0,50],i=[0,20],d=[20,0],m=r.g?c.rb:c.qb;t.a=Object(n.h)(({isPasswordVisible:e,isBig:t})=>{const[a,r]=Object(n.r)(),[u,h]=Object(n.r)(),[b,g]=Object(n.r)(!1),[p,v]=Object(n.r)(!1);Object(n.n)(()=>{a?setTimeout(()=>v(!0),2e3):Object(s.a)("MonkeyClose").then(r)},[a]),Object(n.n)(()=>{u||Object(s.a)("MonkeyPeek").then(h)},[u]);const E=Object(n.m)(()=>g(!0),[]);return n.a.createElement("div",{id:"monkey",className:t?"big":""},!b&&n.a.createElement("div",{className:"monkey-preview"}),a&&n.a.createElement(l.a,{id:"closeMonkey",size:t?c.Bb:m,className:p?"hidden":"shown",animationData:a,playSegment:o,noLoop:!0,onLoad:E}),u&&n.a.createElement(l.a,{id:"peekMonkey",size:t?c.Bb:m,className:p?"shown":"hidden",animationData:u,playSegment:e?i:d,noLoop:!0}))})},function(e,t,a){"use strict";var n=a(0),c=a(1),r=a(7),s=a(8),l=a(25),o=a(32);const i=r.g?550:400;t.a=Object(n.h)(({isLoading:e=!1,isPasswordVisible:t,error:a,hint:d,placeholder:m="Password",submitLabel:u="Next",clearError:h,onChangePasswordVisibility:b,onInputChange:g,onSubmit:p})=>{const v=Object(n.q)(null),E=Object(l.a)(),[O,f]=Object(n.r)(""),[j,C]=Object(n.r)(!1);return Object(n.n)(()=>{r.l||setTimeout(()=>{v.current.focus()},i)},[]),Object(n.n)(()=>{a&&requestAnimationFrame(()=>{v.current.focus(),v.current.select()})},[a]),n.a.createElement("form",{action:"",onSubmit:function(t){t.preventDefault(),e||j&&p(O)},autoComplete:"off"},n.a.createElement("div",{className:Object(s.a)("input-group password-input",O&&"touched",a&&"error"),dir:E.isRtl?"rtl":void 0},n.a.createElement("input",{ref:v,className:"form-control",type:t?"text":"password",id:"sign-in-password",value:O||"",autoComplete:"current-password",onChange:function(e){a&&h();const{target:t}=e;f(t.value),C(t.value.length>=c.Y),g&&g(t.value)},dir:"auto"}),n.a.createElement("label",null,a||d||m),n.a.createElement("div",{className:"toggle-password",onClick:function(){b(!t)},role:"button",tabIndex:0,title:"Toggle password visibility"},n.a.createElement("i",{className:t?"icon-eye":"icon-eye-closed"}))),j&&n.a.createElement(o.a,{type:"submit",ripple:!0,isLoading:e},u))})},,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,function(e,t,a){},,,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){},function(e,t,a){}])]); +//# sourceMappingURL=3.b7d1e22369add742c79e.js.map \ No newline at end of file diff --git a/dist/3.b7d1e22369add742c79e.js.map b/dist/3.b7d1e22369add742c79e.js.map new file mode 100644 index 00000000..67d8c90a --- /dev/null +++ b/dist/3.b7d1e22369add742c79e.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///./src/components/mediaViewer/helpers/ghostAnimation.ts","webpack:///./src/components/mediaViewer/SenderInfo.tsx","webpack:///./src/components/mediaViewer/MediaViewerActions.tsx","webpack:///./src/components/mediaViewer/MediaViewerFooter.tsx","webpack:///./src/hooks/useFullscreen.ts","webpack:///./src/components/mediaViewer/helpers/formatFileSize.ts","webpack:///./src/components/mediaViewer/VideoPlayerControls.tsx","webpack:///./src/components/mediaViewer/VideoPlayer.tsx","webpack:///./src/components/mediaViewer/ZoomControls.tsx","webpack:///./src/components/mediaViewer/PanZoom.tsx","webpack:///./src/components/mediaViewer/MediaViewer.tsx","webpack:///./src/components/main/ForwardPicker.tsx","webpack:///./src/components/main/Errors.tsx","webpack:///./src/components/main/Notifications.tsx","webpack:///./src/components/main/SafeLinkModal.tsx","webpack:///./src/components/common/CalendarModal.tsx","webpack:///./src/components/main/HistoryCalendar.tsx","webpack:///./src/components/common/DeleteMessageModal.tsx","webpack:///./src/components/common/PinMessageModal.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.tsx","webpack:///./src/components/middle/DeleteSelectedMessagesModal.tsx","webpack:///./src/components/middle/MessageSelectToolbar.tsx","webpack:///./src/hooks/useSelectWithEnter.ts","webpack:///./src/components/left/search/LeftSearchResultChat.tsx","webpack:///./src/components/left/search/RecentContacts.tsx","webpack:///./src/components/left/search/ChatMessage.tsx","webpack:///./src/components/left/search/DateSuggest.tsx","webpack:///./src/components/left/search/ChatResults.tsx","webpack:///./src/components/left/search/ChatMessageResults.tsx","webpack:///./src/components/left/search/helpers/createMapStateToProps.ts","webpack:///./src/components/left/search/MediaResults.tsx","webpack:///./src/components/left/search/helpers/getSenderName.ts","webpack:///./src/components/left/search/LinkResults.tsx","webpack:///./src/components/left/search/FileResults.tsx","webpack:///./src/components/left/search/AudioResults.tsx","webpack:///./src/components/left/search/LeftSearch.tsx","webpack:///./src/hooks/useReducer.ts","webpack:///./src/hooks/reducers/useFoldersReducer.ts","webpack:///./src/hooks/reducers/useTwoFaReducer.ts","webpack:///./src/components/left/settings/SettingsHeader.tsx","webpack:///./src/components/left/settings/SettingsMain.tsx","webpack:///./src/components/ui/FloatingActionButton.tsx","webpack:///./src/components/common/UsernameInput.tsx","webpack:///./src/components/left/settings/SettingsEditProfile.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersMain.tsx","webpack:///./src/components/ui/ShowMoreButton.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersEdit.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatsPicker.tsx","webpack:///./src/components/left/settings/folders/SettingsFoldersChatFilters.tsx","webpack:///./src/components/left/settings/folders/SettingsFolders.tsx","webpack:///./src/components/ui/RangeSlider.tsx","webpack:///./src/components/middle/composer/StickerSetCoverAnimated.tsx","webpack:///./src/components/middle/composer/StickerSetCover.tsx","webpack:///./src/components/common/StickerButton.tsx","webpack:///./src/components/left/settings/SettingsStickerSet.tsx","webpack:///./src/components/left/settings/SettingsGeneral.tsx","webpack:///./src/util/systemFilesDialog.ts","webpack:///./src/util/colors.ts","webpack:///./src/components/left/settings/WallpaperTile.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackground.tsx","webpack:///./src/components/left/settings/SettingsGeneralBackgroundColor.tsx","webpack:///./src/components/left/settings/SettingsNotifications.tsx","webpack:///./src/components/left/settings/SettingsPrivacy.tsx","webpack:///./src/components/left/settings/SettingsLanguage.tsx","webpack:///./src/components/left/settings/helper/privacy.ts","webpack:///./src/components/left/settings/SettingsPrivacyVisibility.tsx","webpack:///./src/components/left/settings/SettingsPrivacyActiveSessions.tsx","webpack:///./src/components/left/settings/SettingsPrivacyBlockedUsers.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEnabled.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaPassword.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaStart.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaSkippableForm.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaCongratulations.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFaEmailCode.tsx","webpack:///./src/components/left/settings/twoFa/SettingsTwoFa.tsx","webpack:///./src/components/common/Picker.tsx","webpack:///./src/components/left/settings/SettingsPrivacyVisibilityExceptionList.tsx","webpack:///./src/components/left/settings/Settings.tsx","webpack:///./src/components/left/main/ContactList.tsx","webpack:///./src/components/left/newChat/NewChatStep1.tsx","webpack:///./src/components/left/newChat/NewChatStep2.tsx","webpack:///./src/components/left/newChat/NewChat.tsx","webpack:///./src/components/left/ArchivedChats.tsx","webpack:///./src/util/scrollLock.ts","webpack:///./src/components/middle/message/helpers/copyOptions.ts","webpack:///./src/components/middle/message/MessageContextMenu.tsx","webpack:///./src/components/middle/message/ContextMenuContainer.tsx","webpack:///./src/components/common/StickerSetModal.tsx","webpack:///./src/components/middle/HeaderMenuContainer.tsx","webpack:///./src/components/middle/MobileSearch.tsx","webpack:///./src/util/findInViewport.ts","webpack:///./src/util/isFullyVisible.ts","webpack:///./src/components/middle/composer/MentionTooltip.tsx","webpack:///./src/components/middle/composer/AttachmentModal.tsx","webpack:///./src/components/middle/composer/PollModal.tsx","webpack:///./src/hooks/useMouseInside.ts","webpack:///./src/components/middle/composer/EmojiButton.tsx","webpack:///./src/components/middle/composer/EmojiCategory.tsx","webpack:///./src/components/middle/composer/EmojiPicker.tsx","webpack:///./src/components/middle/composer/StickerSet.tsx","webpack:///./src/components/middle/composer/StickerPicker.tsx","webpack:///./src/components/common/GifButton.tsx","webpack:///./src/components/middle/composer/GifPicker.tsx","webpack:///./src/components/middle/composer/SymbolMenuFooter.tsx","webpack:///./src/components/middle/composer/SymbolMenu.tsx","webpack:///./src/components/middle/composer/AttachMenu.tsx","webpack:///./src/components/middle/composer/StickerTooltip.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.tsx","webpack:///./src/components/middle/composer/EmojiTooltip.tsx","webpack:///./src/components/right/RightSearch.tsx","webpack:///./src/components/right/StickerSetResult.tsx","webpack:///./src/components/right/StickerSearch.tsx","webpack:///./src/components/right/GifSearch.tsx","webpack:///./src/components/right/PollAnswerResults.tsx","webpack:///./src/components/right/PollResults.tsx","webpack:///./src/components/right/management/ManageUser.tsx","webpack:///./src/components/right/management/ManageGroup.tsx","webpack:///./src/components/right/management/ManageGroupPermissions.tsx","webpack:///./src/components/right/management/ManageGroupRemovedUsers.tsx","webpack:///./src/components/right/management/ManageChannel.tsx","webpack:///./src/components/right/management/ManageChatPrivacyType.tsx","webpack:///./src/components/right/management/ManageDiscussion.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissions.tsx","webpack:///./src/components/right/management/ManageChatAdministrators.tsx","webpack:///./src/components/right/management/ManageGroupRecentActions.tsx","webpack:///./src/components/right/management/ManageGroupAdminRights.tsx","webpack:///./src/components/right/management/ManageGroupMembers.tsx","webpack:///./src/components/right/management/ManageGroupUserPermissionsCreate.tsx","webpack:///./src/components/right/management/Management.tsx","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/components/common/helpers/detectCardType.ts","webpack:///./src/hooks/reducers/usePaymentReducer.ts","webpack:///./src/hooks/useFocusAfterAnimation.tsx","webpack:///./src/components/ui/Select.tsx","webpack:///./src/components/payment/ShippingInfo.tsx","webpack:///./src/components/payment/Shipping.tsx","webpack:///./src/components/payment/Checkout.tsx","webpack:///./src/components/payment/ExpiryInput.tsx","webpack:///./src/components/middle/helpers/inputFormatters.ts","webpack:///./src/assets/mastercard.svg","webpack:///./src/assets/visa.svg","webpack:///./src/components/payment/CardInput.tsx","webpack:///./src/components/payment/PaymentInfo.tsx","webpack:///./src/components/payment/PaymentModal.tsx","webpack:///./src/components/payment/ReceiptModal.tsx","webpack:///./src/components/common/helpers/animatedAssets.ts","webpack:///./src/assets/TwoFactorSetupMonkeyIdle.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyTracking.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyClose.tgs","webpack:///./src/assets/TwoFactorSetupMonkeyPeek.tgs","webpack:///./src/assets/FoldersAll.tgs","webpack:///./src/assets/FoldersNew.tgs","webpack:///./src/assets/DiscussionGroupsDucks.tgs","webpack:///./src/components/ui/CropModal.tsx","webpack:///./src/components/ui/AvatarEditable.tsx","webpack:///./src/components/common/PasswordMonkey.tsx","webpack:///./src/components/common/PasswordForm.tsx"],"names":["animateOpening","hasFooter","origin","bestImageData","message","mediaEl","fromImage","getNodes","width","windowWidth","windowSize","get","mediaSize","isVideo","photo","video","webPage","getMessageContent","Boolean","getVideoDimensions","getPhotoFullDimensions","AVATAR_FULL_DIMENSIONS","availableWidth","height","availableHeight","getMediaViewerAvailableDimensions","toWidth","toHeight","calculateDimensions","toLeft","toTop","mql","window","matchMedia","MEDIA_VIEWER_MEDIA_QUERY","topOffsetRem","matches","REM","getTopOffset","top","fromTop","left","fromLeft","fromWidth","fromHeight","getBoundingClientRect","MediaViewerOrigin","SharedMedia","Album","ScheduledAlbum","SearchResult","includes","uncovered","realWidth","realHeight","size","Math","max","srcWidth","srcHeight","uncover","fromTranslateX","fromTranslateY","fromScaleX","fromScaleY","ghost","createGhost","applyStyles","transform","applyShape","document","body","classList","add","requestAnimationFrame","appendChild","style","firstChild","objectFit","remove","clearShape","setTimeout","contains","removeChild","ANIMATION_END_DELAY","animateClosing","container","toImage","getElementById","querySelector","targetTop","el","display","rect","windowHeight","isElementInViewport","shouldFadeOut","Inline","ScheduledInline","isMessageImageFullyVisible","existingGhost","getElementsByClassName","ProfileAvatar","transition","transformOrigin","opacity","source","shouldAppendProfileInfo","createElement","img","Image","src","HTMLVideoElement","poster","profileInfo","cloneNode","imageEl","messageListElement","imgOffsetTop","offsetTop","closest","id","parentElement","scrollTop","offsetHeight","element","styles","Object","assign","containerSelector","mediaSelector","MiddleHeaderAvatar","mediaEls","querySelectorAll","length","withGlobal","global","chatId","messageId","isAvatar","sender","isChatPrivate","selectUser","selectChat","selectChatMessage","selectSender","setGlobal","actions","pick","closeMediaViewer","focusMessage","handleFocusMessage","useCallback","lang","useLang","isFromChat","senderTitle","getSenderTitle","className","onClick","Avatar","key","chat","user","dir","renderText","formatMediaDateTime","date","MediaViewerActions","mediaData","isZoomed","fileName","onCloseMediaViewer","onForward","onZoomToggle","isVideoDownloadAllowed","setIsVideoDownloadAllowed","useState","videoMediaHash","getMessageMediaHash","undefined","videoBlobUrl","downloadProgress","useMediaWithDownloadProgress","useEffect","download","handleVideoDownloadClick","e","stopPropagation","isAllowed","MenuButton","useMemo","onTrigger","isOpen","Button","round","color","ariaLabel","IS_MOBILE_SCREEN","DropdownMenu","trigger","positionX","MenuItem","icon","href","ProgressSpinner","progress","noCross","MediaViewerFooter","text","isHideable","isMultiline","setIsMultiline","footerContent","checkIsMultiline","clientHeight","handleResize","throttle","addEventListener","removeEventListener","prop","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","getBrowserFullscreenElementProp","units","bytes","number","floor","log","toFixed","stopEvent","VideoPlayerControls","bufferedProgress","currentTime","duration","fileSize","isForceVisible","isForceMobileVersion","isPlayed","isFullscreenSupported","isFullscreen","onChangeFullscreen","onPlayPause","onSeek","isVisible","setVisibility","timeout","clearTimeout","downloadedPercent","totalSize","percentagePlayed","percentageBuffered","min","step","type","onInput","value","renderSeekLine","ripple","formatMediaDuration","renderTime","formatFileSize","memo","url","isGif","posterData","posterSize","isMediaViewerOpen","noPlay","onClose","videoRef","useRef","setIsPlayed","IS_TOUCH_ENV","IS_IOS","setCurrentTime","isControlsVisible","setIsControlsVisible","setFullscreen","exitFullscreen","elRef","setIsFullscreen","useLayoutEffect","listener","listenerEnter","listenerExit","current","PLATFORM_ENV","requestFullscreen","webkitRequestFullscreen","webkitEnterFullscreen","mozRequestFullScreen","mozCancelFullScreen","webkitCancelFullScreen","webkitExitFullscreen","useFullscreenStatus","isBuffered","bufferingHandlers","useBuffering","shouldRender","shouldRenderSpinner","transitionClassNames","spinnerClassNames","useShowTransition","pause","safePlay","togglePlayState","play","useVideoCleanup","handleMouseOver","handleMouseOut","handleTimeUpdate","currentTarget","handleEnded","handleFullscreenChange","handleSeek","Number","target","toggleControls","togglePayingStateBySpace","wrapperStyle","videoStyle","onMouseOver","onMouseOut","ref","autoPlay","playsInline","loop","muted","onEnded","onTimeUpdate","join","square","isShown","onChangeZoom","prevIsShown","usePrevious","inputRef","zoomLevel","setZoomLevel","isSeeking","handleStartSeek","handleStopSeek","buildClassName","disabled","onChange","onMouseDown","onMouseUp","INITIAL_MATRIX","SCALE_VALUES","1","1.5","2","2.5","3","children","noWrap","canPan","panDeltaX","panDeltaY","onPan","tunedZoomLevel","isDragging","setIsDragging","dragData","setDragData","dx","dy","x","y","matrixData","setMatrixData","panWrapperRef","panContainerRef","newZoomLevel","newPandx","newPandy","newMatrixData","areSortedArraysEqual","oldScale","wrapper","image","wrapperRect","imageRect","newImgWidth","newImgHeight","newImgX","newImgY","calculateSafeZoneOnZoom","toString","preventDefault","newDragData","pageX","pageY","onMouseMove","deltaX","deltaY","getNewMatrixData","renderPhoto","blobUrl","imageSize","canDrag","alt","draggable","Spinner","threadId","avatarOwnerId","profilePhotoIndex","mediaViewer","animationLevel","settings","byKey","senderId","avatarOwner","chatMessages","collectionIds","selectScheduledMessage","selectScheduledMessages","selectChatMessages","selectOutlyingIds","selectListedIds","currentSearch","selectCurrentMediaSearch","foundIds","resultsByType","media","openMediaViewer","openForwardMenu","animationKey","webPagePhoto","getMessageWebPagePhoto","getMessagePhoto","getMessageVideo","isWebPagePhoto","isPhoto","isFromSharedMedia","isFromSearch","slideAnimation","headerAnimation","isGhostAnimation","getMessageMediaFilename","prevSenderId","canPanZoomWrap","setCanPanZoomWrap","setIsZoomed","panDelta","setPanDelta","messageIds","getChatMediaMessageIds","selectedMediaMessageIndex","indexOf","isFirst","isLast","getMediaHash","full","photos","getChatAvatarHash","blobUrlPictogram","useMedia","ApiMediaFormat","BlobUrl","previewMediaHash","blobUrlPreview","startsWith","DataUri","fullMediaData","getMessageMediaFormat","localBlobUrl","thumbDataUri","useBlurSync","getMessageMediaThumbDataUri","photoDimensions","videoDimensions","toggle","forceUpdate","useForceUpdate","addListener","removeListener","prevMessage","prevOrigin","prevAvatarOwner","prevBestImageData","dispatchHeavyAnimationEvent","textParts","renderMessageText","timer","closeZoom","handleZoomToggle","handleZoomValue","level","canCloseZoom","close","handleFooterClick","handleForward","fromChatId","captureEscKeyListener","stopCurrentAudio","getMessageId","fromId","direction","index","selectPreviousMedia","selectNextMedia","handleKeyDown","shouldCloseOnVideo","captureEvents","excludedClosestSelector","onSwipe","SwipeDirection","Right","Left","handlePan","renderSlide","isActive","calculateMediaViewerDimensions","renderSenderInfo","ShowTransition","isRtl","Transition","activeKey","name","aria-label","chats","byId","chatsById","listIds","currentUserId","activeListIds","active","archivedListIds","archived","setForwardChatId","exitForwardMode","loadMoreChats","filter","setFilter","focus","blur","chatIds","sortChatIds","getCanPostInChat","MAIN_THREAD_ID","searchWords","getChatTitle","viewportIds","getMore","useInfiniteScroll","handleFilterChange","containerRef","useKeyboardListNavigation","modalHeader","InputText","onKeyDown","placeholder","Modal","header","InfiniteScroll","items","onLoadMore","noScrollRestore","map","ListItem","PrivateChatInfo","status","userId","GroupChatInfo","Loading","getErrorHeader","error","isSlowMode","errors","dismissError","title","getReadableErrorText","isText","notifications","dismissNotification","Notification","onDismiss","toggleSafeLinkModal","handleOpen","open","handleDismiss","renderingUrl","useCurrentOrPrev","ConfirmDialog","confirmLabel","confirmHandler","WEEKDAY_LETTERS","isDisabledDay","year","month","day","minDate","maxDate","selectedDay","Date","fixedMinDate","getFullYear","getMonth","getDate","fixedMaxDate","formatInputTime","String","padStart","selectedAt","maxAt","isFutureMode","isPastMode","withTimePicker","submitButtonLabel","secondButtonLabel","onSubmit","onSecondButtonClick","now","defaultSelectedDate","selectedDate","setSelectedDate","selectedHours","setSelectedHours","getHours","selectedMinutes","setSelectedMinutes","getMinutes","currentYear","currentMonth","currentDate","shouldDisableNextMonth","shouldDisablePrevMonth","calendarGrid","grid","setFullYear","setMonth","setDate","monthStartDay","getDay","i","push","gridDate","buildCalendarGrid","handleChangeHours","replace","hours","getTime","setHours","hoursStr","handleChangeMinutes","minutes","setMinutes","minutesStr","formatMonthAndYear","d","dateCopy","letter","role","tabIndex","handleDateSelect","inputMode","formatHumanDate","formatTime","formatSubmitLabel","historyCalendarSelectedAt","searchMessagesByDate","closeHistoryCalendar","handleJumpToDate","timestamp","valueOf","isSchedule","selectCurrentMessageList","canDeleteForAll","selectAllowedMessageActions","contactName","getUserFirstOrLastName","getPrivateChatUserId","willDeleteForCurrentUserOnly","isChatBasicGroup","willDeleteForAll","isChatSuperGroup","album","deleteMessages","deleteScheduledMessages","handleDeleteMessageForAll","messages","shouldDeleteForAll","handleDeleteMessageForSelf","onEnter","isPrivateChat","isChatWithSelf","selectIsChatWithSelf","isChannel","isChatChannel","isGroup","isSuperGroup","canPinForAll","pinMessage","handlePinMessageForAll","isUnpin","handlePinMessage","isOneSide","isSilent","pinnedMessagesCount","onUnpin","selectedMessageIds","selectedMessages","selectCanDeleteSelectedMessages","selectCurrentChat","exitMessageSelectMode","messageListType","canDelete","selectedMessagesCount","selectSelectedMessagesCount","canDeleteMessages","canPost","openForwardMenuForSelectedMessages","isDeleteModalOpen","openDeleteModal","closeDeleteModal","useFlag","captureKeyboardListeners","onBackspace","onDelete","onEsc","prevSelectedMessagesCount","renderingSelectedMessagesCount","formattedMessagesCount","destructive","onSelect","buttonRef","activeElement","privateChatUserId","privateChatUser","isPinned","selectIsChatPinned","withUsername","contextActions","useChatContextActions","handleDelete","handleClick","useSelectWithEnter","avatarSize","DeleteChatModal","runThrottled","cb","userIds","topUserIds","topPeers","usersById","users","recentlyFoundChatIds","globalSearch","onReset","loadTopUsers","loadContactList","openChat","addRecentlyFoundChatId","clearRecentlyFoundChats","topUsersRef","useHorizontalScroll","lastSyncTime","searchQuery","mediaThumbnail","mediaBlobUrl","isRoundVideo","getMessageRoundVideo","withOnlineStatus","isSavedMessages","isSelf","isVerified","VerifiedIcon","Link","formatPastTimeShort","getMessageSummaryText","highlight","renderMessageSummary","searchDate","suggestions","match","formatDateToString","suggestion","latestYear","getSuggestionsFromDate","localContactIds","contactList","fetchingStatus","globalResults","localResults","globalChatIds","globalUserIds","localChatIds","localUserIds","byChatId","globalMessagesByChatId","dateSearchQuery","onSearchDateSelect","searchMessagesGlobal","setGlobalSearchChatId","shouldShowMoreLocal","setShouldShowMoreLocal","shouldShowMoreGlobal","setShouldShowMoreGlobal","handleLoadMore","LoadMoreDirection","Backwards","query","handleChatClick","handlePickerItemClick","MEMO_EMPTY_ARRAY","foundContactIds","fullName","getUserFullName","username","unique","foundMessages","split","sort","a","b","handleClickShowMoreLocal","handleClickShowMoreGlobal","nothingFound","noScrollRestoreOnTop","noFastList","NothingFound","description","PickerSelectedItem","chatOrUserId","clickArg","createMapStateToProps","props","currentType","isVoice","isLoading","searchChatId","handleSelectMedia","canRenderContents","useAsyncRendering","SLIDE_TRANSITION_DURATION","isMediaGrid","isMessageList","classNames","itemSelector","Media","idPrefix","getSenderName","senderName","isChatGroup","handleMessageFocus","shouldDrawDateDivider","toYearMonth","WebLink","onMessageClick","getMessageDocument","Document","withDate","datetime","smaller","onDateClick","openAudioPlayer","handlePlayAudio","Audio","renderingFor","onPlay","TABS","GlobalSearchContent","ChatList","Links","Files","Music","Voice","CHAT_TABS","slice","TRANSITION_RENDER_COUNT","keys","currentContent","setGlobalSearchContent","setGlobalSearchDate","activeTab","setActiveTab","parseDateString","handleSwitchTab","tab","content","handleSearchDateSelect","TabList","tabs","onSwitchTab","renderCount","useReducer","reducer","initialState","reducerRef","state","setState","action","currentState","INCLUDED_CHAT_TYPES","EXCLUDED_CHAT_TYPES","INCLUDE_FILTER_FIELDS","EXCLUDE_FILTER_FIELDS","selectChatFilters","mode","selectTemp","selectedChatIds","selectedChatTypes","includedChatIds","includeFilters","folder","excludedChatIds","excludeFilters","getSuggestedFolderName","filters","values","bots","groups","channels","contacts","nonContacts","INITIAL_STATE","chatFilter","foldersReducer","payload","isTouched","omit","folderId","currentPassword","password","hint","email","twoFaReducer","currentScreen","editedFolderId","onSaveFilter","signOut","deleteChatFolder","isSignOutDialogOpen","setIsSignOutDialogOpen","isDeleteFolderDialogOpen","setIsDeleteFolderDialogOpen","openSignOutConfirmation","closeSignOutConfirmation","openDeleteFolderConfirmation","closeDeleteFolderConfirmation","handleSignOutMessage","handleDeleteFolderMessage","SettingsMenuButton","SettingsScreens","EditProfile","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyPhoneNumberAllowedContacts","PrivacyLastSeenAllowedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyForwardingAllowedContacts","PrivacyGroupChatsAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsDeniedContacts","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaNewPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaChangePasswordHint","TwoFaNewPasswordEmail","TwoFaRecoveryEmail","TwoFaNewPasswordEmailCode","TwoFaRecoveryEmailCode","TwoFaCongratulations","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","Folders","FoldersCreateFolder","FoldersEditFolder","FoldersIncludedChats","FoldersExcludedChats","renderHeaderContent","confirmIsDestructive","currentUser","onScreenSelect","formatPhoneNumberWithCode","phoneNumber","FloatingActionButton","buttonClassName","LINK_PREFIX_REGEX","USERNAME_REGEX","runDebouncedForCheckUsername","debounce","currentUsername","asLink","isUsernameAvailable","checkUsername","setUsername","langPrefix","label","usernameSuccess","usernameError","test","handleUsernameChange","newUsername","trim","isValid","isUsernameValid","success","readOnly","profileEdit","firstName","currentFirstName","lastName","currentLastName","fullInfo","bio","currentBio","currentAvatarHash","loadCurrentUser","updateProfile","isUsernameTouched","setIsUsernameTouched","isProfileFieldsTouched","setIsProfileFieldsTouched","setError","setPhoto","setFirstName","setLastName","setBio","currentAvatarBlobUrl","ProfileEditProgress","InProgress","isUsernameError","isSaveButtonShown","Complete","handlePhotoChange","newPhoto","handleFirstNameChange","handleLastNameChange","handleBioChange","handleProfileSave","trimmedFirstName","trimmedLastName","trimmedBio","AvatarEditable","UsernameInput","runThrottledForLoadRecommended","orderedIds","orderedFolderIds","foldersById","recommended","recommendedChatFolders","chatFolders","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","onCreateFolder","onEditFolder","loadRecommendedChatFolders","addChatFolder","showError","animationData","setAnimationData","isAnimationLoaded","setIsAnimationLoaded","handleAnimationLoad","getAnimationData","then","handleCreateFolder","userFolders","subtitle","getFolderDescriptionText","handleCreateFolderFromRecommended","AnimatedSticker","STICKER_SIZE_FOLDER_SETTINGS","noLoop","onLoad","pill","fluid","narrow","multiline","ShowMoreButton","count","itemName","itemPluralName","ERROR_NO_TITLE","ERROR_NO_CHATS","loadedActiveChatIds","loadedArchivedChatIds","dispatch","onAddIncludedChats","onAddExcludedChats","editChatFolder","isIncludedChatsListExpanded","setIsIncludedChatsListExpanded","isExcludedChatsListExpanded","setIsExcludedChatsListExpanded","includedChatTypes","excludedChatTypes","visibleIncludedChatIds","visibleExcludedChatIds","allLoadedChatsSet","Set","loadedIncludedChatIds","findIntersectionWithSet","loadedExcludedChatIds","listType","renderChats","visibleChatIds","isExpanded","leftChatsCount","clickHandler","chatType","find","typeKey","inactive","renderChatType","event","folderUpdate","selectedIds","filterValue","onSelectedIdsChange","onSelectedChatTypesChange","onFilterChange","chatTypes","shouldMinimize","hasMaxChats","handleItemClick","newSelectedIds","splice","handleChatTypeClick","newSelectedChatTypes","selectedType","isMinimized","canClose","Checkbox","checked","isSelected","withChatType","orderedPinnedIds","archivedPinnedIds","activeChatArrays","prepareChatList","archivedChatArrays","pinnedChats","otherChats","displayedIds","newFilter","handleSelectedIdsChange","ids","handleSelectedChatTypesChange","newFilters","forEach","handleReset","handleEditFolder","handleAddIncludedChats","handleAddExcludedChats","options","range","handleChange","trackWidth","possibleValuesLength","option","STICKER_SIZE_PICKER_HEADER","stickerSet","observeIntersection","isIntersecting","useIsIntersecting","mediaHash","lottieData","Lottie","shouldRenderFullMedia","useTransitionForMedia","getFirstLetters","hasThumbnail","sticker","noAnimate","onUnfaveClick","localMediaHash","stickerSelector","thumbnail","dataUri","previewBlobUrl","shouldPlay","isAnimated","markLoaded","unmarkLoaded","canAnimatedPlay","shouldRenderThumb","shouldRenderPreview","previewTransitionClassNames","fullClassName","emoji","data-sticker-id","isLowPriority","stickers","firstSticker","STICKER_SIZE_GENERAL_SETTINGS","ANIMATION_LEVEL_OPTIONS","stickerSetIds","added","setIds","stickerSetsById","setsById","messageTextSize","messageSendKeyCombo","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayGifs","shouldAutoPlayVideos","shouldSuggestStickers","shouldLoopStickers","setSettingOption","loadStickerSets","loadAddedStickers","stickerSettingsRef","observe","observeIntersectionForCovers","useIntersectionObserver","rootRef","isModalOpen","openModal","closeModal","setSticker","KEYBOARD_SEND_OPTIONS","subLabel","IS_MAC_OS","handleAnimationLevelChange","newLevel","_","handleMessageTextSizeChange","newSize","documentElement","setProperty","handleStickerSetClick","stickerSets","installedDate","RadioGroup","selected","onCheck","isChecked","fromSticker","fileSelector","openSystemFilesDialog","accept","callback","noMultiple","setAttribute","removeAttribute","onchange","click","hex2rgb","param","parseInt","substring","rgb2hex","p0","p1","p2","rgb2hsb","r","g","h","s","v","hsb2rgb","f","p","q","t","getPatternColor","rgbColor","hue","saturation","wallpaper","theme","slug","thumbRef","useCanvasBlur","isDownloadAllowed","setIsDownloadAllowed","fullMedia","wasDownloadDisabled","UPLOADING_WALLPAPER_SLUG","cacheKeyRef","handleSelect","blob","fetchBlob","cacheApi","CUSTOM_BG_CACHE_NAME","background","isBlurred","themes","loadedWallpapers","loadWallpapers","uploadWallpaper","setThemeSettings","themeRef","handleFileSelect","files","handleUploadWallpaper","handleSetColor","handleResetToDefault","backgroundColor","patternColor","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","handleWallPaperSelect","currentWallpaper","async","defaultRGB","data","rgb","canvas","context","getContext","preloadImage","naturalHeight","naturalWidth","offsetWidth","drawImage","getImageData","blockSize","getAverageColor","handleWallPaperBlurChange","isUploading","DEFAULT_HSB","PREDEFINED_COLORS","hsb2positions","hsb","rects","colorPosition","colorRect","huePosition","hueRect","positions2hsb","colorPickerRef","huePickerRef","isFirstRunRef","setHsb","getInitialHsb","hsbRef","markIsDragging","unmarkIsDragging","rgbInput","setRgbInput","hexInput","setHexInput","rectsRef","colorCtxRef","offsetLeft","handleColorDrag","handleHueDrag","onCapture","onDrag","onRelease","withCursor","hex","hueHex","w","ctx","imgData","createImageData","pixels","col","perY","st","ed","perX","putImageData","drawColor","drawHue","handleRgbChange","rgbValue","channel","handleHexChange","hexValue","handlePredefinedColorClick","dataset","data-color","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","hasContactJoinedNotifications","loadNotificationSettings","updateContactSignUpNotification","updateNotificationSettings","handleSettingsChange","peerType","setting","currentIsSilent","currentShouldShowPreviews","shouldShowPreviews","handleContactNotificationChange","hasPassword","privacy","blocked","activeSessions","blockedCount","totalCount","sessionsCount","visibilityPrivacyPhoneNumber","visibility","visibilityPrivacyLastSeen","lastSeen","visibilityPrivacyProfilePhoto","profilePhoto","visibilityPrivacyForwarding","forwards","visibilityPrivacyGroupChats","chatInvite","loadPrivacySettings","loadBlockedContacts","loadAuthorizations","getVisibilityValue","languages","language","loadLanguages","selectedLanguage","setSelectedLanguage","markIsLoading","unmarkIsLoading","langCode","setLanguage","currentLangCode","navigator","toLowerCase","shortLangCode","substr","nativeName","buildOptions","loadingOption","getPrivacyKey","screen","privacySettings","allowUserIds","allowChatIds","blockUserIds","blockChatIds","setPrivacyVisibility","visibilityOptions","exceptionLists","shouldShowDenied","shouldShowAllowed","privacyKey","headerText","descriptionText","allowedContactsScreen","deniedContactsScreen","allowedCount","reduce","result","membersCount","blockCount","handleVisibilityChange","getLocation","session","region","country","getDeviceEnvironment","deviceModel","platform","systemVersion","terminateAuthorization","terminateAllAuthorizations","isConfirmTerminateAllDialogOpen","openConfirmTerminateAllDialog","closeConfirmTerminateAllDialog","handleTerminateSessionClick","hash","handleTerminateAllSessions","currentSession","isCurrent","otherSessions","renderSession","handler","dateActive","appName","ip","sessions","chatsByIds","usersByIds","blockedIds","unblockContact","handleUnblockClick","contactId","viewportOffset","isPrivate","CHAT_HEIGHT_PX","renderContact","animatedEmoji","selectAnimatedEmoji","AnimatedEmoji","expectedPassword","submitLabel","clearError","validationError","setValidationError","shouldShowPassword","setShouldShowPassword","handleSubmit","newPassword","handleClearError","PasswordMonkey","isBig","isPasswordVisible","PasswordForm","onChangePasswordVisibility","onStart","FOCUS_DELAY_TIMEOUT_MS","shouldConfirm","setValue","isConfirmShown","markIsConfirmShown","unmarkIsConfirmShown","codeLength","twoFaSettings","waitingEmailCodeLength","newValue","updatePassword","checkPassword","clearTwoFaError","updateRecoveryEmail","provideTwoFaEmailCode","clearPassword","handleStartWizard","handleNewPassword","handleNewPasswordConfirm","handleNewPasswordHint","handleNewPasswordEmail","onSuccess","handleChangePasswordCurrent","handleChangePasswordNew","handleChangePasswordConfirm","handleChangePasswordHint","handleTurnOff","handleRecoveryEmailCurrentPassword","handleRecoveryEmail","handleEmailCode","code","itemIds","filterPlaceholder","notFoundText","searchInputId","getCurrentPrivacySettings","isAllowList","setPrivacySettings","selectedContactIds","setSearchQuery","isSubmitShown","setIsSubmitShown","newSelectedContactIds","setNewSelectedContactIds","handleSelectedContactIdsChange","contactsIds","foldersState","foldersDispatch","twoFaState","twoFaDispatch","handleSaveFilter","renderCurrentSection","Main","renderCurrentSectionContent","contactIds","resultIds","sortUserIds","forceShowSelf","isSearching","selectedMemberIds","onSelectedMemberIdsChange","onNextStep","setGlobalSearchQuery","handleNextStep","creationProgress","creationError","chatCreation","memberIds","createGroupChat","createChannel","setTitle","about","setAbout","ChatCreationProgress","handleTitleChange","handleDescriptionChange","handleCreateGroup","handleCreateChannel","renderedError","RENDER_COUNT","LeftColumnContent","onContentChange","newChatMemberIds","setNewChatMemberIds","NewChannelStep2","NewGroupStep2","NewChannelStep1","NewGroupStep1","folderType","noChatsText","IGNORED_KEYS","Down","ArrowDown","Up","ArrowUp","ArrowLeft","ArrowRight","PageUp","PageDown","End","Home","Tab","preventDefaultForScrollKeys","disableScrolling","passive","ontouchmove","onkeydown","enableScrolling","getCopyLabel","hasSelection","canImageBeCopied","MessageContextMenu","anchor","canSendNow","canReschedule","canReply","canEdit","canPin","canUnpin","canForward","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","onReply","onEdit","onPin","onFaveSticker","onUnfaveSticker","onSend","onReschedule","onCloseAnimationEnd","onCopyLink","copyOptions","afterEffect","getMessageText","CLIPBOARD_ITEM_SUPPORTED","selection","getSelection","mediaLoader","copyImageToClipboard","anchorNode","parentNode","clipboardText","copyTextToClipboard","getMessageCopyOptions","getTriggerElement","getRootElement","getMenuElement","positionY","useContextMenuPosition","Menu","noOptions","isScheduled","setReplyingToId","setEditingId","faveSticker","unfaveSticker","toggleMessageSelection","sendScheduledMessages","rescheduleMessage","loadMessageLink","isMenuOpen","setIsMenuOpen","setIsDeleteModalOpen","isPinModalOpen","setIsPinModalOpen","isCalendarOpen","openCalendar","closeCalendar","closeMenu","closePinModal","handleCloseCalendar","handleReply","handleEdit","handlePin","handleUnpin","handleFaveSticker","handleUnfaveSticker","handleSelectMessage","params","childMessageIds","withShift","handleScheduledMessageSend","handleOpenCalendar","handleRescheduleMessage","scheduledAt","handleCopyLink","scheduledMaxDate","getDayStartAt","selectStickerSet","stickerSetId","loadStickers","toggleStickerSet","sendMessage","throttleMs","isDisabled","stickerSetAccessHash","isPreloadedGlobally","handleButtonClick","hasCloseButton","STICKER_SIZE_MODAL","isRestricted","isMuted","canDeleteChat","getCanDeleteChat","canSubscribe","canSearch","canMute","canLeave","onSubscribeChannel","onSearchClick","updateChatMutedState","enterMessageSelectMode","handleToggleMuteClick","handleSubscribe","handleSearch","handleSelectMessages","Portal","runDebouncedForSearch","results","selectCurrentTextSearch","isHistoryCalendarOpen","setLocalTextSearchQuery","searchTextMessagesLocal","closeLocalTextSearch","openHistoryCalendar","focusedIndex","setFocusedIndex","visualViewport","mainEl","pageTop","Array","from","input","div","contentEditable","handleMessageSearchQueryChange","newQuery","handleUp","newFocusIndex","handleDown","SearchInput","findInViewport","selectorOrElements","margin","isDense","shouldContainBottom","isHorizontal","viewportY1","viewportY2","allElements","visibleIndexes","isFound","y1","y2","isFullyVisible","onInsertUserName","filteredChatMembers","getSelectedIndex","newIndex","cycleRestrict","selectedMentionIndex","setSelectedMentionIndex","handleArrowKey","handleUserSelect","forceFocus","handleSelectMention","member","onUp","onDown","onTab","first","position","fastSmoothScroll","setItemVisible","prevChatMembers","renderedChatMembers","attachments","caption","canSuggestMembers","groupChatMembers","recentEmojis","onCaptionUpdate","addRecentEmoji","loadEmojiKeywords","onFileAppend","onClear","hideTimeoutRef","prevAttachments","renderingAttachments","isHovered","markHovered","unmarkHovered","isQuick","every","quick","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","insertMention","mentionFilteredMembers","useMentionTooltip","EDITABLE_INPUT_MODAL_ID","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","sendAttachments","handleFilesDrop","dataTransfer","newFiles","file","CONTENT_TYPES_FOR_QUICK_UPLOAD","areAllPhotos","mimeType","areAllVideos","renderHeader","onDragEnter","onDrop","onDragOver","onDragLeave","relatedTarget","toTarget","fromTarget","data-attach-description","attachment","File","filename","extension","getFileExtension","previewData","emojis","onEmojiSelect","MessageInput","html","editableInputId","onUpdate","shouldSetFocus","questionInputRef","optionsListRef","solutionRef","question","setQuestion","setOptions","isAnonymous","setIsAnonymous","isMultipleAnswers","setIsMultipleAnswers","isQuizMode","setIsQuizMode","solution","setSolution","correctOption","setCorrectOption","hasErrors","setHasErrors","focusInput","solutionEl","innerHTML","addNewOption","newOptions","list","scrollHeight","scrollTo","behavior","handleCreate","questionTrimmed","optionsTrimmed","o","summary","answers","correct","isPublic","multipleChoice","quiz","entities","parseMessageInput","correctAnswers","solutionEntities","updateOption","removeOption","handleCorrectOptionChange","handleIsAnonymousChange","handleMultipleAnswersChange","handleQuizModeChange","handleKeyPress","keyCode","getQuestionError","getOptionsError","renderOptions","onKeyPress","renderQuizNoOptionError","hidden","closeTimeout","useMouseInside","menuCloseTimeout","isMouseInside","native","names","IS_EMOJI_SUPPORTED","loading","category","allEmojis","useOnIntersect","emojisPerRow","ceil","displayedEmoji","ICONS_BY_CATEGORY","recent","people","nature","foods","activity","places","objects","symbols","flags","categoryIntersections","emojiDataPromise","emojiRawData","emojiData","headerRef","categories","setCategories","setEmojis","activeCategoryIndex","setActiveCategoryIndex","entries","entry","intersectingWithIndexes","newLeft","HEADER_BUTTON_WIDTH","fastSmoothScrollHorizontal","allCategories","themeCategories","unshift","exec","default","uncompressEmoji","ensureEmojiData","selectCategory","categoryEl","handleEmojiSelect","MENU_TRANSITION_DURATION","containerClassName","faded","STICKER_MARGIN","loadAndPlay","onStickerSelect","onStickerUnfave","stickersPerRow","STICKER_SIZE_PICKER","stickerSetIntersections","favorite","recentStickers","favoriteStickers","addedSetIds","canSendStickers","loadRecentStickers","loadFavoriteStickers","addRecentSticker","activeSetIndex","setActiveSetIndex","areAddedLoaded","allSets","noPopulatedSets","set","stickerSetEl","handleStickerSelect","handleStickerUnfave","gif","videoData","shouldRenderVideo","preload","savedGifs","gifs","saved","canSendGifs","onGifSelect","loadSavedGifs","debounceMs","SymbolMenuTabs","SYMBOL_MENU_TAB_TITLES","SYMBOL_MENU_TAB_ICONS","Emoji","Stickers","GIFs","onRemoveSymbol","onSearchOpen","renderTabButton","handleSearchOpen","isActivated","allowedAttachmentOptions","setRecentEmojis","handleMouseEnter","handleMouseLeave","fastRaf","recentEmojisRef","renderContent","isFrom","onMouseEnter","onMouseLeave","noCloseOnBackdrop","onFileSelect","onPollCreate","handleQuickSelect","handleDocumentSelect","canAttachMedia","canAttachPolls","autoClose","forEmoji","clearStickersForEmoji","prevStickers","displayedStickers","clickInlineButton","keyboardButtons","row","button","onSilentSend","onScheduleSend","listEmojis","usePrevDuringAnimation","selectedIndex","setSelectedIndex","emojisCount","handleSelectEmoji","onLeft","onRight","messagesById","foundResults","senderUser","getGlobal","senderChat","forwardInfo","isChannelPost","orderBy","preloadBackwards","LastMessageMeta","selectShouldLoopStickers","isSomeModalOpen","onModalToggle","isAdded","areStickersLoaded","useOnChange","coverStickerIds","covers","otherStickers","handleAddClick","canRenderStickers","STICKER_SIZE_SEARCH","selectCurrentStickerSearch","featured","featuredIds","loadFeaturedStickers","setIsModalOpen","selectCurrentGifSearch","isChatWithBot","selectIsChatWithBot","searchMoreGifs","setGifSearchQuery","getAllowedAttachmentOptions","handleGifClick","hasResults","answer","voters","offsets","pollResults","offset","answerVote","totalVoters","loadPollOptionResults","closePollResults","prevVotersCount","votersCount","setIsLoading","areVotersLoaded","limit","shouldResetVoters","handleViewMoreClick","handleMemberClick","noStatusOrTyping","leftVotersCount","renderViewMoreButton","total","getMessagePoll","resultsByOption","buildCollectionByKey","management","updateContact","deleteUser","deleteHistory","closeManagement","isDeleteDialogOpen","openDeleteDialog","closeDeleteDialog","currentIsMuted","isNotificationsEnabled","setIsNotificationsEnabled","ManagementProgress","handleNotificationChange","handleDeleteContact","withFullInfo","hasLinkedChannel","linkedChatId","isBasicGroup","canChangeInfo","getHasAdminRight","canBanUsers","togglePreHistoryHidden","updateChat","leaveChannel","deleteChannel","currentTitle","currentAbout","imageHash","handleClickEditType","ManagementScreens","ChatPrivacyType","handleClickDiscussion","Discussion","handleClickPermissions","GroupPermissions","handleClickAdministrators","ChatAdministrators","handleSetPhoto","handleAboutChange","handleUpdateGroup","trimmedTitle","trimmedAbout","handleClickMembers","GroupMembers","handleTogglePreHistory","isPreHistoryHidden","isEnabled","enabledPermissionsCount","defaultBannedRights","sendStickers","sendGifs","adminsCount","adminMembers","handleDeleteGroup","isCreator","formatInteger","onChatMemberSelect","updateChatDefaultBannedRights","permissions","setPermissions","havePermissionChanged","setHavePermissionChanged","handleRemovedUsersClick","GroupRemovedUsers","handleAddExceptionClick","GroupUserPermissionsCreate","handleExceptionMemberClick","promotedByUserId","GroupUserPermissions","handlePermissionChange","getUpdatedPermissionValue","handleSavePermissions","bannedRights","removedUsersCount","kickedMembers","exceptionMembers","members","getMemberExceptions","langKey","getLangKeyForBannedRightKey","translatedString","sendMessages","blocking","sendMedia","sendPolls","embedLinks","inviteUsers","pinMessages","changeInfo","updateChatMemberBannedRights","removedMembers","getRemovedBy","kickedByUserId","kickedByUser","getContextActions","isSignaturesShown","toggleSignatures","hasLinkedChat","handleUpdateChannel","handleToggleSignatures","handleClickSubscribers","ChannelSubscribers","handleDeleteChannel","selectManagement","checkPublicLink","updatePublicLink","updatePrivateLink","privateLink","inviteLink","privacyType","setPrivacyType","isRevokeConfirmDialogOpen","openRevokeConfirmDialog","closeRevokeConfirmDialog","canUpdate","handleOptionChange","handleSave","handleRevokePrivateLink","langPrefix1","langPrefix2","SafeLink","forDiscussionIds","linkedChat","loadGroupsForDiscussion","linkDiscussionGroup","unlinkDiscussionGroup","linkedGroupId","setLinkedGroupId","isConfirmUnlinkGroupDialogOpen","openConfirmUnlinkGroupDialog","closeConfirmUnlinkGroupDialog","isConfirmLinkGroupDialogOpen","openConfirmLinkGroupDialog","closeConfirmLinkGroupDialog","handleUnlinkGroupSessions","channelId","Initial","handleLinkGroupSessions","renderLinkGroupHeader","linkedGroup","renderLinkGroupConfirmText","hasPrivateLink","STICKER_SIZE_DISCUSSION_GROUPS","teactFastList","teactOrderKey","isButtonsInOneRow","isPromotedByCurrentUser","isFormFullyDisabled","selectedChatMemberId","isBanConfirmationDialogOpen","openBanConfirmationDialog","closeBanConfirmationDialog","selectedChatMember","handleBanFromGroup","viewMessages","getControlIsDisabled","isOwner","handleAdminMemberClick","ChatAdminRights","getMemberStatus","promotedByUser","GroupRecentActions","updateChatAdmin","setIsTouched","isDismissConfirmationDialogOpen","openDismissConfirmationDialog","closeDismissConfirmationDialog","customTitle","setCustomTitle","adminRights","handleDismissAdmin","memberStatus","handleCustomTitleChange","postMessages","editMessages","banUsers","addAdmins","anonymous","maxLength","openUserInfo","memberId","managementType","selectCurrentManagementType","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","VISA","MASTERCARD1","MASTERCARD2","CardType","cards","Default","Visa","Mastercard","detectCardType","cardNumber","streetLine1","streetLine2","city","countryIso2","postCode","phone","shipping","cardholder","expiry","cvv","billingCountry","billingZip","saveInfo","saveCredentials","formErrors","getBillingCountry","countryCode","countryList","useFocusAfterAnimation","animationDuration","hasArrow","labelText","htmlFor","needEmail","needPhone","needName","needAddress","phoneRef","selectCountryRef","handleAddress1Change","handleAddress2Change","handleCityChange","handleStateChange","handleCountryChange","handlePostCodeChange","handleFullNameChange","handleEmailChange","handlePhoneChange","handleSaveInfoChange","shippingOptions","handleShippingSelect","amount","renderPaymentItem","main","renderCheckoutItem","invoiceContent","prices","shippingPrices","checkoutInfo","totalPrice","photoUrl","paymentMethod","paymentProvider","shippingAddress","shippingMethod","item","expiryInputRef","charAt","parts","formatCardExpiry","cardNumberRef","cardType","setCardType","newCardType","formatCardNumber","cardIcon","mastercardIconPath","visaIconPath","getCardIcon","canSaveCredentials","needCardholderName","needCountry","needZip","handleCardNumberChange","handleCardholderChange","toUpperCase","handleExpiryChange","handleCvvChange","handleBillingPostCodeChange","handleChangeSaveCredentials","savedInfo","invoice","nativeProvider","nativeParams","passwordMissing","payment","isProviderError","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","globalErrors","validateRequestedInfo","sendPaymentForm","setPaymentStep","sendCredentialsInfo","clearPaymentError","paymentState","paymentDispatch","currencySign","field","fieldError","getShippingError","handleErrorModalClose","PaymentStep","Checkout","shippingOption","getShippingPrices","totalPrices","concat","acc","cur","getTotalPrice","detectCardTypeText","findShippingOption","getCheckoutInfo","validateRequest","requestInfo","getRequestInfo","sendCredentials","credentials","expiryMonth","expiryYear","zip","getCredentials","sendForm","shippingOptionId","setStep","nextStep","ShippingInfo","Shipping","PaymentInfo","buttonText","cuurentStep","renderModalContent","renderError","optionId","receipt","mapedPrices","info","totalAmount","credentialsTitle","fullAddress","ANIMATED_STICKERS_PATHS","MonkeyIdle","MonkeyTracking","MonkeyClose","MonkeyPeek","FoldersAll","FoldersNew","DiscussionGroups","path","location","cropperResultOptions","quality","format","circle","Croppie","croppiePromise","cropper","isCroppieReady","setIsCroppieReady","imgFile","cropContainer","enableZoom","boundary","viewport","blobToDataUri","bind","err","DEBUG","console","initCropper","ensureCroppie","croppedImg","blobToFile","selectedFile","setSelectedFile","croppedBlobUrl","setCroppedBlobUrl","labelClassName","URL","revokeObjectURL","createObjectURL","SEGMENT_COVER_EYES","SEGMENT_UNCOVER_EYE","SEGMENT_COVER_EYE","STICKER_SIZE","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_AUTH","closeMonkeyData","setCloseMonkeyData","peekMonkeyData","setPeekMonkeyData","isFirstMonkeyLoaded","setIsFirstMonkeyLoaded","isPeekShown","setIsPeekShown","handleFirstMonkeyLoad","STICKER_SIZE_TWO_FA","playSegment","onInputChange","setPassword","canSubmit","setCanSubmit","select","autoComplete","MIN_PASSWORD_LENGTH"],"mappings":"2mEAiBO,SAASA,EACdC,EAAoBC,EAA2BC,EAAuBC,GAEtE,MAAQC,QAASC,GAAcC,EAASL,EAAQE,GAChD,IAAKE,EACH,OAGF,MAAQE,MAAOC,GAAgBC,IAAWC,MAE1C,IACIC,EADAC,GAAU,EAEd,GAAIT,EAAS,CACX,MAAM,MAAEU,EAAF,MAASC,EAAT,QAAgBC,GAAYC,YAAkBb,GACpDS,EAAUK,QAAQH,GAClBH,EAAYG,EAAQI,aAAmBJ,GAAUK,YAAwBN,GAASE,EAASF,YAE3FF,EAAYS,IAId,MACEb,MAAOc,EAAgBC,OAAQC,GAC7BC,YAAkCxB,EAAWY,IACzCL,MAAOkB,EAASH,OAAQI,GAAaC,YAC3CN,EAAgBE,EAAiBZ,EAAUJ,MAAOI,EAAUW,QAExDM,GAAUpB,EAAciB,GAAW,EACnCI,EAgPR,SAAsB7B,GACpB,MAAM8B,EAAMC,OAAOC,WAAWC,KAC9B,IAAIC,EAAe,MACflC,IACFkC,GAAgBJ,EAAIK,QAAU,KAAQ,OAGx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O7D,MAAM3H,QAAU61E,KAChCN,GACFA,EAAc/pE,EAAO7D,QAkCjB7F,IAAI,SAEN,+BAAQqZ,GAASsW,GAAQrX,GACzB,yBACE5Y,UAAU,kBACVC,QAnCR,WACEs1C,GAA4BF,IAmCtBp2B,KAAK,SACLC,SAAU,EACVnF,MAAM,8BAEN,uBAAG/Z,UAAWq1C,EAAoB,WAAa,sBAGlD4+B,GACC,kBAAC,IAAD,CAAQhuE,KAAK,SAASI,QAAM,EAAC6jB,UAAWA,GACrCwqB,O","file":"3.b7d1e22369add742c79e.js","sourcesContent":["import { ApiMessage } from '../../../api/types';\nimport { MediaViewerOrigin } from '../../../types';\n\nimport { ANIMATION_END_DELAY } from '../../../config';\nimport { getMessageContent, getPhotoFullDimensions, getVideoDimensions } from '../../../modules/helpers';\nimport {\n AVATAR_FULL_DIMENSIONS,\n calculateDimensions,\n getMediaViewerAvailableDimensions,\n MEDIA_VIEWER_MEDIA_QUERY,\n REM,\n} from '../../common/helpers/mediaDimensions';\n\nimport windowSize from '../../../util/windowSize';\n\nconst ANIMATION_DURATION = 200;\n\nexport function animateOpening(\n hasFooter: boolean, origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage,\n) {\n const { mediaEl: fromImage } = getNodes(origin, message);\n if (!fromImage) {\n return;\n }\n\n const { width: windowWidth } = windowSize.get();\n\n let isVideo = false;\n let mediaSize;\n if (message) {\n const { photo, video, webPage } = getMessageContent(message);\n isVideo = Boolean(video);\n mediaSize = video ? getVideoDimensions(video)! : getPhotoFullDimensions((photo || webPage!.photo)!)!;\n } else {\n mediaSize = AVATAR_FULL_DIMENSIONS;\n }\n\n // eslint-disable-next-line max-len\n const {\n width: availableWidth, height: availableHeight,\n } = getMediaViewerAvailableDimensions(hasFooter, isVideo);\n const { width: toWidth, height: toHeight } = calculateDimensions(\n availableWidth, availableHeight, mediaSize.width, mediaSize.height,\n );\n const toLeft = (windowWidth - toWidth) / 2;\n const toTop = getTopOffset(hasFooter) + (availableHeight - toHeight) / 2;\n\n let {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n const uncovered = uncover(toWidth, toHeight, fromTop, fromLeft, fromWidth, fromHeight);\n fromTop = uncovered.top;\n fromLeft = uncovered.left;\n fromWidth = uncovered.width;\n fromHeight = uncovered.height;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n const fromScaleX = fromWidth / toWidth;\n const fromScaleY = fromHeight / toHeight;\n\n const ghost = createGhost(bestImageData || fromImage);\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n applyShape(ghost, origin);\n\n document.body.classList.add('ghost-animating');\n\n requestAnimationFrame(() => {\n document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n ghost.style.transform = '';\n clearShape(ghost);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (document.body.contains(ghost)) {\n document.body.removeChild(ghost);\n }\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nexport function animateClosing(origin: MediaViewerOrigin, bestImageData: string, message?: ApiMessage) {\n const { container, mediaEl: toImage } = getNodes(origin, message);\n if (!toImage) {\n return;\n }\n\n const fromImage = document.getElementById('MediaViewer')!.querySelector(\n '.active .media-viewer-content img, .active .media-viewer-content video',\n );\n if (!fromImage || !toImage) {\n return;\n }\n\n const {\n top: fromTop, left: fromLeft, width: fromWidth, height: fromHeight,\n } = fromImage.getBoundingClientRect();\n const {\n top: targetTop, left: toLeft, width: toWidth, height: toHeight,\n } = toImage.getBoundingClientRect();\n\n let toTop = targetTop;\n if (!isElementInViewport(container)) {\n const { height: windowHeight } = windowSize.get();\n toTop = targetTop < fromTop ? -toHeight : windowHeight;\n }\n\n const fromTranslateX = (fromLeft + fromWidth / 2) - (toLeft + toWidth / 2);\n const fromTranslateY = (fromTop + fromHeight / 2) - (toTop + toHeight / 2);\n let fromScaleX = fromWidth / toWidth;\n let fromScaleY = fromHeight / toHeight;\n\n const shouldFadeOut = (\n [MediaViewerOrigin.Inline, MediaViewerOrigin.ScheduledInline].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n ) || (\n [MediaViewerOrigin.Album, MediaViewerOrigin.ScheduledAlbum].includes(origin)\n && !isMessageImageFullyVisible(container, toImage)\n );\n\n if ([\n MediaViewerOrigin.SharedMedia,\n MediaViewerOrigin.Album,\n MediaViewerOrigin.ScheduledAlbum,\n MediaViewerOrigin.SearchResult,\n ].includes(origin)) {\n if (fromScaleX > fromScaleY) {\n fromScaleX = fromScaleY;\n } else if (fromScaleY > fromScaleX) {\n fromScaleY = fromScaleX;\n }\n }\n\n const existingGhost = document.getElementsByClassName('ghost')[0] as HTMLDivElement;\n\n const ghost = existingGhost || createGhost(bestImageData || toImage, origin === MediaViewerOrigin.ProfileAvatar);\n if (!existingGhost) {\n applyStyles(ghost, {\n top: `${toTop}px`,\n left: `${toLeft}px`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n transform: `translate3d(${fromTranslateX}px, ${fromTranslateY}px, 0) scale(${fromScaleX}, ${fromScaleY})`,\n });\n }\n\n requestAnimationFrame(() => {\n if (existingGhost) {\n const {\n top,\n left,\n width,\n height,\n } = existingGhost.getBoundingClientRect();\n const scaleX = width / toWidth;\n const scaleY = height / toHeight;\n\n applyStyles(ghost, {\n transition: 'none',\n top: `${toTop}px`,\n left: `${toLeft}px`,\n transformOrigin: 'top left',\n transform: `translate3d(${left - toLeft}px, ${top - toTop}px, 0) scale(${scaleX}, ${scaleY})`,\n width: `${toWidth}px`,\n height: `${toHeight}px`,\n });\n }\n document.body.classList.add('ghost-animating');\n if (!existingGhost) document.body.appendChild(ghost);\n\n requestAnimationFrame(() => {\n if (existingGhost) {\n existingGhost.style.transition = '';\n }\n\n ghost.style.transform = '';\n\n if (shouldFadeOut) {\n ghost.style.opacity = '0';\n }\n\n applyShape(ghost, origin);\n\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (document.body.contains(ghost)) {\n document.body.removeChild(ghost);\n }\n document.body.classList.remove('ghost-animating');\n });\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n });\n });\n}\n\nfunction createGhost(source: string | HTMLImageElement | HTMLVideoElement, shouldAppendProfileInfo = false) {\n const ghost = document.createElement('div');\n ghost.classList.add('ghost');\n\n const img = new Image();\n\n if (typeof source === 'string') {\n img.src = source;\n } else if (source instanceof HTMLVideoElement) {\n img.src = source.poster;\n } else {\n img.src = source.src;\n }\n\n ghost.appendChild(img);\n\n if (shouldAppendProfileInfo) {\n ghost.classList.add('ProfileInfo');\n const profileInfo = document.querySelector('#RightColumn .ProfileInfo .info');\n if (profileInfo) {\n ghost.appendChild(profileInfo.cloneNode(true));\n }\n }\n\n return ghost;\n}\n\nfunction uncover(realWidth: number, realHeight: number, top: number, left: number, width: number, height: number) {\n if (realWidth === realHeight) {\n const size = Math.max(width, height) * (realWidth / realHeight);\n left -= (size - width) / 2;\n top -= (size - height) / 2;\n width = size;\n height = size;\n } else if (realWidth > realHeight) {\n const srcWidth = width;\n width = height * (realWidth / realHeight);\n left -= (width - srcWidth) / 2;\n } else if (realHeight > realWidth) {\n const srcHeight = height;\n height = width * (realHeight / realWidth);\n top -= (height - srcHeight) / 2;\n }\n\n return {\n top, left, width, height,\n };\n}\n\nfunction isElementInViewport(el: HTMLElement) {\n if (el.style.display === 'none') {\n return false;\n }\n\n const rect = el.getBoundingClientRect();\n const { height: windowHeight } = windowSize.get();\n\n return (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);\n}\n\nfunction isMessageImageFullyVisible(container: HTMLElement, imageEl: HTMLElement) {\n const messageListElement = document.querySelector('.active > .MessageList')!;\n let imgOffsetTop = container.offsetTop + imageEl.closest('.content-inner, .WebPage')!.offsetTop;\n if (container.id.includes('album-media-')) {\n imgOffsetTop += container.parentElement!.offsetTop + container.closest('.Message')!.offsetTop;\n }\n\n return imgOffsetTop > messageListElement.scrollTop\n && imgOffsetTop + imageEl.offsetHeight < messageListElement.scrollTop + messageListElement.offsetHeight;\n}\n\nfunction getTopOffset(hasFooter: boolean) {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n let topOffsetRem = 4.125;\n if (hasFooter) {\n topOffsetRem += mql.matches ? 0.875 : 3.375;\n }\n\n return topOffsetRem * REM;\n}\n\nfunction applyStyles(element: HTMLElement, styles: Record) {\n Object.assign(element.style, styles);\n}\n\nfunction getNodes(origin: MediaViewerOrigin, message?: ApiMessage) {\n let containerSelector;\n let mediaSelector;\n\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n containerSelector = `.active > .MessageList #album-media-${message!.id}`;\n mediaSelector = '.full-media';\n break;\n\n case MediaViewerOrigin.SharedMedia:\n containerSelector = `#shared-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.SearchResult:\n containerSelector = `#search-media${message!.id}`;\n mediaSelector = 'img';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n containerSelector = '.MiddleHeader .ChatInfo .Avatar';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ProfileAvatar:\n containerSelector = '#RightColumn .ProfileInfo .active .ProfilePhoto';\n mediaSelector = 'img.avatar-media';\n break;\n\n case MediaViewerOrigin.ScheduledInline:\n case MediaViewerOrigin.Inline:\n default:\n containerSelector = `.active > .MessageList #message${message!.id}`;\n mediaSelector = '.message-content .full-media, .message-content .thumbnail';\n }\n\n const container = document.querySelector(containerSelector)!;\n const mediaEls = container && container.querySelectorAll(mediaSelector);\n\n return {\n container,\n mediaEl: mediaEls && mediaEls[mediaEls.length - 1],\n };\n}\n\nfunction applyShape(ghost: HTMLDivElement, origin: MediaViewerOrigin) {\n switch (origin) {\n case MediaViewerOrigin.Album:\n case MediaViewerOrigin.ScheduledAlbum:\n case MediaViewerOrigin.Inline:\n case MediaViewerOrigin.ScheduledInline:\n ghost.classList.add('rounded-corners');\n break;\n\n case MediaViewerOrigin.SharedMedia:\n case MediaViewerOrigin.ProfileAvatar:\n case MediaViewerOrigin.SearchResult:\n (ghost.firstChild as HTMLElement).style.objectFit = 'cover';\n break;\n\n case MediaViewerOrigin.MiddleHeaderAvatar:\n ghost.classList.add('circle');\n break;\n }\n}\n\nfunction clearShape(ghost: HTMLDivElement) {\n (ghost.firstChild as HTMLElement).style.objectFit = 'default';\n ghost.classList.remove('rounded-corners', 'circle');\n}\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../api/types';\n\nimport { getSenderTitle, isChatPrivate } from '../../modules/helpers';\nimport { formatMediaDateTime } from '../../util/dateFormat';\nimport renderText from '../common/helpers/renderText';\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectUser,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Avatar from '../common/Avatar';\n\nimport './SenderInfo.scss';\n\ntype OwnProps = {\n chatId?: number;\n messageId?: number;\n isAvatar?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n message?: ApiMessage;\n};\n\ntype DispatchProps = Pick;\n\nconst SenderInfo: FC = ({\n chatId, messageId, sender, isAvatar, message, closeMediaViewer, focusMessage,\n}) => {\n const handleFocusMessage = useCallback(() => {\n closeMediaViewer();\n focusMessage({ chatId, messageId });\n }, [chatId, focusMessage, messageId, closeMediaViewer]);\n\n const lang = useLang();\n\n if (!sender || (!message && !isAvatar)) {\n return undefined;\n }\n\n const isFromChat = sender.id < 0;\n const senderTitle = getSenderTitle(lang, sender);\n\n return (\n
\n {isFromChat ? (\n \n ) : (\n \n )}\n
\n
\n {senderTitle && renderText(senderTitle)}\n
\n
\n {isAvatar ? lang('lng_mediaview_profile_photo') : formatMediaDateTime(lang, message!.date * 1000)}\n
\n
\n
\n );\n};\n\nexport default withGlobal(\n (global, { chatId, messageId, isAvatar }): StateProps => {\n if (isAvatar && chatId) {\n return {\n sender: isChatPrivate(chatId) ? selectUser(global, chatId) : selectChat(global, chatId),\n };\n }\n\n if (!messageId || !chatId) {\n return {};\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n message,\n sender: message && selectSender(global, message),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['closeMediaViewer', 'focusMessage']),\n)(SenderInfo);\n","import React, {\n FC, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport download from '../../util/download';\nimport { getMessageMediaHash } from '../../modules/helpers';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './MediaViewerActions.scss';\n\ntype OwnProps = {\n mediaData?: string;\n isVideo: boolean;\n isZoomed: boolean;\n message?: ApiMessage;\n fileName?: string;\n isAvatar?: boolean;\n onCloseMediaViewer: NoneToVoidFunction;\n onForward: NoneToVoidFunction;\n onZoomToggle: NoneToVoidFunction;\n};\n\nconst MediaViewerActions: FC = ({\n mediaData,\n isVideo,\n isZoomed,\n message,\n fileName,\n isAvatar,\n onCloseMediaViewer,\n onForward,\n onZoomToggle,\n}) => {\n const [isVideoDownloadAllowed, setIsVideoDownloadAllowed] = useState(false);\n const videoMediaHash = isVideo && message ? getMessageMediaHash(message, 'download') : undefined;\n const {\n mediaData: videoBlobUrl, downloadProgress,\n } = useMediaWithDownloadProgress(videoMediaHash, !isVideoDownloadAllowed);\n\n // Download with browser when fully loaded\n useEffect(() => {\n if (isVideoDownloadAllowed && videoBlobUrl) {\n download(videoBlobUrl, fileName!);\n setIsVideoDownloadAllowed(false);\n }\n }, [fileName, videoBlobUrl, isVideoDownloadAllowed]);\n\n // Cancel download on slide change\n useEffect(() => {\n setIsVideoDownloadAllowed(false);\n }, [videoMediaHash]);\n\n const handleVideoDownloadClick = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n setIsVideoDownloadAllowed((isAllowed) => !isAllowed);\n }, []);\n\n const lang = useLang();\n\n const MenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n \n \n \n );\n }, []);\n\n if (IS_MOBILE_SCREEN) {\n return (\n
\n \n {!isAvatar && (\n \n {lang('Forward')}\n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? `${Math.round(downloadProgress * 100)}% Downloading...` : 'Download'}\n \n ) : (\n \n {lang('AccActionDownload')}\n \n )}\n \n {isVideoDownloadAllowed && }\n
\n );\n }\n\n return (\n
\n {!isAvatar && (\n <>\n \n \n \n \n )}\n {isVideo ? (\n \n {isVideoDownloadAllowed ? (\n \n ) : (\n \n )}\n \n ) : (\n \n \n \n )}\n \n \n \n \n \n \n
\n );\n};\n\nexport default MediaViewerActions;\n","import React, { FC, useEffect, useState } from '../../lib/teact/teact';\nimport { throttle } from '../../util/schedulers';\nimport { TextPart } from '../common/helpers/renderMessageText';\nimport { REM } from '../common/helpers/mediaDimensions';\n\nimport './MediaViewerFooter.scss';\n\nconst RESIZE_THROTTLE_MS = 500;\n\ntype OwnProps = {\n text: TextPart | TextPart[];\n onClick: () => void;\n isHideable: boolean;\n};\n\nconst MediaViewerFooter: FC = ({ text = '', isHideable, onClick }) => {\n const [isMultiline, setIsMultiline] = useState(false);\n useEffect(() => {\n const footerContent = document.querySelector('.MediaViewerFooter .media-text') as HTMLDivElement | null;\n\n const checkIsMultiline = () => {\n const height = footerContent ? footerContent.clientHeight : 0;\n\n setIsMultiline(height > REM * 2);\n };\n\n // First run for initial detection of multiline footer text\n checkIsMultiline();\n\n const handleResize = throttle(checkIsMultiline, RESIZE_THROTTLE_MS, true);\n\n window.addEventListener('resize', handleResize, false);\n\n return () => {\n window.removeEventListener('resize', handleResize, false);\n };\n }, []);\n\n function stopEvent(e: React.MouseEvent) {\n if (text) {\n e.stopPropagation();\n }\n }\n\n return (\n
\n {text && (\n
\n

{text}

\n
\n )}\n
\n );\n};\n\nexport default MediaViewerFooter;\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\nimport { PLATFORM_ENV } from '../util/environment';\n\ntype RefType = {\n current: HTMLElement | null;\n};\n\ntype ReturnType = [boolean, () => void, () => void] | [false];\ntype CallbackType = (isPlayed: boolean) => void;\n\nconst prop = getBrowserFullscreenElementProp();\n\nexport default function useFullscreenStatus(elRef: RefType, setIsPlayed: CallbackType): ReturnType {\n const [isFullscreen, setIsFullscreen] = useState(Boolean(prop && document[prop]));\n\n const setFullscreen = () => {\n if (!elRef.current || !(prop || PLATFORM_ENV === 'iOS')) {\n return;\n }\n\n if (elRef.current.requestFullscreen) {\n elRef.current.requestFullscreen();\n } else if (elRef.current.webkitRequestFullscreen) {\n elRef.current.webkitRequestFullscreen();\n } else if (elRef.current.webkitEnterFullscreen) {\n elRef.current.webkitEnterFullscreen();\n } else if (elRef.current.mozRequestFullScreen) {\n elRef.current.mozRequestFullScreen();\n }\n\n setIsFullscreen(true);\n };\n\n const exitFullscreen = () => {\n if (!elRef.current) {\n return;\n }\n\n if (document.exitFullscreen) {\n document.exitFullscreen();\n } else if (document.mozCancelFullScreen) {\n document.mozCancelFullScreen();\n } else if (document.webkitCancelFullScreen) {\n document.webkitCancelFullScreen();\n } else if (document.webkitExitFullscreen) {\n document.webkitExitFullscreen();\n }\n\n setIsFullscreen(false);\n };\n\n useLayoutEffect(() => {\n const listener = () => { setIsFullscreen(Boolean(prop && document[prop])); };\n const listenerEnter = () => { setIsFullscreen(true); };\n const listenerExit = () => {\n setIsFullscreen(false);\n setIsPlayed(false);\n };\n const video = elRef.current;\n\n document.addEventListener('fullscreenchange', listener, false);\n document.addEventListener('webkitfullscreenchange', listener, false);\n document.addEventListener('mozfullscreenchange', listener, false);\n\n if (video) {\n video.addEventListener('webkitbeginfullscreen', listenerEnter, false);\n video.addEventListener('webkitendfullscreen', listenerExit, false);\n }\n\n return () => {\n document.removeEventListener('fullscreenchange', listener, false);\n document.removeEventListener('webkitfullscreenchange', listener, false);\n document.removeEventListener('mozfullscreenchange', listener, false);\n if (video) {\n video.removeEventListener('webkitbeginfullscreen', listenerEnter, false);\n video.removeEventListener('webkitendfullscreen', listenerExit, false);\n }\n };\n // eslint-disable-next-line\n }, []);\n\n if (!prop && PLATFORM_ENV !== 'iOS') {\n return [false];\n }\n\n return [isFullscreen, setFullscreen, exitFullscreen];\n}\n\nfunction getBrowserFullscreenElementProp() {\n if (typeof document.fullscreenElement !== 'undefined') {\n return 'fullscreenElement';\n } else if (typeof document.mozFullScreenElement !== 'undefined') {\n return 'mozFullScreenElement';\n } else if (typeof document.webkitFullscreenElement !== 'undefined') {\n return 'webkitFullscreenElement';\n }\n\n return '';\n}\n","const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];\n\nexport default (bytes: number) => {\n const number = bytes === 0 ? 0 : Math.floor(Math.log(bytes) / Math.log(1024));\n\n return `${(bytes / 1024 ** Math.floor(number)).toFixed(1)} ${units[number]}`;\n};\n","import React, { FC, useState, useEffect } from '../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { formatMediaDuration } from '../../util/dateFormat';\nimport formatFileSize from './helpers/formatFileSize';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './VideoPlayerControls.scss';\n\ntype IProps = {\n bufferedProgress: number;\n currentTime: number;\n duration: number;\n fileSize: number;\n isForceVisible: boolean;\n isForceMobileVersion?: boolean;\n isPlayed: boolean;\n isFullscreenSupported: boolean;\n isFullscreen: boolean;\n onChangeFullscreen: (e: React.MouseEvent) => void;\n onPlayPause: (e: React.MouseEvent) => void;\n onSeek: OnChangeHandler;\n};\n\ntype OnChangeHandler = (e: React.ChangeEvent) => void;\n\nconst stopEvent = (e: React.MouseEvent) => {\n e.stopPropagation();\n};\n\nconst HIDE_CONTROLS_TIMEOUT_MS = 800;\n\nconst VideoPlayerControls: FC = ({\n bufferedProgress,\n currentTime,\n duration,\n fileSize,\n isForceVisible,\n isForceMobileVersion,\n isPlayed,\n isFullscreenSupported,\n isFullscreen,\n onChangeFullscreen,\n onPlayPause,\n onSeek,\n}) => {\n const [isVisible, setVisibility] = useState(true);\n\n useEffect(() => {\n if (isForceVisible) {\n setVisibility(isForceVisible);\n }\n }, [isForceVisible]);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n if (!isForceVisible) {\n if (IS_MOBILE_SCREEN) {\n setVisibility(false);\n } else {\n timeout = window.setTimeout(() => {\n setVisibility(false);\n }, HIDE_CONTROLS_TIMEOUT_MS);\n }\n }\n\n return () => {\n if (timeout) {\n window.clearTimeout(timeout);\n }\n };\n }, [isForceVisible]);\n\n useEffect(() => {\n if (isVisible || isForceVisible) {\n document.body.classList.add('video-controls-visible');\n }\n\n return () => {\n document.body.classList.remove('video-controls-visible');\n };\n }, [isForceVisible, isVisible]);\n\n const lang = useLang();\n\n if (!isVisible && !isForceVisible) {\n return undefined;\n }\n\n return (\n
\n {renderSeekLine(currentTime, duration, bufferedProgress, onSeek)}\n \n \n \n {renderTime(currentTime, duration)}\n {bufferedProgress < 1 && renderFileSize(bufferedProgress, fileSize)}\n {isFullscreenSupported && (\n \n \n \n )}\n
\n );\n};\n\nfunction renderTime(currentTime: number, duration: number) {\n return (\n
\n {`${formatMediaDuration(currentTime)} / ${formatMediaDuration(duration)}`}\n
\n );\n}\n\nfunction renderFileSize(downloadedPercent: number, totalSize: number) {\n return (\n
\n {`${formatFileSize(totalSize * downloadedPercent)} / ${formatFileSize(totalSize)}`}\n
\n );\n}\n\nfunction renderSeekLine(currentTime: number, duration: number, bufferedProgress: number, onSeek: OnChangeHandler) {\n const percentagePlayed = (currentTime / duration) * 100;\n const percentageBuffered = bufferedProgress * 100;\n\n return (\n
\n
\n \n \n \n
\n
\n );\n}\n\nexport default VideoPlayerControls;\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { IDimensions } from '../../modules/helpers';\n\nimport { IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../util/environment';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBuffering from '../../hooks/useBuffering';\nimport useFullscreenStatus from '../../hooks/useFullscreen';\nimport useVideoCleanup from '../../hooks/useVideoCleanup';\nimport safePlay from '../../util/safePlay';\n\nimport VideoPlayerControls from './VideoPlayerControls';\nimport ProgressSpinner from '../ui/ProgressSpinner';\n\nimport './VideoPlayer.scss';\n\ntype OwnProps = {\n url?: string;\n isGif?: boolean;\n posterData?: string;\n posterSize?: IDimensions;\n downloadProgress?: number;\n fileSize: number;\n isMediaViewerOpen?: boolean;\n noPlay?: boolean;\n onClose: (e: React.MouseEvent) => void;\n};\n\nconst MOBILE_VERSION_CONTROL_WIDTH = 400;\n\nconst VideoPlayer: FC = ({\n url,\n isGif,\n posterData,\n posterSize,\n downloadProgress,\n fileSize,\n isMediaViewerOpen,\n noPlay,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n const [isPlayed, setIsPlayed] = useState(!IS_TOUCH_ENV || !IS_IOS);\n const [currentTime, setCurrentTime] = useState(0);\n const [isControlsVisible, setIsControlsVisible] = useState(true);\n\n const [isFullscreen, setFullscreen, exitFullscreen] = useFullscreenStatus(videoRef, setIsPlayed);\n\n const { isBuffered, bufferedProgress, bufferingHandlers } = useBuffering();\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(!isBuffered, undefined, undefined, 'slow');\n\n useEffect(() => {\n if (noPlay || !isMediaViewerOpen) {\n videoRef.current!.pause();\n } else if (url && !IS_TOUCH_ENV) {\n // Chrome does not automatically start playing when `url` becomes available (even with `autoPlay`),\n // so we force it here. Contrary, iOS does not allow to call `play` without mouse event,\n // so we need to use `autoPlay` instead to allow pre-buffering.\n safePlay(videoRef.current!);\n }\n }, [noPlay, isMediaViewerOpen, url]);\n\n useEffect(() => {\n if (videoRef.current!.currentTime === videoRef.current!.duration) {\n setCurrentTime(0);\n setIsPlayed(false);\n } else {\n setCurrentTime(videoRef.current!.currentTime);\n }\n }, [currentTime]);\n\n const togglePlayState = useCallback((e: React.MouseEvent | KeyboardEvent) => {\n e.stopPropagation();\n if (isPlayed) {\n videoRef.current!.pause();\n setIsPlayed(false);\n } else {\n videoRef.current!.play();\n setIsPlayed(true);\n }\n }, [isPlayed]);\n\n useVideoCleanup(videoRef, []);\n\n const handleMouseOver = useCallback(() => {\n setIsControlsVisible(true);\n }, []);\n\n const handleMouseOut = useCallback(() => {\n setIsControlsVisible(false);\n }, []);\n\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setCurrentTime(e.currentTarget.currentTime);\n }, []);\n\n const handleEnded = useCallback(() => {\n setCurrentTime(0);\n setIsPlayed(false);\n }, []);\n\n const handleFullscreenChange = useCallback(() => {\n if (isFullscreen && exitFullscreen) {\n exitFullscreen();\n } else if (!isFullscreen && setFullscreen) {\n setFullscreen();\n }\n }, [exitFullscreen, isFullscreen, setFullscreen]);\n\n const handleSeek = useCallback((e: React.ChangeEvent) => {\n e.stopPropagation();\n\n videoRef.current!.currentTime = (Number(e.target.value) * videoRef.current!.duration) / 100;\n }, []);\n\n const toggleControls = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n setIsControlsVisible(!isControlsVisible);\n }, [isControlsVisible]);\n\n useEffect(() => {\n const togglePayingStateBySpace = (e: KeyboardEvent) => {\n if (e.key === 'Enter' || e.key === ' ') {\n togglePlayState(e);\n }\n };\n\n document.addEventListener('keydown', togglePayingStateBySpace, false);\n\n return () => {\n document.removeEventListener('keydown', togglePayingStateBySpace, false);\n };\n }, [togglePlayState]);\n\n const wrapperStyle = posterSize && `width: ${posterSize.width}px; height: ${posterSize.height}px`;\n const videoStyle = `background-image: url(${posterData})`;\n\n return (\n \n \n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n {url && }\n \n \n {shouldRenderSpinner && (\n
\n {!isBuffered &&
Buffering...
}\n \n
\n )}\n {!isGif && !shouldRenderSpinner && (\n \n )}\n \n );\n};\n\nexport default memo(VideoPlayer);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport usePrevious from '../../hooks/usePrevious';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ZoomControls.scss';\n\ntype OwnProps = {\n isShown: boolean;\n onChangeZoom: (level: number, canCloseZoom?: boolean) => void;\n};\n\nexport const MAX_ZOOM_LEVEL = 3;\nexport const MIN_ZOOM_LEVEL = 1;\nconst ONE_STEP_PERCENT = 100 / (MAX_ZOOM_LEVEL - MIN_ZOOM_LEVEL);\nconst RESET_ZOOM_LEVEL = 1.5;\n\nconst ZoomControls: FC = ({ isShown, onChangeZoom }) => {\n const { transitionClassNames } = useShowTransition(isShown);\n const prevIsShown = usePrevious(isShown);\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const [zoomLevel, setZoomLevel] = useState(1);\n const isSeeking = useRef(false);\n\n useEffect(() => {\n if (isShown && !prevIsShown) {\n setZoomLevel(RESET_ZOOM_LEVEL);\n }\n }, [isShown, prevIsShown]);\n\n const handleZoomOut = () => {\n if (inputRef.current) {\n setZoomLevel(Math.max(MIN_ZOOM_LEVEL, zoomLevel - 0.5));\n }\n };\n\n const handleZoomIn = () => {\n if (inputRef.current) {\n setZoomLevel(Math.min(MAX_ZOOM_LEVEL, zoomLevel + 0.5));\n }\n };\n\n const handleStartSeek = useCallback(() => {\n isSeeking.current = true;\n }, []);\n\n const handleStopSeek = useCallback(() => {\n isSeeking.current = false;\n if (zoomLevel === 1) {\n onChangeZoom(zoomLevel, !isSeeking.current);\n }\n }, [onChangeZoom, zoomLevel]);\n\n const handleSeeklineChange = (e:React.ChangeEvent) => {\n setZoomLevel(Math.min(MAX_ZOOM_LEVEL, Math.max(Number(e.target.value), MIN_ZOOM_LEVEL)));\n };\n\n useEffect(() => {\n onChangeZoom(zoomLevel, !isSeeking.current);\n }, [zoomLevel, onChangeZoom]);\n\n const lang = useLang();\n\n const className = buildClassName(\n 'ZoomControls',\n transitionClassNames,\n );\n\n return (\n
\n \n \n \n \n \n \n
\n
\n \n \n
\n
\n
\n );\n};\n\nexport default memo(ZoomControls);\n","/*\n @source https://github.com/ajainarayanan/react-pan-zoom\n\n Heavily inspired/lifted from this idea: https://stackoverflow.com/a/39311435/661768\n without jqueryUI or jquery dependency.\n*/\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nimport './PanZoom.scss';\n\nexport interface IDragData {\n x: number;\n y: number;\n dx: number;\n dy: number;\n}\n\nexport interface OwnProps {\n children: any;\n className?: string;\n noWrap: boolean;\n canPan: boolean;\n zoomLevel: number;\n panDeltaX: number;\n panDeltaY: number;\n onPan?: (x: number, y: number) => void;\n}\n\nconst INITIAL_MATRIX = [\n 1, 0, 0, 1, 0, 0,\n];\n\nconst SCALE_VALUES = {\n 1: 1,\n 1.5: 1.5,\n 2: 2.2,\n 2.5: 3.3,\n 3: 5.5,\n};\n\nconst ZOOM_SAFE_AREA = 150;\n\nfunction calculateSafeZoneOnZoom(oldScale: number, matrixData: number[], wrapper: HTMLDivElement | null) {\n const image = wrapper && wrapper.querySelector('.active img');\n if (!wrapper || !image) {\n return matrixData;\n }\n const wrapperRect = wrapper.getBoundingClientRect();\n const imageRect = image.getBoundingClientRect();\n\n const newImgWidth = (imageRect.width / oldScale) * matrixData[0];\n const newImgHeight = (imageRect.height / oldScale) * matrixData[3];\n const newImgX = (wrapperRect.width - newImgWidth) / 2 + matrixData[4];\n const newImgY = (wrapperRect.height - newImgHeight) / 2 + matrixData[5];\n if (wrapperRect.width && wrapperRect.width - ZOOM_SAFE_AREA < newImgX) {\n matrixData[4] -= newImgX + wrapperRect.width - ZOOM_SAFE_AREA;\n } else if (newImgWidth && newImgWidth + newImgX < ZOOM_SAFE_AREA) {\n matrixData[4] -= newImgWidth + newImgX - ZOOM_SAFE_AREA;\n }\n if (wrapperRect.height && wrapperRect.height - ZOOM_SAFE_AREA < newImgY) {\n matrixData[5] -= newImgY + wrapperRect.height - ZOOM_SAFE_AREA;\n } else if (newImgHeight && newImgHeight + newImgY < ZOOM_SAFE_AREA) {\n matrixData[5] -= newImgHeight + newImgY - ZOOM_SAFE_AREA;\n }\n\n return matrixData;\n}\n\nconst PanZoom: FC = ({\n children,\n className,\n noWrap,\n canPan,\n zoomLevel,\n panDeltaX,\n panDeltaY,\n onPan,\n}) => {\n const tunedZoomLevel = SCALE_VALUES[zoomLevel as keyof typeof SCALE_VALUES] || zoomLevel;\n const [isDragging, setIsDragging] = useState(false);\n const [dragData, setDragData] = useState({\n dx: panDeltaX, dy: panDeltaY, x: 0, y: 0,\n });\n // [zoom, skew, skew, zoom, dx, dy] - see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix()\n const [matrixData, setMatrixData] = useState(INITIAL_MATRIX);\n // Used to set cursor while moving.\n // eslint-disable-next-line no-null/no-null\n const panWrapperRef = useRef(null);\n // Used to set transform for pan.\n // eslint-disable-next-line no-null/no-null\n const panContainerRef = useRef(null);\n\n useEffect(() => {\n const newZoomLevel = tunedZoomLevel || matrixData[0];\n const newPandx = panDeltaX || matrixData[4];\n const newPandy = panDeltaY || matrixData[5];\n\n const newMatrixData = [...matrixData];\n if (matrixData[0] !== newZoomLevel) {\n newMatrixData[0] = newZoomLevel || newMatrixData[0];\n newMatrixData[3] = newZoomLevel || newMatrixData[3];\n }\n if (matrixData[4] !== newPandx) {\n newMatrixData[4] = newPandx;\n }\n if (matrixData[5] !== newPandy) {\n newMatrixData[5] = newPandy;\n }\n\n if (!areSortedArraysEqual(matrixData, newMatrixData)) {\n setMatrixData(calculateSafeZoneOnZoom(matrixData[0], newMatrixData, panWrapperRef.current));\n }\n // eslint-disable-next-line\n }, [panDeltaX, panDeltaY, tunedZoomLevel]);\n\n useEffect(() => {\n if (!canPan) {\n setMatrixData(INITIAL_MATRIX);\n }\n }, [canPan]);\n\n useEffect(() => {\n if (panContainerRef.current) {\n panContainerRef.current.style.transform = `matrix(${matrixData.toString()})`;\n }\n }, [noWrap, matrixData]);\n\n const handleMouseDown = (e: React.MouseEvent) => {\n if (!canPan) {\n return;\n }\n\n e.stopPropagation();\n e.preventDefault();\n\n const offsetX = matrixData[4];\n const offsetY = matrixData[5];\n const newDragData: IDragData = {\n dx: offsetX,\n dy: offsetY,\n x: e.pageX,\n y: e.pageY,\n };\n setDragData(newDragData);\n setIsDragging(true);\n\n if (panWrapperRef.current) {\n panWrapperRef.current.classList.add('move');\n }\n };\n\n const handleMouseUp = () => {\n setIsDragging(false);\n\n if (panWrapperRef.current) {\n panWrapperRef.current.classList.remove('move');\n }\n\n if (onPan) {\n onPan(matrixData[4], matrixData[5]);\n }\n };\n\n function getNewMatrixData(x: number, y: number): number[] {\n const newMatrixData = [...matrixData];\n const deltaX = dragData.x - x;\n const deltaY = dragData.y - y;\n newMatrixData[4] = dragData.dx - deltaX;\n newMatrixData[5] = dragData.dy - deltaY;\n\n return newMatrixData;\n }\n\n const handleMouseMove = (e: React.MouseEvent) => {\n if (isDragging) {\n const newMatrixData = getNewMatrixData(e.pageX, e.pageY);\n setMatrixData(newMatrixData);\n\n if (panContainerRef.current) {\n panContainerRef.current.style.transform = `matrix(${matrixData.toString()})`;\n }\n }\n };\n\n if (noWrap) {\n return children;\n }\n\n return (\n \n \n {children}\n \n \n );\n};\n\nexport default memo(PanZoom);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../../api/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport { IS_IOS, IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../util/environment';\nimport {\n AVATAR_FULL_DIMENSIONS,\n MEDIA_VIEWER_MEDIA_QUERY,\n calculateMediaViewerDimensions,\n} from '../common/helpers/mediaDimensions';\nimport {\n selectChat,\n selectChatMessage,\n selectChatMessages,\n selectCurrentMediaSearch,\n selectListedIds,\n selectOutlyingIds,\n selectScheduledMessage,\n selectScheduledMessages,\n selectUser,\n} from '../../modules/selectors';\nimport {\n getChatAvatarHash,\n getChatMediaMessageIds,\n getMessageMediaFilename,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageMediaThumbDataUri,\n getMessagePhoto,\n getMessageVideo,\n getMessageWebPagePhoto,\n getPhotoFullDimensions,\n getVideoDimensions,\n IDimensions,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { stopCurrentAudio } from '../../util/audioPlayer';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport useMedia from '../../hooks/useMedia';\nimport useMediaWithDownloadProgress from '../../hooks/useMediaWithDownloadProgress';\nimport useBlurSync from '../../hooks/useBlurSync';\nimport usePrevious from '../../hooks/usePrevious';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport { renderMessageText } from '../common/helpers/renderMessageText';\nimport { animateClosing, animateOpening } from './helpers/ghostAnimation';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\nimport ShowTransition from '../ui/ShowTransition';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport SenderInfo from './SenderInfo';\nimport MediaViewerActions from './MediaViewerActions';\nimport MediaViewerFooter from './MediaViewerFooter';\nimport VideoPlayer from './VideoPlayer';\nimport ZoomControls from './ZoomControls';\nimport PanZoom from './PanZoom';\n\nimport './MediaViewer.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageId?: number;\n senderId?: number;\n origin?: MediaViewerOrigin;\n avatarOwner?: ApiChat | ApiUser;\n profilePhotoIndex?: number;\n message?: ApiMessage;\n chatMessages?: Record;\n collectionIds?: number[];\n animationLevel: 0 | 1 | 2;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 350;\n\nconst MediaViewer: FC = ({\n chatId,\n threadId,\n messageId,\n senderId,\n origin,\n avatarOwner,\n profilePhotoIndex,\n message,\n chatMessages,\n collectionIds,\n openMediaViewer,\n closeMediaViewer,\n openForwardMenu,\n focusMessage,\n animationLevel,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const animationKey = useRef(null);\n const isOpen = Boolean(avatarOwner || messageId);\n const webPagePhoto = message ? getMessageWebPagePhoto(message) : undefined;\n const photo = message ? getMessagePhoto(message) : undefined;\n const video = message ? getMessageVideo(message) : undefined;\n const isWebPagePhoto = Boolean(webPagePhoto);\n const isPhoto = Boolean(photo || webPagePhoto);\n const isVideo = Boolean(video);\n const isGif = video ? video.isGif : undefined;\n const isFromSharedMedia = origin === MediaViewerOrigin.SharedMedia;\n const isFromSearch = origin === MediaViewerOrigin.SearchResult;\n const slideAnimation = animationLevel >= 1 ? 'mv-slide' : 'none';\n const headerAnimation = animationLevel === 2 ? 'slide-fade' : 'none';\n const isGhostAnimation = animationLevel === 2;\n const fileName = avatarOwner\n ? `avatar${avatarOwner.id}-${profilePhotoIndex}.jpg`\n : message && getMessageMediaFilename(message);\n const prevSenderId = usePrevious(senderId);\n const [canPanZoomWrap, setCanPanZoomWrap] = useState(false);\n const [isZoomed, setIsZoomed] = useState(false);\n const [zoomLevel, setZoomLevel] = useState(1);\n const [panDelta, setPanDelta] = useState({ x: 0, y: 0 });\n\n const messageIds = useMemo(() => {\n return isWebPagePhoto && messageId\n ? [messageId]\n : getChatMediaMessageIds(chatMessages || {}, collectionIds || [], isFromSharedMedia);\n }, [isWebPagePhoto, messageId, chatMessages, collectionIds, isFromSharedMedia]);\n\n const selectedMediaMessageIndex = messageId ? messageIds.indexOf(messageId) : -1;\n const isFirst = selectedMediaMessageIndex === 0 || selectedMediaMessageIndex === -1;\n const isLast = selectedMediaMessageIndex === messageIds.length - 1 || selectedMediaMessageIndex === -1;\n if (isOpen && (!prevSenderId || prevSenderId !== senderId || !animationKey.current)) {\n animationKey.current = selectedMediaMessageIndex;\n }\n\n function getMediaHash(full?: boolean) {\n if (avatarOwner && profilePhotoIndex !== undefined) {\n const { photos } = avatarOwner;\n return photos && photos[profilePhotoIndex]\n ? `photo${photos[profilePhotoIndex].id}?size=c`\n : getChatAvatarHash(avatarOwner, full ? 'big' : 'normal');\n }\n\n return message && getMessageMediaHash(message, full ? 'viewerFull' : 'viewerPreview');\n }\n\n const blobUrlPictogram = useMedia(\n message && (isFromSharedMedia || isFromSearch) && getMessageMediaHash(message, 'pictogram'),\n undefined,\n ApiMediaFormat.BlobUrl,\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n const previewMediaHash = getMediaHash();\n const blobUrlPreview = useMedia(\n previewMediaHash,\n undefined,\n avatarOwner && previewMediaHash && previewMediaHash.startsWith('profilePhoto')\n ? ApiMediaFormat.DataUri\n : ApiMediaFormat.BlobUrl,\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n const { mediaData: fullMediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMediaHash(true),\n undefined,\n message && getMessageMediaFormat(message, 'viewerFull'),\n undefined,\n isGhostAnimation && ANIMATION_DURATION,\n );\n\n const localBlobUrl = (photo || video) ? (photo || video)!.blobUrl : undefined;\n let bestImageData = (!isVideo && (localBlobUrl || fullMediaData)) || blobUrlPreview || blobUrlPictogram;\n const thumbDataUri = useBlurSync(!bestImageData && message && getMessageMediaThumbDataUri(message));\n if (!bestImageData && origin !== MediaViewerOrigin.SearchResult) {\n bestImageData = thumbDataUri;\n }\n\n const photoDimensions = isPhoto ? getPhotoFullDimensions((\n isWebPagePhoto ? getMessageWebPagePhoto(message!) : getMessagePhoto(message!)\n )!) : undefined;\n const videoDimensions = isVideo ? getVideoDimensions(getMessageVideo(message!)!) : undefined;\n\n useEffect(() => {\n if (!IS_MOBILE_SCREEN) {\n return;\n }\n\n document.body.classList.toggle('is-media-viewer-open', isOpen);\n }, [isOpen]);\n\n const forceUpdate = useForceUpdate();\n useEffect(() => {\n const mql = window.matchMedia(MEDIA_VIEWER_MEDIA_QUERY);\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', forceUpdate);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(forceUpdate);\n }\n\n return () => {\n if (typeof mql.removeEventListener === 'function') {\n mql.removeEventListener('change', forceUpdate);\n } else if (typeof mql.removeListener === 'function') {\n mql.removeListener(forceUpdate);\n }\n };\n }, [forceUpdate]);\n\n const prevMessage = usePrevious(message);\n const prevOrigin = usePrevious(origin);\n const prevAvatarOwner = usePrevious(avatarOwner);\n const prevBestImageData = usePrevious(bestImageData);\n useEffect(() => {\n if (isGhostAnimation && isOpen && !prevMessage && !prevAvatarOwner) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n const textParts = message ? renderMessageText(message) : undefined;\n const hasFooter = Boolean(textParts);\n animateOpening(hasFooter, origin!, bestImageData!, message);\n }\n\n if (isGhostAnimation && !isOpen && (prevMessage || prevAvatarOwner)) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n animateClosing(prevOrigin!, prevBestImageData!, prevMessage || undefined);\n }\n }, [\n isGhostAnimation, isOpen, origin, prevOrigin,\n message, prevMessage, prevAvatarOwner, bestImageData, prevBestImageData,\n ]);\n\n useEffect(() => {\n let timer: number | undefined;\n\n if (isZoomed) {\n setCanPanZoomWrap(true);\n } else {\n timer = window.setTimeout(() => {\n setCanPanZoomWrap(false);\n }, ANIMATION_DURATION);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [isZoomed]);\n\n const closeZoom = () => {\n setIsZoomed(false);\n setZoomLevel(1);\n setPanDelta({ x: 0, y: 0 });\n };\n\n const handleZoomToggle = useCallback(() => {\n setIsZoomed(!isZoomed);\n setZoomLevel(!isZoomed ? 1.5 : 1);\n if (isZoomed) {\n setPanDelta({ x: 0, y: 0 });\n }\n }, [isZoomed]);\n\n const handleZoomValue = useCallback((level: number, canCloseZoom = false) => {\n setZoomLevel(level);\n if (level === 1 && canCloseZoom) {\n closeZoom();\n }\n }, []);\n\n const close = useCallback(() => {\n closeMediaViewer();\n closeZoom();\n }, [closeMediaViewer]);\n\n const handleFooterClick = useCallback(() => {\n close();\n focusMessage({ chatId, threadId, messageId });\n }, [close, chatId, threadId, focusMessage, messageId]);\n\n const handleForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n closeZoom();\n }, [openForwardMenu, chatId, messageId]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(() => {\n if (isZoomed) {\n closeZoom();\n } else {\n close();\n }\n }) : undefined), [close, isOpen, isZoomed]);\n\n useEffect(() => {\n if (isVideo && !isGif) {\n stopCurrentAudio();\n }\n }, [isGif, isVideo]);\n\n const getMessageId = useCallback((fromId: number, direction: number): number => {\n let index = messageIds.indexOf(fromId);\n if ((direction === -1 && index > 0) || (direction === 1 && index < messageIds.length - 1)) {\n index += direction;\n }\n\n return messageIds[index];\n }, [messageIds]);\n\n const selectPreviousMedia = useCallback(() => {\n if (isFirst) {\n return;\n }\n\n openMediaViewer({\n chatId,\n threadId,\n messageId: messageId ? getMessageId(messageId, -1) : undefined,\n origin,\n });\n }, [chatId, threadId, getMessageId, isFirst, messageId, openMediaViewer, origin]);\n\n const selectNextMedia = useCallback(() => {\n if (isLast) {\n return;\n }\n\n openMediaViewer({\n chatId,\n threadId,\n messageId: messageId ? getMessageId(messageId, 1) : undefined,\n origin,\n });\n }, [chatId, threadId, getMessageId, isLast, messageId, openMediaViewer, origin]);\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n switch (e.key) {\n case 'Left': // IE/Edge specific value\n case 'ArrowLeft':\n selectPreviousMedia();\n break;\n\n case 'Right': // IE/Edge specific value\n case 'ArrowRight':\n selectNextMedia();\n break;\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n });\n\n // Support for swipe gestures and closing on click\n useEffect(() => {\n const element = document.querySelector('.slide-container > .active, .slide-container > .to');\n if (!element) {\n return undefined;\n }\n\n const shouldCloseOnVideo = isGif && !IS_IOS;\n\n return captureEvents(element, {\n // eslint-disable-next-line max-len\n excludedClosestSelector: `.backdrop, .navigation, .media-viewer-head, .media-viewer-footer${!shouldCloseOnVideo ? ', .VideoPlayer' : ''}`,\n onClick: () => {\n if (!isZoomed) {\n close();\n }\n },\n onSwipe: IS_TOUCH_ENV ? (e, direction) => {\n if (direction === SwipeDirection.Right) {\n selectPreviousMedia();\n } else if (direction === SwipeDirection.Left) {\n selectNextMedia();\n } else {\n close();\n }\n } : undefined,\n });\n }, [close, isGif, isZoomed, selectNextMedia, selectPreviousMedia, canPanZoomWrap]);\n\n const handlePan = useCallback((x: number, y: number) => {\n setPanDelta({ x, y });\n }, []);\n\n const lang = useLang();\n\n function renderSlide(isActive: boolean) {\n if (avatarOwner) {\n return (\n
\n {renderPhoto(\n fullMediaData || blobUrlPreview,\n calculateMediaViewerDimensions(AVATAR_FULL_DIMENSIONS, false),\n !IS_MOBILE_SCREEN && !isZoomed,\n )}\n
\n );\n } else if (message) {\n const textParts = renderMessageText(message);\n const hasFooter = Boolean(textParts);\n\n return (\n
\n {isPhoto && renderPhoto(\n localBlobUrl || fullMediaData || blobUrlPreview || blobUrlPictogram,\n message && calculateMediaViewerDimensions(photoDimensions!, hasFooter),\n !IS_MOBILE_SCREEN && !isZoomed,\n )}\n {isVideo && (\n \n )}\n {textParts && (\n \n )}\n
\n );\n }\n\n return undefined;\n }\n\n function renderSenderInfo() {\n return (\n \n );\n }\n\n return (\n \n {() => (\n <>\n
\n {IS_MOBILE_SCREEN && (\n \n \n \n )}\n \n {renderSenderInfo}\n \n \n
\n \n \n {renderSlide}\n \n \n {!isFirst && (\n \n )}\n {!isLast && (\n \n )}\n \n \n )}\n \n );\n};\n\nfunction renderPhoto(blobUrl?: string, imageSize?: IDimensions, canDrag?: boolean) {\n return blobUrl\n ? (\n \n )\n : (\n \n \n \n );\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = global.mediaViewer;\n const {\n animationLevel,\n } = global.settings.byKey;\n\n if (origin === MediaViewerOrigin.SearchResult) {\n if (!(chatId && messageId)) {\n return { animationLevel };\n }\n\n const message = selectChatMessage(global, chatId, messageId);\n if (!message) {\n return { animationLevel };\n }\n\n return {\n chatId,\n messageId,\n senderId: message.senderId,\n origin,\n message,\n animationLevel,\n };\n }\n\n if (avatarOwnerId) {\n const sender = selectUser(global, avatarOwnerId) || selectChat(global, avatarOwnerId);\n\n return {\n messageId: -1,\n senderId: avatarOwnerId,\n avatarOwner: sender,\n profilePhotoIndex: profilePhotoIndex || 0,\n animationLevel,\n origin,\n };\n }\n\n if (!(chatId && threadId && messageId)) {\n return { animationLevel };\n }\n\n let message: ApiMessage | undefined;\n if (origin && [MediaViewerOrigin.ScheduledAlbum, MediaViewerOrigin.ScheduledInline].includes(origin)) {\n message = selectScheduledMessage(global, chatId, messageId);\n } else {\n message = selectChatMessage(global, chatId, messageId);\n }\n\n if (!message) {\n return { animationLevel };\n }\n\n let chatMessages: Record | undefined;\n\n if (origin && [MediaViewerOrigin.ScheduledAlbum, MediaViewerOrigin.ScheduledInline].includes(origin)) {\n chatMessages = selectScheduledMessages(global, chatId);\n } else {\n chatMessages = selectChatMessages(global, chatId);\n }\n let collectionIds: number[] | undefined;\n\n if (origin === MediaViewerOrigin.Inline || origin === MediaViewerOrigin.Album) {\n collectionIds = selectOutlyingIds(global, chatId, threadId) || selectListedIds(global, chatId, threadId);\n } else if (origin === MediaViewerOrigin.SharedMedia) {\n const currentSearch = selectCurrentMediaSearch(global);\n const { foundIds } = (currentSearch && currentSearch.resultsByType && currentSearch.resultsByType.media) || {};\n collectionIds = foundIds;\n }\n\n return {\n chatId,\n threadId,\n messageId,\n senderId: message.senderId,\n origin,\n message,\n chatMessages,\n collectionIds,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openMediaViewer', 'closeMediaViewer', 'openForwardMenu', 'focusMessage',\n ]),\n)(MediaViewer));\n","import React, {\n FC, useMemo, useState, memo, useRef, useEffect, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, MAIN_THREAD_ID } from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n getCanPostInChat, getChatTitle, isChatPrivate, sortChatIds,\n} from '../../modules/helpers';\nimport searchWords from '../../util/searchWords';\nimport { pick } from '../../util/iteratees';\nimport useInfiniteScroll from '../../hooks/useInfiniteScroll';\nimport useLang from '../../hooks/useLang';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\n\nimport Loading from '../ui/Loading';\nimport Modal from '../ui/Modal';\nimport InputText from '../ui/InputText';\nimport Button from '../ui/Button';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\n\nimport './ForwardPicker.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n};\n\ntype StateProps = {\n chatsById: Record;\n activeListIds?: number[];\n archivedListIds?: number[];\n orderedPinnedIds?: number[];\n currentUserId?: number;\n};\n\ntype DispatchProps = Pick;\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\nconst MODAL_HIDE_DELAY_MS = 300;\n\nconst ForwardPicker: FC = ({\n chatsById,\n activeListIds,\n archivedListIds,\n currentUserId,\n isOpen,\n setForwardChatId,\n exitForwardMode,\n loadMoreChats,\n}) => {\n const [filter, setFilter] = useState('');\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (isOpen) {\n if (!IS_MOBILE_SCREEN) {\n setTimeout(() => {\n requestAnimationFrame(() => {\n if (inputRef.current) {\n inputRef.current.focus();\n }\n });\n }, FOCUS_DELAY_MS);\n }\n } else {\n if (inputRef.current) {\n inputRef.current.blur();\n }\n\n setTimeout(() => {\n setFilter('');\n }, MODAL_HIDE_DELAY_MS);\n }\n }, [isOpen]);\n\n const chatIds = useMemo(() => {\n const listIds = [\n ...activeListIds || [],\n ...archivedListIds || [],\n ];\n\n return sortChatIds([\n ...listIds.filter((id) => {\n const chat = chatsById[id];\n if (!chat) {\n return true;\n }\n\n if (!getCanPostInChat(chat, MAIN_THREAD_ID)) {\n return false;\n }\n\n if (!filter) {\n return true;\n }\n\n return searchWords(getChatTitle(lang, chatsById[id], undefined, id === currentUserId), filter);\n }),\n ], chatsById, undefined, currentUserId ? [currentUserId] : undefined);\n }, [activeListIds, archivedListIds, chatsById, currentUserId, filter, lang]);\n\n const [viewportIds, getMore] = useInfiniteScroll(loadMoreChats, chatIds, Boolean(filter));\n\n const handleFilterChange = useCallback((e: React.ChangeEvent) => {\n setFilter(e.currentTarget.value);\n }, []);\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, isOpen, (index) => {\n if (viewportIds) {\n setForwardChatId({ id: viewportIds[index] });\n }\n }, '.ListItem-button', true);\n\n const modalHeader = (\n
\n \n \n \n \n
\n );\n\n return (\n \n {viewportIds && viewportIds.length ? (\n \n {viewportIds.map((id) => (\n setForwardChatId({ id })}\n >\n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n ))}\n \n ) : viewportIds && !viewportIds.length ? (\n

Sorry, nothing found.

\n ) : (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n },\n currentUserId,\n } = global;\n\n return {\n chatsById,\n activeListIds: listIds.active,\n archivedListIds: listIds.archived,\n currentUserId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setForwardChatId', 'exitForwardMode', 'loadMoreChats']),\n)(ForwardPicker));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiError } from '../../api/types';\n\nimport getReadableErrorText from '../../util/getReadableErrorText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './Errors.scss';\n\ntype StateProps = {\n errors: ApiError[];\n};\n\ntype DispatchProps = Pick;\n\nconst Errors: FC = ({ errors, dismissError }) => {\n const lang = useLang();\n\n if (!errors.length) {\n return undefined;\n }\n\n return (\n
\n {errors.map((error) => (\n \n

{getReadableErrorText(error)}

\n \n \n ))}\n
\n );\n};\n\nfunction getErrorHeader(error: ApiError) {\n if (error.isSlowMode) {\n return 'Slowmode enabled';\n }\n\n return 'Something went wrong';\n}\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['errors']),\n (setGlobal, actions): DispatchProps => pick(actions, ['dismissError']),\n)(Errors));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiNotification } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\n\nimport Notification from '../ui/Notification';\nimport renderText from '../common/helpers/renderText';\n\ntype StateProps = {\n notifications: ApiNotification[];\n};\n\ntype DispatchProps = Pick;\n\nconst Notifications: FC = ({ notifications, dismissNotification }) => {\n if (!notifications.length) {\n return undefined;\n }\n\n return (\n
\n {notifications.map(({ message }) => (\n \n ))}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['notifications']),\n (setGlobal, actions): DispatchProps => pick(actions, ['dismissNotification']),\n)(Notifications));\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\n\nexport type OwnProps = {\n url?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLinkModal: FC = ({ url, toggleSafeLinkModal }) => {\n const lang = useLang();\n\n const handleOpen = useCallback(() => {\n window.open(url);\n toggleSafeLinkModal({ url: undefined });\n }, [toggleSafeLinkModal, url]);\n\n const handleDismiss = useCallback(() => {\n toggleSafeLinkModal({ url: undefined });\n }, [toggleSafeLinkModal]);\n\n const renderingUrl = useCurrentOrPrev(url);\n\n return (\n \n );\n};\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['toggleSafeLinkModal']),\n)(SafeLinkModal));\n","import React, {\n FC, memo, useState, useEffect, useMemo, useCallback,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport {\n formatMonthAndYear, formatHumanDate, formatTime,\n} from '../../util/dateFormat';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './CalendarModal.scss';\n\nexport type OwnProps = {\n selectedAt?: number;\n maxAt?: number;\n isFutureMode?: boolean;\n isPastMode?: boolean;\n isOpen: boolean;\n withTimePicker?: boolean;\n submitButtonLabel?: string;\n secondButtonLabel?: string;\n onClose: () => void;\n onSubmit: (date: Date) => void;\n onSecondButtonClick?: NoneToVoidFunction;\n};\n\nconst WEEKDAY_LETTERS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];\n\nconst CalendarModal: FC = ({\n selectedAt,\n maxAt,\n isFutureMode,\n isPastMode,\n isOpen,\n withTimePicker,\n submitButtonLabel,\n secondButtonLabel,\n onClose,\n onSubmit,\n onSecondButtonClick,\n}) => {\n const lang = useLang();\n const now = new Date();\n const defaultSelectedDate = useMemo(() => (selectedAt ? new Date(selectedAt) : new Date()), [selectedAt]);\n const maxDate = maxAt ? new Date(maxAt) : undefined;\n\n const [selectedDate, setSelectedDate] = useState(defaultSelectedDate);\n const [selectedHours, setSelectedHours] = useState(\n formatInputTime(defaultSelectedDate.getHours()),\n );\n const [selectedMinutes, setSelectedMinutes] = useState(\n formatInputTime(defaultSelectedDate.getMinutes()),\n );\n\n const currentYear = selectedDate.getFullYear();\n const currentMonth = selectedDate.getMonth();\n const currentDate = selectedDate.getDate();\n\n useEffect(() => {\n if (isOpen) {\n setSelectedDate(defaultSelectedDate);\n }\n }, [isOpen, defaultSelectedDate]);\n\n const shouldDisableNextMonth = (isPastMode && currentYear >= now.getFullYear() && currentMonth >= now.getMonth())\n || (maxDate && currentYear >= maxDate.getFullYear() && currentMonth >= maxDate.getMonth());\n const shouldDisablePrevMonth = isFutureMode && currentYear <= now.getFullYear() && currentMonth <= now.getMonth();\n\n const calendarGrid = useMemo(() => (\n buildCalendarGrid(currentYear, currentMonth)\n ), [currentMonth, currentYear]);\n\n function handlePrevMonth() {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setMonth(dateCopy.getMonth() - 1);\n\n return dateCopy;\n });\n }\n\n function handleNextMonth() {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setMonth(dateCopy.getMonth() + 1);\n\n return dateCopy;\n });\n }\n\n function handleDateSelect(date: number) {\n setSelectedDate((d) => {\n const dateCopy = new Date(d);\n dateCopy.setDate(date);\n\n return dateCopy;\n });\n }\n\n function handleSubmit() {\n onSubmit(selectedDate);\n }\n\n const handleChangeHours = useCallback((e: React.ChangeEvent) => {\n const value = e.target.value.replace(/[^\\d]+/g, '');\n if (!value.length) {\n setSelectedHours('');\n e.target.value = '';\n return;\n }\n\n const hours = Math.max(0, Math.min(Number(value), 23));\n\n const date = new Date(selectedDate.getTime());\n date.setHours(hours);\n setSelectedDate(date);\n\n const hoursStr = formatInputTime(hours);\n setSelectedHours(hoursStr);\n e.target.value = hoursStr;\n }, [selectedDate]);\n\n const handleChangeMinutes = useCallback((e: React.ChangeEvent) => {\n const value = e.target.value.replace(/[^\\d]+/g, '');\n if (!value.length) {\n setSelectedMinutes('');\n e.target.value = '';\n return;\n }\n\n const minutes = Math.max(0, Math.min(Number(value), 59));\n\n const date = new Date(selectedDate.getTime());\n date.setMinutes(minutes);\n setSelectedDate(date);\n\n const minutesStr = formatInputTime(minutes);\n setSelectedMinutes(minutesStr);\n e.target.value = minutesStr;\n }, [selectedDate]);\n\n function renderTimePicker() {\n return (\n
\n \n :\n \n
\n );\n }\n\n return (\n \n
\n
\n \n \n \n\n

\n {formatMonthAndYear(lang, selectedDate, IS_MOBILE_SCREEN)}\n

\n\n \n \n \n\n \n \n \n
\n
\n\n
\n
\n {WEEKDAY_LETTERS.map((letter) => (\n
\n {letter}\n
\n ))}\n {calendarGrid.map((gridDate) => (\n handleDateSelect(gridDate)}\n className={buildClassName(\n 'day-button',\n isDisabledDay(\n currentYear, currentMonth, gridDate, isFutureMode ? now : undefined, isPastMode ? now : maxDate,\n )\n ? 'disabled'\n : `${gridDate ? 'clickable' : ''}`,\n gridDate === currentDate && 'selected',\n )}\n >\n {!!gridDate && (\n {gridDate}\n )}\n
\n ))}\n
\n \n\n {withTimePicker && renderTimePicker()}\n\n
\n \n {secondButtonLabel && (\n \n )}\n
\n \n );\n};\n\nfunction buildCalendarGrid(year: number, month: number) {\n const grid: number[] = [];\n\n const date = new Date();\n date.setFullYear(year);\n date.setMonth(month);\n date.setDate(1);\n\n const monthStartDay = date.getDay();\n // Fill empty cells\n for (let i = 1; i < monthStartDay; i++) {\n grid.push(0);\n }\n\n while (date.getMonth() === month) {\n const gridDate = date.getDate();\n grid.push(gridDate);\n date.setDate(gridDate + 1);\n }\n\n return grid;\n}\n\nfunction isDisabledDay(year: number, month: number, day: number, minDate?: Date, maxDate?: Date) {\n const selectedDay = new Date(year, month, day, 0, 0, 0, 0);\n const fixedMinDate = minDate && new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate(), 0, 0, 0, 0);\n const fixedMaxDate = maxDate && new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 0, 0, 0, 0);\n\n if (fixedMaxDate && selectedDay > fixedMaxDate) {\n return true;\n } else if (fixedMinDate && selectedDay < fixedMinDate) {\n return true;\n }\n\n return false;\n}\n\nfunction formatInputTime(value: string | number) {\n return String(value).padStart(2, '0');\n}\n\nfunction formatSubmitLabel(lang: LangFn, date: Date) {\n const day = formatHumanDate(lang, date, true);\n\n if (day === 'Today') {\n return lang('Conversation.ScheduleMessage.SendToday', formatTime(date));\n }\n\n return lang('Conversation.ScheduleMessage.SendOn', day).replace('%@', formatTime(date));\n}\n\nexport default memo(CalendarModal);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport CalendarModal from '../common/CalendarModal';\n\nexport type OwnProps = {\n isOpen: boolean;\n};\n\ntype StateProps = {\n selectedAt?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst HistoryCalendar: FC = ({\n isOpen, selectedAt, searchMessagesByDate, closeHistoryCalendar,\n}) => {\n const handleJumpToDate = useCallback((date: Date) => {\n searchMessagesByDate({ timestamp: date.valueOf() / 1000 });\n closeHistoryCalendar();\n }, [closeHistoryCalendar, searchMessagesByDate]);\n\n const lang = useLang();\n\n return (\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n selectedAt: global.historyCalendarSelectedAt,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesByDate', 'closeHistoryCalendar',\n ]),\n)(HistoryCalendar));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../api/types';\nimport { IAlbum } from '../../types';\n\nimport { GlobalActions } from '../../global/types';\n\nimport {\n selectAllowedMessageActions,\n selectChat,\n selectCurrentMessageList,\n selectUser,\n} from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n isSchedule: boolean;\n message: ApiMessage;\n album?: IAlbum;\n onClose: () => void;\n};\n\ntype StateProps = {\n canDeleteForAll?: boolean;\n contactName?: string;\n willDeleteForCurrentUserOnly?: boolean;\n willDeleteForAll?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst DeleteMessageModal: FC = ({\n isOpen,\n isSchedule,\n message,\n album,\n canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n onClose,\n deleteMessages,\n deleteScheduledMessages,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n const messageIds = album && album.messages\n ? album.messages.map(({ id }) => id)\n : [message.id];\n deleteMessages({ messageIds, shouldDeleteForAll: true });\n onClose();\n }, [deleteMessages, message.id, onClose, album]);\n\n const handleDeleteMessageForSelf = useCallback(() => {\n const messageIds = album && album.messages\n ? album.messages.map(({ id }) => id)\n : [message.id];\n if (isSchedule) {\n deleteScheduledMessages({ messageIds });\n } else {\n deleteMessages({\n messageIds,\n shouldDeleteForAll: false,\n });\n }\n onClose();\n }, [album, message.id, isSchedule, onClose, deleteScheduledMessages, deleteMessages]);\n\n const lang = useLang();\n\n return (\n \n

{lang('AreYouSureDeleteSingleMessage')}

\n {willDeleteForCurrentUserOnly && (\n

{lang('lng_delete_for_me_chat_hint')}

\n )}\n {willDeleteForAll && (\n

{lang('lng_delete_for_everyone_hint', 1, 'i')}

\n )}\n {canDeleteForAll && (\n \n )}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { message, isSchedule }): StateProps => {\n const { threadId } = selectCurrentMessageList(global) || {};\n const { canDeleteForAll } = (threadId && selectAllowedMessageActions(global, message, threadId)) || {};\n const chat = selectChat(global, message.chatId);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n const willDeleteForCurrentUserOnly = chat && isChatBasicGroup(chat) && !canDeleteForAll;\n const willDeleteForAll = chat && isChatSuperGroup(chat);\n\n return {\n canDeleteForAll: !isSchedule && canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'deleteMessages', 'deleteScheduledMessages',\n ]),\n)(DeleteMessageModal));\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { selectChat, selectIsChatWithSelf, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n isChatChannel,\n} from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n chatId: number;\n messageId: number;\n onClose: () => void;\n};\n\ntype StateProps = {\n isChannel: boolean;\n isPrivateChat: boolean;\n isChatWithSelf: boolean;\n isGroup: boolean;\n isSuperGroup: boolean;\n canPinForAll: boolean;\n contactName?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst PinMessageModal: FC = ({\n isOpen,\n messageId,\n chatId,\n isChannel,\n isGroup,\n isSuperGroup,\n canPinForAll,\n contactName,\n onClose,\n pinMessage,\n}) => {\n const handlePinMessageForAll = useCallback(() => {\n pinMessage({\n chatId, messageId, isUnpin: false,\n });\n onClose();\n }, [pinMessage, chatId, messageId, onClose]);\n\n const handlePinMessage = useCallback(() => {\n pinMessage({\n chatId, messageId, isUnpin: false, isOneSide: true, isSilent: true,\n });\n onClose();\n }, [chatId, messageId, onClose, pinMessage]);\n\n const lang = useLang();\n\n function renderMessage() {\n if (isChannel) {\n return lang('PinMessageAlertChannel');\n }\n\n if (isGroup || isSuperGroup) {\n return lang('PinMessageAlert');\n }\n\n return lang('PinMessageAlertChat');\n }\n\n return (\n \n

{renderMessage()}

\n \n {canPinForAll && (\n \n )}\n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const isPrivateChat = isChatPrivate(chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const chat = selectChat(global, chatId);\n const isChannel = !!chat && isChatChannel(chat);\n const isGroup = !!chat && isChatBasicGroup(chat);\n const isSuperGroup = !!chat && isChatSuperGroup(chat);\n const canPinForAll = (isPrivateChat && !isChatWithSelf) || isSuperGroup || isGroup;\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n return {\n isPrivateChat,\n isChatWithSelf,\n isChannel,\n isGroup,\n isSuperGroup,\n canPinForAll,\n contactName,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['pinMessage']),\n)(PinMessageModal));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n chatId?: number;\n pinnedMessagesCount?: number;\n onClose: () => void;\n onUnpin: () => void;\n};\n\nconst UnpinAllMessagesModal: FC = ({\n isOpen,\n pinnedMessagesCount = 0,\n onClose,\n onUnpin,\n}) => {\n const lang = useLang();\n\n return (\n \n

{lang('Chat.UnpinAllMessagesConfirmation', pinnedMessagesCount, 'i')}

\n \n \n \n );\n};\n\nexport default memo(UnpinAllMessagesModal);\n","import React, { FC, useCallback, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { selectCanDeleteSelectedMessages, selectCurrentChat, selectUser } from '../../modules/selectors';\nimport {\n isChatPrivate,\n getUserFirstOrLastName,\n getPrivateChatUserId,\n isChatBasicGroup,\n isChatSuperGroup,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nexport type OwnProps = {\n isOpen: boolean;\n isSchedule: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n selectedMessageIds?: number[];\n canDeleteForAll?: boolean;\n contactName?: string;\n willDeleteForCurrentUserOnly?: boolean;\n willDeleteForAll?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst DeleteSelectedMessagesModal: FC = ({\n isOpen,\n isSchedule,\n selectedMessageIds,\n canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n onClose,\n deleteMessages,\n deleteScheduledMessages,\n exitMessageSelectMode,\n}) => {\n const handleDeleteMessageForAll = useCallback(() => {\n deleteMessages({ messageIds: selectedMessageIds, shouldDeleteForAll: true });\n exitMessageSelectMode();\n onClose();\n }, [deleteMessages, exitMessageSelectMode, selectedMessageIds, onClose]);\n\n const handleDeleteMessageForSelf = useCallback(() => {\n if (isSchedule) {\n deleteScheduledMessages({ messageIds: selectedMessageIds });\n } else {\n deleteMessages({ messageIds: selectedMessageIds, shouldDeleteForAll: false });\n }\n\n exitMessageSelectMode();\n onClose();\n }, [\n isSchedule, exitMessageSelectMode, onClose, deleteScheduledMessages, selectedMessageIds, deleteMessages,\n ]);\n\n const lang = useLang();\n\n if (!selectedMessageIds) {\n return undefined;\n }\n\n return (\n \n

{lang('AreYouSureDeleteFewMessages')}

\n {willDeleteForCurrentUserOnly && (\n

This will delete them just for you, not for other participants in the chat.

\n )}\n {willDeleteForAll && (\n

This will delete them for everyone in this chat.

\n )}\n {canDeleteForAll && (\n \n )}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global, { isSchedule }): StateProps => {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { canDeleteForAll } = selectCanDeleteSelectedMessages(global);\n const chat = selectCurrentChat(global);\n const contactName = chat && isChatPrivate(chat.id)\n ? getUserFirstOrLastName(selectUser(global, getPrivateChatUserId(chat)!))\n : undefined;\n\n const willDeleteForCurrentUserOnly = chat && isChatBasicGroup(chat) && !canDeleteForAll;\n const willDeleteForAll = chat && isChatSuperGroup(chat);\n\n return {\n selectedMessageIds,\n canDeleteForAll: !isSchedule && canDeleteForAll,\n contactName,\n willDeleteForCurrentUserOnly,\n willDeleteForAll,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'deleteMessages',\n 'deleteScheduledMessages',\n 'exitMessageSelectMode',\n ]),\n)(DeleteSelectedMessagesModal));\n","import React, { FC, memo, useEffect } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\n\nimport {\n selectCanDeleteSelectedMessages,\n selectCurrentMessageList,\n selectSelectedMessagesCount,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport useFlag from '../../hooks/useFlag';\nimport captureKeyboardListeners from '../../util/captureKeyboardListeners';\nimport buildClassName from '../../util/buildClassName';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport MenuItem from '../ui/MenuItem';\n\nimport DeleteSelectedMessagesModal from './DeleteSelectedMessagesModal';\n\nimport './MessageSelectToolbar.scss';\n\nexport type OwnProps = {\n isActive?: boolean;\n canPost?: boolean;\n messageListType?: MessageListType;\n};\n\ntype StateProps = {\n isSchedule: boolean;\n selectedMessagesCount?: number;\n canDeleteMessages?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageSelectToolbar: FC = ({\n canPost,\n isActive,\n messageListType,\n isSchedule,\n selectedMessagesCount,\n canDeleteMessages,\n exitMessageSelectMode,\n openForwardMenuForSelectedMessages,\n}) => {\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n useEffect(() => {\n return isActive && !isDeleteModalOpen\n ? captureKeyboardListeners({\n onBackspace: openDeleteModal,\n onDelete: openDeleteModal,\n onEsc: exitMessageSelectMode,\n })\n : undefined;\n }, [isActive, isDeleteModalOpen, openDeleteModal, exitMessageSelectMode]);\n\n const prevSelectedMessagesCount = usePrevious(selectedMessagesCount || undefined, true);\n const renderingSelectedMessagesCount = isActive ? selectedMessagesCount : prevSelectedMessagesCount;\n\n const lang = useLang();\n\n const formattedMessagesCount = lang('VoiceOver.Chat.MessagesSelected', renderingSelectedMessagesCount);\n\n const className = buildClassName(\n 'MessageSelectToolbar',\n canPost && 'with-composer',\n isActive && 'shown',\n );\n\n return (\n
\n
\n \n \n \n \n {formattedMessagesCount}\n \n\n {!!selectedMessagesCount && (\n
\n {messageListType !== 'scheduled' && (\n \n \n {lang('Forward')}\n \n \n )}\n \n \n {lang('Delete')}\n \n \n
\n )}\n
\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { type: messageListType } = selectCurrentMessageList(global) || {};\n const { canDelete } = selectCanDeleteSelectedMessages(global);\n\n return {\n isSchedule: messageListType === 'scheduled',\n selectedMessagesCount: selectSelectedMessagesCount(global),\n canDeleteMessages: canDelete,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['exitMessageSelectMode', 'openForwardMenuForSelectedMessages']),\n)(MessageSelectToolbar));\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nexport default (\n onSelect: NoneToVoidFunction,\n) => {\n // eslint-disable-next-line no-null/no-null\n const buttonRef = useRef(null);\n\n const handleKeyDown = useCallback((e: KeyboardEvent) => {\n if (e.key !== 'Enter') return;\n const isFocused = buttonRef.current === document.activeElement;\n\n if (isFocused) {\n onSelect();\n }\n }, [onSelect]);\n\n useEffect(() => {\n window.addEventListener('keydown', handleKeyDown, false);\n\n return () => window.removeEventListener('keydown', handleKeyDown);\n }, [handleKeyDown]);\n\n return buttonRef;\n};\n","import React, {\n FC, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport useChatContextActions from '../../../hooks/useChatContextActions';\nimport useFlag from '../../../hooks/useFlag';\nimport { isChatPrivate, getPrivateChatUserId } from '../../../modules/helpers';\nimport { selectChat, selectUser, selectIsChatPinned } from '../../../modules/selectors';\nimport useSelectWithEnter from '../../../hooks/useSelectWithEnter';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../common/GroupChatInfo';\nimport DeleteChatModal from '../../common/DeleteChatModal';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n withUsername?: boolean;\n onClick: (id: number) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n isPinned?: boolean;\n};\n\nconst LeftSearchResultChat: FC = ({\n chatId,\n chat,\n privateChatUser,\n isPinned,\n withUsername,\n onClick,\n}) => {\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n\n const contextActions = useChatContextActions({\n chat,\n privateChatUser,\n isPinned,\n handleDelete: openDeleteModal,\n });\n\n const handleClick = () => {\n onClick(chatId);\n };\n\n const buttonRef = useSelectWithEnter(handleClick);\n\n if (!chat) {\n return undefined;\n }\n\n return (\n \n {isChatPrivate(chatId) ? (\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 privateChatUserId = chat && getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n const isPinned = selectIsChatPinned(global, chatId);\n\n return {\n chat,\n privateChatUser,\n isPinned,\n };\n },\n)(LeftSearchResultChat));\n","import React, {\n FC, useEffect, useCallback, useRef, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser } from '../../../api/types';\n\nimport { getUserFirstOrLastName } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport { throttle } from '../../../util/schedulers';\nimport { pick } from '../../../util/iteratees';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport LeftSearchResultChat from './LeftSearchResultChat';\n\nimport './RecentContacts.scss';\n\ntype OwnProps = {\n onReset: () => void;\n};\n\ntype StateProps = {\n topUserIds?: number[];\n usersById: Record;\n recentlyFoundChatIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SEARCH_CLOSE_TIMEOUT_MS = 250;\nconst NBSP = '\\u00A0';\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst RecentContacts: FC = ({\n topUserIds, usersById, recentlyFoundChatIds,\n onReset, loadTopUsers, loadContactList, openChat,\n addRecentlyFoundChatId, clearRecentlyFoundChats,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const topUsersRef = useRef(null);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadTopUsers();\n // Loading full contact list for quick local search before user enters the query\n loadContactList();\n });\n }, [loadTopUsers, loadContactList]);\n\n useHorizontalScroll(topUsersRef, !topUserIds);\n\n const handleClick = useCallback(\n (id: number) => {\n openChat({ id });\n onReset();\n setTimeout(() => {\n addRecentlyFoundChatId({ id });\n }, SEARCH_CLOSE_TIMEOUT_MS);\n },\n [openChat, addRecentlyFoundChatId, onReset],\n );\n\n const lang = useLang();\n\n return (\n
\n {topUserIds && (\n
\n
\n {topUserIds.map((userId) => (\n
handleClick(userId)} dir={lang.isRtl ? 'rtl' : undefined}>\n \n
{renderText(getUserFirstOrLastName(usersById[userId]) || NBSP)}
\n
\n ))}\n
\n
\n )}\n {recentlyFoundChatIds && (\n
\n

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

\n {recentlyFoundChatIds.map((id) => (\n \n ))}\n
\n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { userIds: topUserIds } = global.topPeers;\n const usersById = global.users.byId;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n return {\n topUserIds,\n usersById,\n recentlyFoundChatIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadTopUsers',\n 'loadContactList',\n 'openChat',\n 'addRecentlyFoundChatId',\n 'clearRecentlyFoundChats',\n ]),\n)(RecentContacts));\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiChat, ApiUser, ApiMessage, ApiMessageOutgoingStatus,\n} from '../../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n getChatTitle,\n getPrivateChatUserId,\n getMessageMediaHash,\n getMessageSummaryText,\n getMessageMediaThumbDataUri,\n getMessageVideo,\n getMessageRoundVideo,\n} from '../../../modules/helpers';\nimport { selectChat, selectUser } from '../../../modules/selectors';\nimport renderText from '../../common/helpers/renderText';\nimport { pick } from '../../../util/iteratees';\nimport useMedia from '../../../hooks/useMedia';\nimport { formatPastTimeShort } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\nimport useSelectWithEnter from '../../../hooks/useSelectWithEnter';\n\nimport Avatar from '../../common/Avatar';\nimport VerifiedIcon from '../../common/VerifiedIcon';\nimport ListItem from '../../ui/ListItem';\nimport Link from '../../ui/Link';\n\nimport './ChatMessage.scss';\n\ntype OwnProps = {\n searchQuery?: string;\n message: ApiMessage;\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n privateChatUser?: ApiUser;\n lastMessageOutgoingStatus?: ApiMessageOutgoingStatus;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatMessage: FC = ({\n message,\n searchQuery,\n chatId,\n chat,\n privateChatUser,\n focusMessage,\n lastSyncTime,\n}) => {\n const mediaThumbnail = getMessageMediaThumbDataUri(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'micro'));\n const isRoundVideo = Boolean(getMessageRoundVideo(message));\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId, messageId: message.id });\n }, [chatId, focusMessage, message.id]);\n\n const lang = useLang();\n\n const buttonRef = useSelectWithEnter(handleClick);\n\n if (!chat) {\n return undefined;\n }\n\n return (\n \n \n
\n
\n
\n

{renderText(getChatTitle(lang, chat, privateChatUser))}

\n {chat.isVerified && }\n
\n
\n \n {formatPastTimeShort(lang, message.date * 1000)}\n \n
\n\n
\n
\n
\n {renderMessageSummary(lang, message, mediaBlobUrl || mediaThumbnail, searchQuery, isRoundVideo)}\n
\n
\n
\n \n );\n};\n\nfunction renderMessageSummary(\n lang: LangFn, message: ApiMessage, blobUrl?: string, searchQuery?: string, isRoundVideo?: boolean,\n) {\n if (!blobUrl) {\n return renderText(getMessageSummaryText(lang, message));\n }\n\n return (\n \n \"\"\n {getMessageVideo(message) && }\n {renderText(getMessageSummaryText(lang, message, true), ['emoji', 'highlight'], { highlight: searchQuery })}\n \n );\n}\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const privateChatUserId = getPrivateChatUserId(chat);\n\n return {\n chat,\n ...(privateChatUserId && { privateChatUser: selectUser(global, privateChatUserId) }),\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n ]),\n)(ChatMessage));\n","import React, { FC, memo, useMemo } from '../../../lib/teact/teact';\nimport { formatDateToString } from '../../../util/dateFormat';\n\nimport './DateSuggest.scss';\n\nconst SUGGESTION_COUNT = 8;\n\nexport type OwnProps = {\n searchDate: string;\n onSelect: (value: Date) => void;\n};\n\nconst DateSuggest: FC = ({\n searchDate, onSelect,\n}) => {\n const suggestions = useMemo(() => getSuggestionsFromDate(searchDate), [searchDate]);\n return (\n
\n {suggestions.map(({ date, text }) => {\n return (\n onSelect(date)}\n className=\"date-item\"\n key={text}\n >\n \n {text}\n \n );\n })}\n
\n );\n};\n\nfunction getSuggestionsFromDate(searchDate: string) {\n const hasYear = searchDate.match(/^\\d{2,4}-\\d{2}-\\d{2}$/g);\n if (hasYear) {\n const date = new Date(searchDate);\n return [{ date, text: formatDateToString(date) }];\n }\n\n const suggestion = [];\n const currentDate = new Date();\n const currentYear = currentDate.getFullYear();\n const latestYear = currentDate.getTime() > (new Date(`${currentYear}-${searchDate}`)).getTime()\n ? currentYear\n : currentYear - 1;\n\n for (let i = 0; i < SUGGESTION_COUNT; i++) {\n const date = new Date(`${latestYear - i}-${searchDate}`);\n suggestion.push({ date, text: formatDateToString(date) });\n }\n\n return suggestion;\n}\n\nexport default memo(DateSuggest);\n","import React, {\n FC, memo, useCallback, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUser, ApiChat, ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport searchWords from '../../../util/searchWords';\nimport { unique, pick } from '../../../util/iteratees';\nimport { getUserFullName, getMessageSummaryText, sortChatIds } from '../../../modules/helpers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport LeftSearchResultChat from './LeftSearchResultChat';\nimport RecentContacts from './RecentContacts';\nimport ChatMessage from './ChatMessage';\nimport DateSuggest from './DateSuggest';\nimport Link from '../../ui/Link';\nimport NothingFound from '../../common/NothingFound';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\n\nexport type OwnProps = {\n searchQuery?: string;\n dateSearchQuery?: string;\n searchDate?: number;\n onReset: () => void;\n onSearchDateSelect: (value: Date) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n localContactIds?: number[];\n localChatIds?: number[];\n localUserIds?: number[];\n globalChatIds?: number[];\n globalUserIds?: number[];\n foundIds?: string[];\n globalMessagesByChatId?: Record }>;\n chatsById: Record;\n usersById: Record;\n fetchingStatus?: { chats?: boolean; messages?: boolean };\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst MIN_QUERY_LENGTH_FOR_GLOBAL_SEARCH = 4;\nconst LESS_LIST_ITEMS_AMOUNT = 3;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst ChatResults: FC = ({\n searchQuery, searchDate, dateSearchQuery, currentUserId,\n localContactIds, localChatIds, localUserIds, globalChatIds, globalUserIds,\n foundIds, globalMessagesByChatId, chatsById, usersById, fetchingStatus, lastSyncTime,\n onReset, onSearchDateSelect, openChat, addRecentlyFoundChatId, searchMessagesGlobal, setGlobalSearchChatId,\n}) => {\n const lang = useLang();\n\n const [shouldShowMoreLocal, setShouldShowMoreLocal] = useState(false);\n const [shouldShowMoreGlobal, setShouldShowMoreGlobal] = useState(false);\n\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: 'text',\n query: searchQuery,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery]);\n\n const handleChatClick = useCallback(\n (id: number) => {\n openChat({ id });\n\n if (id !== currentUserId) {\n addRecentlyFoundChatId({ id });\n }\n\n if (!IS_MOBILE_SCREEN) {\n onReset();\n }\n },\n [currentUserId, openChat, addRecentlyFoundChatId, onReset],\n );\n\n const handlePickerItemClick = useCallback((id: number) => {\n setGlobalSearchChatId({ id });\n }, [setGlobalSearchChatId]);\n\n const localResults = useMemo(() => {\n if (!searchQuery || (searchQuery.startsWith('@') && searchQuery.length < 2)) {\n return MEMO_EMPTY_ARRAY;\n }\n\n const foundContactIds = localContactIds\n ? localContactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const fullName = getUserFullName(user);\n return (fullName && searchWords(fullName, searchQuery)) || searchWords(user.username, searchQuery);\n })\n : [];\n\n return [\n ...(currentUserId && searchWords(lang('SavedMessages'), searchQuery) ? [currentUserId] : []),\n ...sortChatIds(unique([\n ...foundContactIds,\n ...(localChatIds || []),\n ...(localUserIds || []),\n ]), chatsById),\n ];\n }, [searchQuery, localContactIds, currentUserId, lang, localChatIds, localUserIds, chatsById, usersById]);\n\n const globalResults = useMemo(() => {\n if (!searchQuery || searchQuery.length < MIN_QUERY_LENGTH_FOR_GLOBAL_SEARCH || !globalChatIds || !globalUserIds) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return sortChatIds(unique([...globalChatIds, ...globalUserIds]), chatsById, true);\n }, [chatsById, globalChatIds, globalUserIds, searchQuery]);\n\n const foundMessages = useMemo(() => {\n if ((!searchQuery && !searchDate) || !foundIds || foundIds.length === 0) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds\n .map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return (\n globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]\n );\n })\n .filter(Boolean as any)\n .sort((a, b) => b.date - a.date);\n }, [foundIds, globalMessagesByChatId, searchQuery, searchDate]);\n\n const handleClickShowMoreLocal = useCallback(() => {\n setShouldShowMoreLocal(!shouldShowMoreLocal);\n }, [shouldShowMoreLocal]);\n\n const handleClickShowMoreGlobal = useCallback(() => {\n setShouldShowMoreGlobal(!shouldShowMoreGlobal);\n }, [shouldShowMoreGlobal]);\n\n function renderFoundMessage(message: ApiMessage) {\n const text = getMessageSummaryText(lang, message);\n const chat = chatsById[message.chatId];\n\n if (!text || !chat) {\n return undefined;\n }\n\n return (\n \n );\n }\n\n const nothingFound = fetchingStatus && !fetchingStatus.chats && !fetchingStatus.messages\n && !localResults.length && !globalResults.length && !foundMessages.length;\n\n if (!searchQuery && !searchDate) {\n return ;\n }\n\n return (\n \n {dateSearchQuery && (\n
\n \n
\n )}\n {nothingFound && (\n \n )}\n {!!localResults.length && (\n
\n {localResults.map((id) => (\n \n ))}\n
\n )}\n {!!localResults.length && (\n
\n

\n {localResults.length > LESS_LIST_ITEMS_AMOUNT && (\n \n {lang(shouldShowMoreLocal ? 'ChatList.Search.ShowLess' : 'ChatList.Search.ShowMore')}\n \n )}\n {lang('DialogList.SearchSectionDialogs')}\n

\n {localResults.map((id, index) => {\n if (!shouldShowMoreLocal && index >= LESS_LIST_ITEMS_AMOUNT) {\n return undefined;\n }\n\n return (\n \n );\n })}\n
\n )}\n {!!globalResults.length && (\n
\n

\n {globalResults.length > LESS_LIST_ITEMS_AMOUNT && (\n \n {lang(shouldShowMoreGlobal ? 'ChatList.Search.ShowLess' : 'ChatList.Search.ShowMore')}\n \n )}\n {lang('DialogList.SearchSectionGlobal')}\n

\n {globalResults.map((id, index) => {\n if (!shouldShowMoreGlobal && index >= LESS_LIST_ITEMS_AMOUNT) {\n return undefined;\n }\n\n return (\n \n );\n })}\n
\n )}\n {!!foundMessages.length && (\n
\n

{lang('SearchMessages')}

\n {foundMessages.map(renderFoundMessage)}\n
\n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { byId: chatsById } = global.chats;\n const { byId: usersById } = global.users;\n\n const { userIds: localContactIds } = global.contactList || {};\n\n if (!localContactIds) {\n return {\n chatsById,\n usersById,\n };\n }\n\n const { currentUserId, messages, lastSyncTime } = global;\n const {\n fetchingStatus, globalResults, localResults, resultsByType,\n } = global.globalSearch;\n const { chatIds: globalChatIds, userIds: globalUserIds } = globalResults || {};\n const { chatIds: localChatIds, userIds: localUserIds } = localResults || {};\n const { byChatId: globalMessagesByChatId } = messages;\n const { foundIds } = (resultsByType && resultsByType.text) || {};\n\n return {\n currentUserId,\n localContactIds,\n localChatIds,\n localUserIds,\n globalChatIds,\n globalUserIds,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n usersById,\n fetchingStatus,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'addRecentlyFoundChatId',\n 'searchMessagesGlobal',\n 'setGlobalSearchChatId',\n ]),\n)(ChatResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { getMessageSummaryText } from '../../../modules/helpers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport ChatMessage from './ChatMessage';\nimport NothingFound from '../../common/NothingFound';\nimport DateSuggest from './DateSuggest';\n\nexport type OwnProps = {\n searchQuery?: string;\n dateSearchQuery?: string;\n onReset: () => void;\n onSearchDateSelect: (value: Date) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n foundIds?: string[];\n globalMessagesByChatId?: Record }>;\n chatsById: Record;\n fetchingStatus?: { chats?: boolean; messages?: boolean };\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst ChatMessageResults: FC = ({\n searchQuery,\n currentUserId,\n dateSearchQuery,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n fetchingStatus,\n lastSyncTime,\n searchMessagesGlobal,\n onSearchDateSelect,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: 'text',\n query: searchQuery,\n chatId: currentUserId,\n });\n });\n }\n }, [currentUserId, lastSyncTime, searchMessagesGlobal, searchQuery]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || foundIds.length === 0) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds\n .map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return (\n globalMessagesByChatId && globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId]\n );\n })\n .filter(Boolean as any)\n .sort((a, b) => b.date - a.date);\n }, [foundIds, globalMessagesByChatId]);\n\n function renderFoundMessage(message: ApiMessage) {\n const text = getMessageSummaryText(lang, message);\n const chat = chatsById[message.chatId];\n\n if (!text || !chat) {\n return undefined;\n }\n\n return (\n \n );\n }\n\n const nothingFound = fetchingStatus && !fetchingStatus.chats && !fetchingStatus.messages && !foundMessages.length;\n\n return (\n
\n \n {dateSearchQuery && (\n
\n \n
\n )}\n {nothingFound && (\n \n )}\n {!!foundMessages.length && foundMessages.map(renderFoundMessage)}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { byId: chatsById } = global.chats;\n const { currentUserId, messages: { byChatId: globalMessagesByChatId }, lastSyncTime } = global;\n const { fetchingStatus, resultsByType } = global.globalSearch;\n\n const { foundIds } = (resultsByType && resultsByType.text) || {};\n\n return {\n currentUserId,\n foundIds,\n globalMessagesByChatId,\n chatsById,\n fetchingStatus,\n lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['searchMessagesGlobal']),\n)(ChatMessageResults));\n","import { GlobalState } from '../../../../global/types';\nimport {\n ApiChat, ApiGlobalMessageSearchType, ApiMessage, ApiUser,\n} from '../../../../api/types';\n\nexport type StateProps = {\n isLoading?: boolean;\n chatsById: Record;\n usersById: Record;\n globalMessagesByChatId?: Record }>;\n foundIds?: string[];\n lastSyncTime?: number;\n searchChatId?: number;\n};\n\nexport function createMapStateToProps(type: ApiGlobalMessageSearchType) {\n return (global: GlobalState, props: any) => {\n const { byId: chatsById } = global.chats;\n const { byId: usersById } = global.users;\n const {\n fetchingStatus, resultsByType, chatId,\n } = global.globalSearch;\n\n // One component is used for two different types of results.\n // The differences between them are only in the isVoice property.\n // The rest of the search results use their own personal components.\n const currentType = type !== 'audio' ? type : (props && props.isVoice ? 'voice' : 'audio');\n\n const { byChatId: globalMessagesByChatId } = global.messages;\n const { foundIds } = (resultsByType && resultsByType[currentType]) || {};\n\n return {\n isLoading: foundIds === undefined\n || (fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false),\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n searchChatId: chatId,\n lastSyncTime: global.lastSyncTime,\n };\n };\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection, MediaViewerOrigin } from '../../../types';\n\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { throttle } from '../../../util/schedulers';\nimport useLang from '../../../hooks/useLang';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Media from '../../common/Media';\nimport ChatMessage from './ChatMessage';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst CURRENT_TYPE = 'media';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst MediaResults: FC = ({\n searchQuery,\n searchChatId,\n isLoading,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n openMediaViewer,\n}) => {\n const lang = useLang();\n\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleSelectMedia = useCallback((messageId: number, chatId: number) => {\n openMediaViewer({\n chatId,\n messageId,\n origin: MediaViewerOrigin.SearchResult,\n });\n }, [openMediaViewer]);\n\n function renderGallery() {\n return (\n
\n {foundMessages.map((message) => (\n \n ))}\n
\n );\n }\n\n function renderSearchResult() {\n return foundMessages.map((message) => (\n \n ));\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n const isMediaGrid = canRenderContents && foundIds && foundIds.length > 0 && !searchQuery;\n const isMessageList = canRenderContents && foundIds && foundIds.length > 0 && searchQuery;\n\n const classNames = buildClassName(\n 'search-content custom-scroll',\n isMessageList && 'chat-list',\n );\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {isMediaGrid && renderGallery()}\n {isMessageList && renderSearchResult()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'openMediaViewer',\n ]),\n)(MediaResults));\n","import { ApiChat, ApiMessage, ApiUser } from '../../../../api/types';\nimport {\n getChatTitle,\n getSenderTitle,\n isChatPrivate,\n isChatGroup,\n} from '../../../../modules/helpers';\nimport { LangFn } from '../../../../hooks/useLang';\n\nexport function getSenderName(\n lang: LangFn, message: ApiMessage, chatsById: Record, usersById: Record,\n) {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n const sender = isChatPrivate(senderId) ? usersById[senderId] : chatsById[senderId];\n\n let senderName = getSenderTitle(lang, sender);\n\n const chat = chatsById[message.chatId];\n if (chat) {\n if (isChatPrivate(senderId) && (sender as ApiUser).isSelf) {\n senderName = `${lang('FromYou')} → ${getChatTitle(lang, chat)}`;\n } else if (isChatGroup(chat)) {\n senderName += ` → ${getChatTitle(lang, chat)}`;\n }\n }\n\n return senderName;\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport WebLink from '../../common/WebLink';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst CURRENT_TYPE = 'links';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst LinkResults: FC = ({\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n \n {shouldDrawDateDivider && (\n

\n {formatMonthAndYear(lang, new Date(message.date * 1000))}\n

\n )}\n \n \n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n ]),\n)(LinkResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport { getMessageDocument } from '../../../modules/helpers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport Document from '../../common/Document';\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst CURRENT_TYPE = 'documents';\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst FileResults: FC = ({\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n}) => {\n const lang = useLang();\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: CURRENT_TYPE,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n const message = globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n\n return message && getMessageDocument(message) ? message : undefined;\n }).filter(Boolean) as ApiMessage[];\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n \n {shouldDrawDateDivider && (\n

{formatMonthAndYear(lang, new Date(message.date * 1000))}

\n )}\n \n \n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps(CURRENT_TYPE),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n ]),\n)(FileResults));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { createMapStateToProps, StateProps } from './helpers/createMapStateToProps';\nimport { pick } from '../../../util/iteratees';\nimport { formatMonthAndYear, toYearMonth } from '../../../util/dateFormat';\nimport { getSenderName } from './helpers/getSenderName';\nimport { throttle } from '../../../util/schedulers';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useLang from '../../../hooks/useLang';\n\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport Audio from '../../common/Audio';\nimport NothingFound from '../../common/NothingFound';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n isVoice?: boolean;\n searchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\n\nconst AudioResults: FC = ({\n isVoice,\n searchQuery,\n searchChatId,\n isLoading,\n chatsById,\n usersById,\n globalMessagesByChatId,\n foundIds,\n lastSyncTime,\n searchMessagesGlobal,\n focusMessage,\n openAudioPlayer,\n}) => {\n const lang = useLang();\n const currentType = isVoice ? 'voice' : 'audio';\n const handleLoadMore = useCallback(({ direction }: { direction: LoadMoreDirection }) => {\n if (lastSyncTime && direction === LoadMoreDirection.Backwards) {\n runThrottled(() => {\n searchMessagesGlobal({\n type: currentType,\n query: searchQuery,\n chatId: searchChatId,\n });\n });\n }\n }, [currentType, lastSyncTime, searchMessagesGlobal, searchQuery, searchChatId]);\n\n const foundMessages = useMemo(() => {\n if (!foundIds || !globalMessagesByChatId) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return foundIds.map((id) => {\n const [chatId, messageId] = id.split('_').map(Number);\n\n return globalMessagesByChatId[chatId] && globalMessagesByChatId[chatId].byId[messageId];\n }).filter(Boolean);\n }, [globalMessagesByChatId, foundIds]);\n\n const handleMessageFocus = useCallback((messageId: number, chatId: number) => {\n focusMessage({ chatId, messageId });\n }, [focusMessage]);\n\n const handlePlayAudio = useCallback((messageId: number, chatId: number) => {\n openAudioPlayer({ chatId, messageId });\n }, [openAudioPlayer]);\n\n function renderList() {\n return foundMessages.map((message, index) => {\n const shouldDrawDateDivider = index === 0\n || toYearMonth(message.date) !== toYearMonth(foundMessages[index - 1].date);\n return (\n \n {shouldDrawDateDivider && (\n

\n {formatMonthAndYear(lang, new Date(message.date * 1000))}\n

\n )}\n \n \n );\n });\n }\n\n const canRenderContents = useAsyncRendering([searchQuery], SLIDE_TRANSITION_DURATION) && !isLoading;\n\n return (\n
\n \n {!canRenderContents && }\n {canRenderContents && (!foundIds || foundIds.length === 0) && (\n \n )}\n {canRenderContents && foundIds && foundIds.length > 0 && renderList()}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n createMapStateToProps('audio'),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'searchMessagesGlobal',\n 'focusMessage',\n 'openAudioPlayer',\n ]),\n)(AudioResults));\n","import React, {\n FC, memo, useCallback, useState, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { GlobalSearchContent } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { parseDateString } from '../../../util/dateFormat';\nimport useKeyboardListNavigation from '../../../hooks/useKeyboardListNavigation';\nimport useLang from '../../../hooks/useLang';\n\nimport TabList from '../../ui/TabList';\nimport Transition from '../../ui/Transition';\nimport ChatResults from './ChatResults';\nimport UserChatResults from './ChatMessageResults';\nimport MediaResults from './MediaResults';\nimport LinkResults from './LinkResults';\nimport FileResults from './FileResults';\nimport AudioResults from './AudioResults';\n\nimport './LeftSearch.scss';\n\nexport type OwnProps = {\n searchQuery?: string;\n searchDate?: number;\n isActive: boolean;\n onReset: () => void;\n};\n\ntype StateProps = {\n currentContent?: GlobalSearchContent;\n chatId?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst TABS = [\n { type: GlobalSearchContent.ChatList, title: 'SearchAllChatsShort' },\n { type: GlobalSearchContent.Media, title: 'SharedMediaTab2' },\n { type: GlobalSearchContent.Links, title: 'SharedLinksTab2' },\n { type: GlobalSearchContent.Files, title: 'SharedFilesTab2' },\n { type: GlobalSearchContent.Music, title: 'SharedMusicTab2' },\n { type: GlobalSearchContent.Voice, title: 'SharedVoiceTab2' },\n];\n\nconst CHAT_TABS = [\n { type: GlobalSearchContent.ChatList, title: 'All Messages' },\n ...TABS.slice(1),\n];\n\nconst TRANSITION_RENDER_COUNT = Object.keys(GlobalSearchContent).length / 2;\n\nconst LeftSearch: FC = ({\n searchQuery,\n searchDate,\n isActive,\n currentContent = GlobalSearchContent.ChatList,\n chatId,\n setGlobalSearchContent,\n setGlobalSearchDate,\n onReset,\n}) => {\n const lang = useLang();\n const [activeTab, setActiveTab] = useState(0);\n const dateSearchQuery = useMemo(() => parseDateString(searchQuery), [searchQuery]);\n\n const handleSwitchTab = useCallback((index: number) => {\n const tab = TABS[index];\n setGlobalSearchContent({ content: tab.type });\n setActiveTab(index);\n }, [setGlobalSearchContent]);\n\n const handleSearchDateSelect = useCallback((value: Date) => {\n setGlobalSearchDate({ date: value.getTime() / 1000 });\n }, [setGlobalSearchDate]);\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, isActive, undefined, '.ListItem-button', true);\n\n return (\n
\n \n \n {() => {\n switch (currentContent) {\n case GlobalSearchContent.ChatList:\n if (chatId) {\n return (\n \n );\n }\n return (\n \n );\n case GlobalSearchContent.Media:\n return ;\n case GlobalSearchContent.Links:\n return ;\n case GlobalSearchContent.Files:\n return ;\n case GlobalSearchContent.Music:\n return (\n \n );\n case GlobalSearchContent.Voice:\n return (\n \n );\n default:\n return undefined;\n }\n }}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentContent, chatId } = global.globalSearch;\n\n return { currentContent, chatId };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setGlobalSearchContent', 'setGlobalSearchDate']),\n)(LeftSearch));\n","import { useState, useCallback, useRef } from '../lib/teact/teact';\n\nexport type ReducerAction = { type: Actions; payload?: any };\nexport type StateReducer = (state: State, action: ReducerAction) => State;\nexport type Dispatch = (action: ReducerAction) => void;\n\nexport default function useReducer(\n reducer: StateReducer,\n initialState: State,\n) {\n const reducerRef = useRef(reducer);\n const [state, setState] = useState(initialState);\n\n const dispatch = useCallback((action: ReducerAction) => {\n setState((currentState) => reducerRef.current(currentState, action));\n }, []);\n\n return [\n state,\n dispatch,\n ] as [State, Dispatch];\n}\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\nimport { ApiChatFolder } from '../../api/types';\nimport { pick, omit } from '../../util/iteratees';\n\nexport type FolderChatType = {\n icon: string;\n title: string;\n key: keyof Pick;\n};\n\nexport const INCLUDED_CHAT_TYPES: FolderChatType[] = [\n { icon: 'user', title: 'FilterContacts', key: 'contacts' },\n { icon: 'non-contacts', title: 'FilterNonContacts', key: 'nonContacts' },\n { icon: 'group', title: 'FilterGroups', key: 'groups' },\n { icon: 'channel', title: 'FilterChannels', key: 'channels' },\n { icon: 'bots', title: 'FilterBots', key: 'bots' },\n];\n\nexport const EXCLUDED_CHAT_TYPES: FolderChatType[] = [\n { icon: 'mute', title: 'FilterMuted', key: 'excludeMuted' },\n { icon: 'archive', title: 'FilterArchived', key: 'excludeArchived' },\n { icon: 'readchats', title: 'FilterRead', key: 'excludeRead' },\n];\n\nconst INCLUDE_FILTER_FIELDS: Array = [\n 'includedChatIds', 'bots', 'channels', 'groups', 'contacts', 'nonContacts',\n];\nconst EXCLUDE_FILTER_FIELDS: Array = [\n 'excludedChatIds', 'excludeArchived', 'excludeMuted', 'excludeRead',\n];\n\nexport function selectChatFilters(state: FoldersState, mode: 'included' | 'excluded', selectTemp?: boolean) {\n let selectedChatIds: number[] = [];\n let selectedChatTypes: FolderChatType['key'][] = [];\n\n if (mode === 'included') {\n const {\n includedChatIds,\n ...includeFilters\n } = selectTemp\n ? state.includeFilters || {}\n : pick(\n state.folder,\n INCLUDE_FILTER_FIELDS,\n );\n\n selectedChatIds = includedChatIds || [];\n selectedChatTypes = (Object.keys(includeFilters) as Array)\n .filter((key) => Boolean(includeFilters[key]));\n } else {\n const {\n excludedChatIds,\n ...excludeFilters\n } = selectTemp\n ? state.excludeFilters || {}\n : pick(\n state.folder,\n EXCLUDE_FILTER_FIELDS,\n );\n\n selectedChatIds = excludedChatIds || [];\n selectedChatTypes = (Object.keys(excludeFilters) as Array)\n .filter((key) => Boolean(excludeFilters[key]));\n }\n\n return {\n selectedChatIds,\n selectedChatTypes,\n };\n}\n\nfunction getSuggestedFolderName(includeFilters?: FolderIncludeFilters) {\n if (includeFilters) {\n const {\n includedChatIds,\n ...filters\n } = includeFilters;\n\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (includedChatIds && includedChatIds.length)\n ) {\n return '';\n }\n\n if (filters.bots) {\n return 'Bots';\n } else if (filters.groups) {\n return 'Groups';\n } else if (filters.channels) {\n return 'Channels';\n } else if (filters.contacts) {\n return 'Contacts';\n } else if (filters.nonContacts) {\n return 'Non-Contacts';\n }\n }\n\n return '';\n}\n\ntype FolderIncludeFilters = Pick;\ntype FolderExcludeFilters = Pick;\n\nexport type FoldersState = {\n mode: 'create' | 'edit';\n isLoading?: boolean;\n isTouched?: boolean;\n error?: string;\n folderId?: number;\n chatFilter: string;\n folder: Omit;\n includeFilters?: FolderIncludeFilters;\n excludeFilters?: FolderExcludeFilters;\n};\nexport type FoldersActions = (\n 'setTitle' | 'saveFilters' | 'editFolder' | 'reset' | 'setChatFilter' | 'setIsLoading' | 'setError' |\n 'editIncludeFilters' | 'editExcludeFilters' | 'setIncludeFilters' | 'setExcludeFilters'\n);\nexport type FolderEditDispatch = Dispatch;\n\nconst INITIAL_STATE: FoldersState = {\n mode: 'create',\n chatFilter: '',\n folder: {\n title: '',\n includedChatIds: [],\n excludedChatIds: [],\n },\n};\n\nconst foldersReducer: StateReducer = (\n state,\n action,\n) => {\n switch (action.type) {\n case 'setTitle':\n return {\n ...state,\n folder: {\n ...state.folder,\n title: action.payload,\n },\n isTouched: true,\n };\n case 'editIncludeFilters':\n return {\n ...state,\n includeFilters: pick(\n state.folder,\n INCLUDE_FILTER_FIELDS,\n ),\n };\n case 'editExcludeFilters':\n return {\n ...state,\n excludeFilters: pick(\n state.folder,\n EXCLUDE_FILTER_FIELDS,\n ),\n };\n case 'setIncludeFilters':\n return {\n ...state,\n includeFilters: action.payload,\n chatFilter: '',\n };\n case 'setExcludeFilters':\n return {\n ...state,\n excludeFilters: action.payload,\n chatFilter: '',\n };\n case 'saveFilters':\n if (state.includeFilters) {\n return {\n ...state,\n folder: {\n ...omit(state.folder, INCLUDE_FILTER_FIELDS),\n title: state.folder.title ? state.folder.title : getSuggestedFolderName(state.includeFilters),\n ...state.includeFilters,\n },\n includeFilters: undefined,\n chatFilter: '',\n isTouched: true,\n };\n } else if (state.excludeFilters) {\n return {\n ...state,\n folder: {\n ...omit(state.folder, EXCLUDE_FILTER_FIELDS),\n ...state.excludeFilters,\n },\n excludeFilters: undefined,\n chatFilter: '',\n isTouched: true,\n };\n } else {\n return state;\n }\n case 'editFolder': {\n const { id: folderId, description, ...folder } = action.payload;\n\n return {\n mode: 'edit',\n folderId,\n folder,\n chatFilter: '',\n };\n }\n case 'setChatFilter': {\n return {\n ...state,\n chatFilter: action.payload,\n };\n }\n case 'setIsLoading': {\n return {\n ...state,\n isLoading: action.payload,\n };\n }\n case 'setError': {\n return {\n ...state,\n error: action.payload,\n };\n }\n case 'reset':\n return INITIAL_STATE;\n default:\n return state;\n }\n};\n\nexport default () => {\n return useReducer(foldersReducer, INITIAL_STATE);\n};\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\n\nexport type TwoFaActions = (\n 'setCurrentPassword' | 'setPassword' | 'setHint' | 'setEmail' | 'reset'\n);\nexport type TwoFaDispatch = Dispatch;\n\nexport type TwoFaState = {\n currentPassword: string;\n password: string;\n hint: string;\n email: string;\n};\n\nconst INITIAL_STATE: TwoFaState = {\n currentPassword: '',\n password: '',\n hint: '',\n email: '',\n};\n\nconst twoFaReducer: StateReducer = (\n state,\n action,\n) => {\n switch (action.type) {\n case 'setCurrentPassword':\n return {\n ...state,\n currentPassword: action.payload,\n };\n\n case 'setPassword':\n return {\n ...state,\n password: action.payload,\n };\n\n case 'setHint':\n return {\n ...state,\n hint: action.payload,\n };\n\n case 'setEmail':\n return {\n ...state,\n email: action.payload,\n };\n\n case 'reset':\n return INITIAL_STATE;\n\n default:\n return state;\n }\n};\n\nexport default () => {\n return useReducer(twoFaReducer, INITIAL_STATE);\n};\n","import React, {\n FC, useCallback, useMemo, memo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype OwnProps = {\n currentScreen: SettingsScreens;\n editedFolderId?: number;\n onReset: () => void;\n onSaveFilter: () => void;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsHeader: FC = ({\n currentScreen,\n editedFolderId,\n onReset,\n onSaveFilter,\n signOut,\n deleteChatFolder,\n}) => {\n const [isSignOutDialogOpen, setIsSignOutDialogOpen] = useState(false);\n const [isDeleteFolderDialogOpen, setIsDeleteFolderDialogOpen] = useState(false);\n\n const openSignOutConfirmation = useCallback(() => {\n setIsSignOutDialogOpen(true);\n }, []);\n\n const closeSignOutConfirmation = useCallback(() => {\n setIsSignOutDialogOpen(false);\n }, []);\n\n const openDeleteFolderConfirmation = useCallback(() => {\n setIsDeleteFolderDialogOpen(true);\n }, []);\n\n const closeDeleteFolderConfirmation = useCallback(() => {\n setIsDeleteFolderDialogOpen(false);\n }, []);\n\n const handleSignOutMessage = useCallback(() => {\n closeSignOutConfirmation();\n signOut();\n }, [closeSignOutConfirmation, signOut]);\n\n const handleDeleteFolderMessage = useCallback(() => {\n closeDeleteFolderConfirmation();\n deleteChatFolder({ id: editedFolderId });\n onReset();\n }, [editedFolderId, closeDeleteFolderConfirmation, deleteChatFolder, onReset]);\n\n const SettingsMenuButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n \n \n \n );\n }, []);\n\n const lang = useLang();\n\n function renderHeaderContent() {\n switch (currentScreen) {\n case SettingsScreens.EditProfile:\n return

{lang('lng_settings_information')}

;\n case SettingsScreens.General:\n return

{lang('General')}

;\n case SettingsScreens.Notifications:\n return

{lang('Notifications')}

;\n case SettingsScreens.Privacy:\n return

{lang('PrivacySettings')}

;\n case SettingsScreens.Language:\n return

{lang('Language')}

;\n\n case SettingsScreens.GeneralChatBackground:\n return

{lang('ChatBackground')}

;\n case SettingsScreens.GeneralChatBackgroundColor:\n return

{lang('SetColor')}

;\n\n case SettingsScreens.PrivacyPhoneNumber:\n return

{lang('PrivacyPhone')}

;\n case SettingsScreens.PrivacyLastSeen:\n return

{lang('PrivacyLastSeen')}

;\n case SettingsScreens.PrivacyProfilePhoto:\n return

{lang('Privacy.ProfilePhoto')}

;\n case SettingsScreens.PrivacyForwarding:\n return

{lang('PrivacyForwards')}

;\n case SettingsScreens.PrivacyGroupChats:\n return

{lang('AutodownloadGroupChats')}

;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return

{lang('AlwaysShareWith')}

;\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return

{lang('NeverShareWith')}

;\n\n case SettingsScreens.PrivacyActiveSessions:\n return

{lang('SessionsTitle')}

;\n case SettingsScreens.PrivacyBlockedUsers:\n return

{lang('BlockedUsers')}

;\n\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n return

{lang('TwoStepVerification')}

;\n case SettingsScreens.TwoFaNewPassword:\n case SettingsScreens.TwoFaChangePasswordNew:\n case SettingsScreens.TwoFaChangePasswordConfirm:\n return

{lang('EnterPassword')}

;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return

{lang('PleaseReEnterPassword')}

;\n case SettingsScreens.TwoFaNewPasswordHint:\n case SettingsScreens.TwoFaChangePasswordHint:\n return

{lang('PasswordHint')}

;\n case SettingsScreens.TwoFaNewPasswordEmail:\n case SettingsScreens.TwoFaRecoveryEmail:\n return

{lang('RecoveryEmailTitle')}

;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return

Recovery Email Code

;\n case SettingsScreens.TwoFaCongratulations:\n return

{lang('TwoStepVerificationPasswordSet')}

;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n return

{lang('PleaseEnterCurrentPassword')}

;\n\n case SettingsScreens.Folders:\n return

{lang('Filters')}

;\n case SettingsScreens.FoldersCreateFolder:\n return

{lang('FilterNew')}

;\n case SettingsScreens.FoldersEditFolder:\n return (\n
\n

{lang('FilterEdit')}

\n\n {editedFolderId && (\n \n \n Delete Folder\n \n \n )}\n
\n );\n case SettingsScreens.FoldersIncludedChats:\n case SettingsScreens.FoldersExcludedChats:\n return (\n
\n {currentScreen === SettingsScreens.FoldersIncludedChats ? (\n

{lang('FilterInclude')}

\n ) : (\n

{lang('FilterExclude')}

\n )}\n\n \n \n \n
\n );\n\n default:\n return (\n
\n

{lang('SETTINGS')}

\n\n \n {lang('LogOutTitle')}\n \n
\n );\n }\n }\n\n return (\n
\n \n \n \n {renderHeaderContent()}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['signOut', 'deleteChatFolder']),\n)(SettingsHeader));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { SettingsScreens } from '../../../types';\nimport { ApiUser } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { getUserFullName } from '../../../modules/helpers';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Avatar from '../../common/Avatar';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n currentUser?: ApiUser;\n};\n\nconst SettingsMain: FC = ({\n onScreenSelect,\n currentUser,\n}) => {\n const lang = useLang();\n\n return (\n
\n
\n {currentUser && (\n
\n \n

{getUserFullName(currentUser)}

\n

{formatPhoneNumberWithCode(currentUser.phoneNumber)}

\n
\n )}\n onScreenSelect(SettingsScreens.EditProfile)}\n >\n {lang('lng_settings_information')}\n \n onScreenSelect(SettingsScreens.Folders)}\n >\n {lang('Filters')}\n \n onScreenSelect(SettingsScreens.General)}\n >\n {lang('Telegram.GeneralSettingsViewController')}\n \n onScreenSelect(SettingsScreens.Notifications)}\n >\n {lang('Notifications')}\n \n onScreenSelect(SettingsScreens.Privacy)}\n >\n {lang('PrivacySettings')}\n \n onScreenSelect(SettingsScreens.Language)}\n >\n {lang('Language')}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentUserId } = global;\n\n return {\n currentUser: currentUserId ? selectUser(global, currentUserId) : undefined,\n };\n },\n)(SettingsMain));\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\nimport './FloatingActionButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n className?: string;\n color?: ButtonProps['color'];\n ariaLabel?: ButtonProps['ariaLabel'];\n disabled?: boolean;\n onClick: () => void;\n children: any;\n};\n\nconst FloatingActionButton: FC = ({\n isShown,\n className,\n color = 'primary',\n ariaLabel,\n disabled,\n onClick,\n children,\n}) => {\n const buttonClassName = buildClassName(\n 'FloatingActionButton',\n isShown && 'revealed',\n className,\n );\n\n return (\n \n {children}\n \n );\n};\n\nexport default FloatingActionButton;\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useCallback, memo, useEffect, useMemo,\n} from '../../lib/teact/teact';\n\nimport { debounce } from '../../util/schedulers';\nimport useLang from '../../hooks/useLang';\n\nimport InputText from '../ui/InputText';\n\ntype OwnProps = {\n currentUsername?: string;\n asLink?: boolean;\n isLoading?: boolean;\n isUsernameAvailable?: boolean;\n checkUsername: AnyToVoidFunction;\n onChange: (value: string | false) => void;\n};\n\nconst MIN_USERNAME_LENGTH = 5;\nconst MAX_USERNAME_LENGTH = 32;\nconst LINK_PREFIX = 'https://t.me/';\nconst LINK_PREFIX_REGEX = /https:\\/\\/t\\.me\\/?/i;\nconst USERNAME_REGEX = /^([a-zA-Z0-9_]+)$/;\n\nconst runDebouncedForCheckUsername = debounce((cb) => cb(), 250, false);\n\nfunction isUsernameValid(username: string) {\n return username.length >= MIN_USERNAME_LENGTH\n && username.length <= MAX_USERNAME_LENGTH\n && USERNAME_REGEX.test(username);\n}\n\nconst SettingsEditProfile: FC = ({\n currentUsername,\n asLink,\n isLoading,\n isUsernameAvailable,\n checkUsername,\n onChange,\n}) => {\n const [username, setUsername] = useState(currentUsername || '');\n\n const lang = useLang();\n const langPrefix = asLink ? 'SetUrl' : 'Username';\n const label = asLink ? lang('SetUrlPlaceholder') : lang('Username');\n\n const [usernameSuccess, usernameError] = useMemo(() => {\n if (!username.length) {\n return [];\n }\n\n if (username.length < MIN_USERNAME_LENGTH) {\n return [undefined, `${label} is too short`];\n }\n if (username.length > MAX_USERNAME_LENGTH) {\n return [undefined, `${label} is too long`];\n }\n if (!USERNAME_REGEX.test(username)) {\n return [undefined, `${label} contains invalid characters`];\n }\n\n if (isUsernameAvailable === undefined) {\n return [];\n }\n\n // Variable `isUsernameAvailable` is initialized with `undefined`, so a strict false check is required\n return [\n isUsernameAvailable ? lang(`${langPrefix}Available`, 'Username') : undefined,\n isUsernameAvailable === false ? lang(`${langPrefix}InUse`) : undefined,\n ];\n }, [username, isUsernameAvailable, lang, langPrefix, label]);\n\n useEffect(() => {\n setUsername(currentUsername || '');\n }, [asLink, currentUsername]);\n\n const handleUsernameChange = useCallback((e: ChangeEvent) => {\n const newUsername = e.target.value.trim().replace(LINK_PREFIX_REGEX, '');\n setUsername(newUsername);\n e.target.value = `${asLink ? LINK_PREFIX : ''}${newUsername}`;\n\n const isValid = isUsernameValid(newUsername);\n\n if (isValid) {\n runDebouncedForCheckUsername(() => {\n checkUsername({ username: newUsername });\n });\n }\n\n if (onChange) {\n onChange(isValid ? newUsername : false);\n }\n }, [asLink, checkUsername, onChange]);\n\n return (\n \n );\n};\n\nexport default memo(SettingsEditProfile);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useCallback, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { ProfileEditProgress } from '../../../types';\n\nimport { throttle } from '../../../util/schedulers';\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\nimport { getChatAvatarHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport InputText from '../../ui/InputText';\nimport renderText from '../../common/helpers/renderText';\nimport UsernameInput from '../../common/UsernameInput';\n\ntype StateProps = {\n currentAvatarHash?: string;\n currentFirstName?: string;\n currentLastName?: string;\n currentBio?: string;\n currentUsername?: string;\n progress?: ProfileEditProgress;\n isUsernameAvailable?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst MAX_BIO_LENGTH = 70;\n\nconst ERROR_FIRST_NAME_MISSING = 'Please provide your first name';\nconst ERROR_BIO_TOO_LONG = 'Bio can\\' be longer than 70 characters';\n\nconst SettingsEditProfile: FC = ({\n currentAvatarHash,\n currentFirstName,\n currentLastName,\n currentBio,\n currentUsername,\n progress,\n isUsernameAvailable,\n loadCurrentUser,\n updateProfile,\n checkUsername,\n}) => {\n const [isUsernameTouched, setIsUsernameTouched] = useState(false);\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [error, setError] = useState();\n\n const [photo, setPhoto] = useState();\n const [firstName, setFirstName] = useState(currentFirstName || '');\n const [lastName, setLastName] = useState(currentLastName || '');\n const [bio, setBio] = useState(currentBio || '');\n const [username, setUsername] = useState(currentUsername || '');\n\n const currentAvatarBlobUrl = useMedia(currentAvatarHash, false, ApiMediaFormat.BlobUrl);\n\n const isLoading = progress === ProfileEditProgress.InProgress;\n const isUsernameError = username === false;\n\n const isSaveButtonShown = useMemo(() => {\n if (isUsernameError) {\n return false;\n }\n\n return Boolean(photo) || isProfileFieldsTouched || isUsernameAvailable === true;\n }, [photo, isProfileFieldsTouched, isUsernameError, isUsernameAvailable]);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadCurrentUser();\n });\n }, [loadCurrentUser]);\n\n useEffect(() => {\n setPhoto(undefined);\n }, [currentAvatarBlobUrl]);\n\n useEffect(() => {\n setFirstName(currentFirstName || '');\n setLastName(currentLastName || '');\n setBio(currentBio || '');\n }, [currentFirstName, currentLastName, currentBio]);\n\n useEffect(() => {\n setUsername(currentUsername || '');\n }, [currentUsername]);\n\n useEffect(() => {\n if (progress === ProfileEditProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setIsUsernameTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const handlePhotoChange = useCallback((newPhoto: File) => {\n setPhoto(newPhoto);\n }, []);\n\n const handleFirstNameChange = useCallback((e: ChangeEvent) => {\n setFirstName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleLastNameChange = useCallback((e: ChangeEvent) => {\n setLastName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleBioChange = useCallback((e: ChangeEvent) => {\n setBio(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUsernameChange = useCallback((value: string | false) => {\n setUsername(value);\n setIsUsernameTouched(true);\n }, []);\n\n const handleProfileSave = useCallback(() => {\n const trimmedFirstName = firstName.trim();\n const trimmedLastName = lastName.trim();\n const trimmedBio = bio.trim();\n\n if (!trimmedFirstName.length) {\n setError(ERROR_FIRST_NAME_MISSING);\n return;\n }\n\n if (trimmedBio.length > MAX_BIO_LENGTH) {\n setError(ERROR_BIO_TOO_LONG);\n return;\n }\n\n updateProfile({\n photo,\n ...(isProfileFieldsTouched && {\n firstName: trimmedFirstName,\n lastName: trimmedLastName,\n bio: trimmedBio,\n }),\n ...(isUsernameTouched && {\n username,\n }),\n });\n }, [\n photo,\n firstName, lastName, bio, isProfileFieldsTouched,\n username, isUsernameTouched,\n updateProfile,\n ]);\n\n const lang = useLang();\n\n return (\n
\n
\n
\n \n \n \n \n\n

\n {renderText(lang('lng_settings_about_bio'), ['br', 'simple_markdown'])}\n

\n
\n\n
\n

{lang('Username')}

\n\n \n\n

\n {renderText(lang('UsernameHelp'), ['br', 'simple_markdown'])}\n

\n {username && (\n

\n {lang('lng_username_link')}
\n https://t.me/{username}\n

\n )}\n
\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { currentUserId } = global;\n const { progress, isUsernameAvailable } = global.profileEdit || {};\n const currentUser = currentUserId ? selectUser(global, currentUserId) : undefined;\n\n if (!currentUser) {\n return {\n progress,\n isUsernameAvailable,\n };\n }\n\n const {\n firstName: currentFirstName,\n lastName: currentLastName,\n username: currentUsername,\n fullInfo,\n } = currentUser;\n const { bio: currentBio } = fullInfo || {};\n const currentAvatarHash = getChatAvatarHash(currentUser);\n\n return {\n currentAvatarHash,\n currentFirstName,\n currentLastName,\n currentBio,\n currentUsername,\n progress,\n isUsernameAvailable,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadCurrentUser',\n 'updateProfile',\n 'checkUsername',\n ]),\n)(SettingsEditProfile));\n","import React, {\n FC, memo, useMemo, useCallback, useState, useEffect,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\nimport { ApiChatFolder, ApiChat, ApiUser } from '../../../../api/types';\nimport { NotifyException, NotifySettings } from '../../../../types';\n\nimport { STICKER_SIZE_FOLDER_SETTINGS } from '../../../../config';\nimport { pick } from '../../../../util/iteratees';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../../modules/selectors';\nimport { throttle } from '../../../../util/schedulers';\nimport getAnimationData from '../../../common/helpers/animatedAssets';\nimport { getFolderDescriptionText } from '../../../../modules/helpers';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport Button from '../../../ui/Button';\nimport Loading from '../../../ui/Loading';\nimport AnimatedSticker from '../../../common/AnimatedSticker';\n\ntype OwnProps = {\n onCreateFolder: () => void;\n onEditFolder: (folder: ApiChatFolder) => void;\n};\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n orderedFolderIds?: number[];\n foldersById: Record;\n recommendedChatFolders?: ApiChatFolder[];\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottledForLoadRecommended = throttle((cb) => cb(), 60000, true);\n\nconst MAX_ALLOWED_FOLDERS = 10;\n\nconst SettingsFoldersMain: FC = ({\n onCreateFolder,\n onEditFolder,\n chatsById,\n usersById,\n orderedFolderIds,\n foldersById,\n recommendedChatFolders,\n notifySettings,\n notifyExceptions,\n loadRecommendedChatFolders,\n addChatFolder,\n showError,\n}) => {\n const [animationData, setAnimationData] = useState>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('FoldersAll').then(setAnimationData);\n }\n }, [animationData]);\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottledForLoadRecommended(() => {\n loadRecommendedChatFolders();\n });\n }, [loadRecommendedChatFolders]);\n\n const handleCreateFolder = useCallback(() => {\n if (Object.keys(foldersById).length >= MAX_ALLOWED_FOLDERS) {\n showError({\n error: {\n message: 'DIALOG_FILTERS_TOO_MUCH',\n },\n });\n\n return;\n }\n\n onCreateFolder();\n }, [foldersById, showError, onCreateFolder]);\n\n const lang = useLang();\n\n const userFolders = useMemo(() => {\n if (!orderedFolderIds) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n\n return orderedFolderIds.map((id) => {\n const folder = foldersById[id];\n\n return {\n id: folder.id,\n title: folder.title,\n subtitle: getFolderDescriptionText(\n lang, chatsById, usersById, folder, chatIds, notifySettings, notifyExceptions,\n ),\n };\n });\n }, [orderedFolderIds, chatsById, foldersById, usersById, notifySettings, notifyExceptions, lang]);\n\n const handleCreateFolderFromRecommended = useCallback((folder: ApiChatFolder) => {\n if (Object.keys(foldersById).length >= MAX_ALLOWED_FOLDERS) {\n showError({\n error: {\n message: 'DIALOG_FILTERS_TOO_MUCH',\n },\n });\n\n return;\n }\n\n addChatFolder({ folder });\n }, [foldersById, addChatFolder, showError]);\n\n return (\n
\n
\n
\n {animationData && (\n \n )}\n
\n\n

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

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

{lang('Filters')}

\n\n {userFolders && userFolders.length ? userFolders.map((folder) => (\n onEditFolder(foldersById[folder.id])}\n >\n {folder.title}\n {folder.subtitle}\n \n )) : userFolders && !userFolders.length ? (\n

\n You have no folders yet.\n

\n ) : }\n
\n\n {(recommendedChatFolders && !!recommendedChatFolders.length) && (\n
\n

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

\n\n {recommendedChatFolders.map((folder) => (\n handleCreateFolderFromRecommended(folder)}\n >\n
\n
\n {folder.title}\n {folder.description}\n
\n\n \n {lang('Add')}\n \n
\n \n ))}\n
\n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n } = global;\n\n const {\n orderedIds: orderedFolderIds,\n byId: foldersById,\n recommended: recommendedChatFolders,\n } = global.chatFolders;\n\n return {\n chatsById,\n usersById,\n orderedFolderIds,\n foldersById,\n recommendedChatFolders,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadRecommendedChatFolders', 'addChatFolder', 'showError']),\n)(SettingsFoldersMain));\n","import React, { FC } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\n\nimport './ShowMoreButton.scss';\n\ntype OwnProps = {\n count: number;\n itemName: string;\n itemPluralName?: string;\n isLoading?: boolean;\n onClick: () => void;\n};\n\nconst ShowMoreButton: FC = ({\n count,\n itemName,\n itemPluralName,\n isLoading,\n onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n \n Show {count} more {count > 1 ? itemPluralName || `${itemName}s` : itemName}\n \n );\n};\n\nexport default ShowMoreButton;\n","import React, {\n FC, memo, useCallback, useState, useEffect, useMemo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\n\nimport { STICKER_SIZE_FOLDER_SETTINGS } from '../../../../config';\nimport { pick, findIntersectionWithSet } from '../../../../util/iteratees';\nimport { isChatPrivate } from '../../../../modules/helpers';\nimport getAnimationData from '../../../common/helpers/animatedAssets';\nimport {\n FoldersState,\n FolderEditDispatch,\n INCLUDED_CHAT_TYPES,\n EXCLUDED_CHAT_TYPES,\n selectChatFilters,\n} from '../../../../hooks/reducers/useFoldersReducer';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport AnimatedSticker from '../../../common/AnimatedSticker';\nimport InputText from '../../../ui/InputText';\nimport PrivateChatInfo from '../../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../../common/GroupChatInfo';\nimport FloatingActionButton from '../../../ui/FloatingActionButton';\nimport Spinner from '../../../ui/Spinner';\nimport ShowMoreButton from '../../../ui/ShowMoreButton';\n\ntype OwnProps = {\n state: FoldersState;\n dispatch: FolderEditDispatch;\n onAddIncludedChats: () => void;\n onAddExcludedChats: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n loadedActiveChatIds?: number[];\n loadedArchivedChatIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SUBMIT_TIMEOUT = 500;\n\nconst INITIAL_CHATS_LIMIT = 5;\n\nconst ERROR_NO_TITLE = 'Please provide a title for this folder.';\nconst ERROR_NO_CHATS = 'Please select at least one chat for this folder.';\n\nconst SettingsFoldersEdit: FC = ({\n state,\n dispatch,\n onAddIncludedChats,\n onAddExcludedChats,\n onReset,\n loadedActiveChatIds,\n loadedArchivedChatIds,\n editChatFolder,\n addChatFolder,\n loadMoreChats,\n}) => {\n const [animationData, setAnimationData] = useState>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n\n const [isIncludedChatsListExpanded, setIsIncludedChatsListExpanded] = useState(false);\n const [isExcludedChatsListExpanded, setIsExcludedChatsListExpanded] = useState(false);\n\n const {\n selectedChatIds: includedChatIds,\n selectedChatTypes: includedChatTypes,\n } = selectChatFilters(state, 'included');\n const {\n selectedChatIds: excludedChatIds,\n selectedChatTypes: excludedChatTypes,\n } = selectChatFilters(state, 'excluded');\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('FoldersNew').then(setAnimationData);\n }\n }, [animationData]);\n\n useEffect(() => {\n setIsIncludedChatsListExpanded(false);\n setIsExcludedChatsListExpanded(false);\n }, [state.folderId]);\n\n const [visibleIncludedChatIds, visibleExcludedChatIds] = useMemo(() => {\n const allLoadedChatsSet = new Set([\n ...loadedActiveChatIds || [],\n ...loadedArchivedChatIds || [],\n ]);\n\n const loadedIncludedChatIds = findIntersectionWithSet(includedChatIds, allLoadedChatsSet);\n const loadedExcludedChatIds = findIntersectionWithSet(excludedChatIds, allLoadedChatsSet);\n\n return [\n isIncludedChatsListExpanded\n ? loadedIncludedChatIds\n : loadedIncludedChatIds.slice(0, INITIAL_CHATS_LIMIT - includedChatTypes.length),\n isExcludedChatsListExpanded\n ? loadedExcludedChatIds\n : loadedExcludedChatIds.slice(0, INITIAL_CHATS_LIMIT - excludedChatTypes.length),\n ];\n }, [\n excludedChatIds, includedChatIds, includedChatTypes, excludedChatTypes,\n isExcludedChatsListExpanded, isIncludedChatsListExpanded,\n loadedActiveChatIds, loadedArchivedChatIds,\n ]);\n\n useEffect(() => {\n if (\n visibleIncludedChatIds.length < includedChatIds.length\n || visibleExcludedChatIds.length < excludedChatIds.length\n ) {\n loadMoreChats({ listType: 'active' });\n }\n }, [\n loadMoreChats,\n excludedChatIds.length,\n includedChatIds.length,\n visibleExcludedChatIds.length,\n visibleIncludedChatIds.length,\n ]);\n\n const lang = useLang();\n\n function handleChange(event: React.ChangeEvent) {\n const { currentTarget } = event;\n dispatch({ type: 'setTitle', payload: currentTarget.value.trim() });\n }\n\n function handleSubmit() {\n const { title } = state.folder;\n\n if (!title) {\n dispatch({ type: 'setError', payload: ERROR_NO_TITLE });\n return;\n }\n\n if (!includedChatIds.length && !Object.keys(includedChatTypes).length) {\n dispatch({ type: 'setError', payload: ERROR_NO_CHATS });\n return;\n }\n\n dispatch({ type: 'setIsLoading', payload: true });\n if (state.mode === 'edit') {\n editChatFolder({ id: state.folderId, folderUpdate: state.folder });\n } else {\n addChatFolder({ folder: state.folder });\n }\n\n setTimeout(() => {\n onReset();\n }, SUBMIT_TIMEOUT);\n }\n\n function renderChatType(key: string, mode: 'included' | 'excluded') {\n const chatType = mode === 'included'\n ? INCLUDED_CHAT_TYPES.find(({ key: typeKey }) => typeKey === key)\n : EXCLUDED_CHAT_TYPES.find(({ key: typeKey }) => typeKey === key);\n\n if (!chatType) {\n return undefined;\n }\n\n return (\n \n {lang(chatType.title)}\n \n );\n }\n\n function renderChats(mode: 'included' | 'excluded') {\n const selectedChatTypes = mode === 'included' ? includedChatTypes : excludedChatTypes;\n const visibleChatIds = mode === 'included' ? visibleIncludedChatIds : visibleExcludedChatIds;\n\n const isExpanded = mode === 'included' ? isIncludedChatsListExpanded : isExcludedChatsListExpanded;\n const allChatIds = mode === 'included' ? includedChatIds : excludedChatIds;\n const leftChatsCount = allChatIds.length - selectedChatTypes.length - visibleChatIds.length;\n const clickHandler = mode === 'included'\n ? () => setIsIncludedChatsListExpanded(true)\n : () => setIsExcludedChatsListExpanded(true);\n\n return (\n <>\n {selectedChatTypes.map((key) => renderChatType(key, mode))}\n {visibleChatIds.map((id) => (\n \n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n ))}\n {(!isExpanded && leftChatsCount > 0) && (\n \n )}\n \n );\n }\n\n return (\n
\n
\n
\n
\n {animationData && (\n \n )}\n
\n\n {state.mode === 'create' && (\n

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

\n )}\n\n \n
\n\n
\n {state.error && state.error === ERROR_NO_CHATS && (\n

\n {state.error}\n

\n )}\n\n

{lang('FilterInclude')}

\n\n \n {lang('FilterAddChats')}\n \n\n {renderChats('included')}\n
\n\n
\n

{lang('FilterExclude')}

\n\n \n {lang('FilterAddChats')}\n \n\n {renderChats('excluded')}\n
\n
\n\n \n {state.isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { listIds } = global.chats;\n\n return {\n loadedActiveChatIds: listIds.active,\n loadedArchivedChatIds: listIds.archived,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['editChatFolder', 'addChatFolder', 'loadMoreChats']),\n)(SettingsFoldersEdit));\n","import React, {\n FC, useCallback, useRef, useEffect, memo,\n} from '../../../../lib/teact/teact';\n\nimport { isChatPrivate } from '../../../../modules/helpers';\nimport {\n INCLUDED_CHAT_TYPES,\n EXCLUDED_CHAT_TYPES,\n FolderChatType,\n} from '../../../../hooks/reducers/useFoldersReducer';\nimport useInfiniteScroll from '../../../../hooks/useInfiniteScroll';\nimport useLang from '../../../../hooks/useLang';\n\nimport Checkbox from '../../../ui/Checkbox';\nimport InputText from '../../../ui/InputText';\nimport ListItem from '../../../ui/ListItem';\nimport PrivateChatInfo from '../../../common/PrivateChatInfo';\nimport GroupChatInfo from '../../../common/GroupChatInfo';\nimport PickerSelectedItem from '../../../common/PickerSelectedItem';\nimport InfiniteScroll from '../../../ui/InfiniteScroll';\nimport Loading from '../../../ui/Loading';\n\nimport '../../../common/Picker.scss';\nimport './SettingsFoldersChatsPicker.scss';\n\ntype OwnProps = {\n mode: 'included' | 'excluded';\n chatIds: number[];\n selectedIds: number[];\n selectedChatTypes: string[];\n filterValue?: string;\n onSelectedIdsChange: (ids: number[]) => void;\n onSelectedChatTypesChange: (types: string[]) => void;\n onFilterChange: (value: string) => void;\n onLoadMore: () => void;\n};\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\n\nconst MAX_CHATS = 100;\nconst MAX_FULL_ITEMS = 10;\nconst ALWAYS_FULL_ITEMS_COUNT = 5;\n\nconst SettingsFoldersChatsPicker: FC = ({\n mode,\n chatIds,\n selectedIds,\n selectedChatTypes,\n filterValue,\n onSelectedIdsChange,\n onSelectedChatTypesChange,\n onFilterChange,\n onLoadMore,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const chatTypes = mode === 'included' ? INCLUDED_CHAT_TYPES : EXCLUDED_CHAT_TYPES;\n const shouldMinimize = selectedIds.length + selectedChatTypes.length > MAX_FULL_ITEMS;\n const hasMaxChats = selectedIds.length >= MAX_CHATS;\n\n useEffect(() => {\n setTimeout(() => {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n });\n }, FOCUS_DELAY_MS);\n }, []);\n\n const handleItemClick = useCallback((id: number) => {\n const newSelectedIds = [...selectedIds];\n if (newSelectedIds.includes(id)) {\n newSelectedIds.splice(newSelectedIds.indexOf(id), 1);\n } else {\n newSelectedIds.push(id);\n }\n onSelectedIdsChange(newSelectedIds);\n }, [selectedIds, onSelectedIdsChange]);\n\n const handleChatTypeClick = useCallback((key: FolderChatType['key']) => {\n const newSelectedChatTypes = [...selectedChatTypes];\n if (newSelectedChatTypes.includes(key)) {\n newSelectedChatTypes.splice(newSelectedChatTypes.indexOf(key), 1);\n } else {\n newSelectedChatTypes.push(key);\n }\n onSelectedChatTypesChange(newSelectedChatTypes);\n }, [selectedChatTypes, onSelectedChatTypesChange]);\n\n const handleFilterChange = useCallback((e: React.ChangeEvent) => {\n const { value } = e.currentTarget;\n onFilterChange(value);\n }, [onFilterChange]);\n\n const lang = useLang();\n\n function renderSelectedChatType(key: string) {\n const selectedType = chatTypes.find(({ key: typeKey }) => key === typeKey);\n if (!selectedType) {\n return undefined;\n }\n\n return (\n \n );\n }\n\n function renderChatType(type: FolderChatType) {\n return (\n handleChatTypeClick(type.key)}\n ripple\n >\n \n

{lang(type.title)}

\n \n \n );\n }\n\n function renderItem(id: number) {\n const isSelected = selectedIds.includes(id);\n\n return (\n handleItemClick(id)}\n ripple\n disabled={!isSelected && hasMaxChats}\n >\n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n \n );\n }\n\n const [viewportIds, getMore] = useInfiniteScroll(onLoadMore, chatIds, Boolean(filterValue));\n\n return (\n
\n
\n {selectedChatTypes.map(renderSelectedChatType)}\n {selectedIds.map((id, i) => (\n \n ))}\n {!hasMaxChats ? (\n \n ) : (\n

\n {`Sorry, you can't add more than ${MAX_CHATS} chats.`}\n

\n )}\n
\n \n {(!viewportIds || !viewportIds.length || viewportIds.includes(chatIds[0])) && (\n <>\n

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

\n {chatTypes.map(renderChatType)}\n
\n

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

\n \n )}\n\n {viewportIds && viewportIds.length ? (\n viewportIds.map(renderItem)\n ) : viewportIds && !viewportIds.length ? (\n

Sorry, nothing found.

\n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(SettingsFoldersChatsPicker);\n","import React, {\n FC, memo, useMemo, useCallback,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../../global/types';\nimport { ApiChat } from '../../../../api/types';\n\nimport useLang from '../../../../hooks/useLang';\nimport { pick } from '../../../../util/iteratees';\nimport searchWords from '../../../../util/searchWords';\nimport { prepareChatList, getChatTitle } from '../../../../modules/helpers';\nimport {\n FoldersState,\n FolderEditDispatch,\n selectChatFilters,\n} from '../../../../hooks/reducers/useFoldersReducer';\n\nimport SettingsFoldersChatsPicker from './SettingsFoldersChatsPicker';\n\nimport Loading from '../../../ui/Loading';\n\ntype OwnProps = {\n mode: 'included' | 'excluded';\n state: FoldersState;\n dispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n chatsById: Record;\n listIds?: number[];\n orderedPinnedIds?: number[];\n archivedListIds?: number[];\n archivedPinnedIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsFoldersChatFilters: FC = ({\n mode,\n state,\n dispatch,\n chatsById,\n listIds,\n orderedPinnedIds,\n archivedListIds,\n archivedPinnedIds,\n loadMoreChats,\n}) => {\n const { chatFilter } = state;\n const { selectedChatIds, selectedChatTypes } = selectChatFilters(state, mode, true);\n\n const lang = useLang();\n const chats = useMemo(() => {\n const activeChatArrays = listIds\n ? prepareChatList(chatsById, listIds, orderedPinnedIds, 'all')\n : undefined;\n const archivedChatArrays = archivedListIds\n ? prepareChatList(chatsById, archivedListIds, archivedPinnedIds, 'archived')\n : undefined;\n\n if (!activeChatArrays && !archivedChatArrays) {\n return undefined;\n }\n\n return [\n ...(activeChatArrays\n ? [...activeChatArrays.pinnedChats, ...activeChatArrays.otherChats]\n : []\n ),\n ...(archivedChatArrays ? archivedChatArrays.otherChats : []),\n ];\n }, [chatsById, listIds, orderedPinnedIds, archivedListIds, archivedPinnedIds]);\n\n const displayedIds = useMemo(() => {\n if (!chats) {\n return undefined;\n }\n\n return chats\n .filter((chat) => (\n !chatFilter\n || searchWords(getChatTitle(lang, chat), chatFilter)\n || selectedChatIds.includes(chat.id)\n ))\n .map(({ id }) => id);\n }, [chats, chatFilter, lang, selectedChatIds]);\n\n const handleFilterChange = useCallback((newFilter: string) => {\n dispatch({\n type: 'setChatFilter',\n payload: newFilter,\n });\n }, [dispatch]);\n\n const handleSelectedIdsChange = useCallback((ids: number[]) => {\n if (mode === 'included') {\n dispatch({\n type: 'setIncludeFilters',\n payload: { ...state.includeFilters, includedChatIds: ids },\n });\n } else {\n dispatch({\n type: 'setExcludeFilters',\n payload: { ...state.excludeFilters, excludedChatIds: ids },\n });\n }\n }, [mode, state, dispatch]);\n\n const handleSelectedChatTypesChange = useCallback((keys: string[]) => {\n const newFilters: Record = {};\n keys.forEach((key) => {\n newFilters[key] = true;\n });\n\n if (mode === 'included') {\n dispatch({\n type: 'setIncludeFilters',\n payload: {\n includedChatIds: selectedChatIds,\n ...newFilters,\n },\n });\n } else {\n dispatch({\n type: 'setExcludeFilters',\n payload: {\n excludedChatIds: selectedChatIds,\n ...newFilters,\n },\n });\n }\n }, [mode, selectedChatIds, dispatch]);\n\n if (!displayedIds) {\n return ;\n }\n\n return (\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n orderedPinnedIds,\n },\n } = global;\n\n return {\n chatsById,\n listIds: listIds.active,\n orderedPinnedIds: orderedPinnedIds.active,\n archivedPinnedIds: orderedPinnedIds.archived,\n archivedListIds: listIds.archived,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMoreChats']),\n)(SettingsFoldersChatFilters));\n","import React, { FC, memo, useCallback } from '../../../../lib/teact/teact';\n\nimport { ApiChatFolder } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { FoldersState, FolderEditDispatch } from '../../../../hooks/reducers/useFoldersReducer';\n\nimport SettingsFoldersMain from './SettingsFoldersMain';\nimport SettingsFoldersEdit from './SettingsFoldersEdit';\nimport SettingsFoldersChatFilters from './SettingsFoldersChatFilters';\n\nimport './SettingsFolders.scss';\n\nconst TRANSITION_DURATION = 200;\n\nexport type OwnProps = {\n currentScreen: SettingsScreens;\n state: FoldersState;\n dispatch: FolderEditDispatch;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\nconst SettingsFolders: FC = ({\n currentScreen,\n state,\n dispatch,\n onScreenSelect,\n onReset,\n}) => {\n const handleReset = useCallback(() => {\n if (\n currentScreen === SettingsScreens.FoldersCreateFolder\n || currentScreen === SettingsScreens.FoldersEditFolder\n ) {\n setTimeout(() => {\n dispatch({ type: 'reset' });\n }, TRANSITION_DURATION);\n }\n\n if (\n currentScreen === SettingsScreens.FoldersIncludedChats\n || currentScreen === SettingsScreens.FoldersExcludedChats\n ) {\n if (state.mode === 'create') {\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n } else {\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }\n return;\n }\n\n onReset();\n }, [\n state.mode, dispatch,\n currentScreen, onReset, onScreenSelect,\n ]);\n\n const handleCreateFolder = useCallback(() => {\n dispatch({ type: 'reset' });\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n }, [onScreenSelect, dispatch]);\n\n const handleEditFolder = useCallback((folder: ApiChatFolder) => {\n dispatch({ type: 'editFolder', payload: folder });\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }, [dispatch, onScreenSelect]);\n\n const handleAddIncludedChats = useCallback(() => {\n dispatch({ type: 'editIncludeFilters' });\n onScreenSelect(SettingsScreens.FoldersIncludedChats);\n }, [dispatch, onScreenSelect]);\n\n const handleAddExcludedChats = useCallback(() => {\n dispatch({ type: 'editExcludeFilters' });\n onScreenSelect(SettingsScreens.FoldersExcludedChats);\n }, [dispatch, onScreenSelect]);\n\n switch (currentScreen) {\n case SettingsScreens.Folders:\n return (\n \n );\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n return (\n \n );\n case SettingsScreens.FoldersIncludedChats:\n return (\n \n );\n case SettingsScreens.FoldersExcludedChats:\n return (\n \n );\n\n default:\n return undefined;\n }\n};\n\nexport default memo(SettingsFolders);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, useMemo, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './RangeSlider.scss';\n\ntype OwnProps = {\n options?: string[];\n range?: { min: number; max: number; step?: number };\n label?: string;\n value: number;\n disabled?: boolean;\n onChange: (value: number) => void;\n};\n\nconst RangeSlider: FC = ({\n options,\n range,\n label,\n value,\n disabled,\n onChange,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n onChange(Number(event.currentTarget.value));\n }, [onChange]);\n\n const className = buildClassName(\n 'RangeSlider',\n disabled && 'disabled',\n );\n\n const trackWidth = useMemo(() => {\n if (options) {\n return (value / (options.length - 1)) * 100;\n } else if (range) {\n const possibleValuesLength = (range.max - range.min) / (range.step || 1);\n return ((value - range.min) / possibleValuesLength) * 100;\n }\n return 0;\n }, [value, options, range]);\n\n const [min, max, step] = useMemo(() => {\n if (options) {\n return [0, options.length - 1, 1];\n } else if (range) {\n return [range.min, range.max, range.step || 1];\n }\n\n return [0, 0, 0];\n }, [range, options]);\n\n return (\n
\n {label && (\n
\n {label}\n {range && (\n {value}\n )}\n
\n )}\n
\n \n \n {options && (\n
\n {options.map((option, index) => (\n onChange(index)}\n >\n {option}\n
\n ))}\n
\n )}\n
\n
\n );\n};\n\nexport default memo(RangeSlider);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiStickerSet } from '../../../api/types';\n\nimport { STICKER_SIZE_PICKER_HEADER } from '../../../config';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport { getFirstLetters } from '../../../util/textFormat';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\n\ntype OwnProps = {\n size?: number;\n stickerSet: ApiStickerSet;\n observeIntersection: ObserveFn;\n};\n\nconst StickerSetCoverAnimated: FC = ({\n size = STICKER_SIZE_PICKER_HEADER,\n stickerSet,\n observeIntersection,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaHash = `stickerSet${stickerSet.id}`;\n const lottieData = useMedia(mediaHash, !isIntersecting, ApiMediaFormat.Lottie);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(lottieData, 'slow');\n\n return (\n
\n {!shouldRenderFullMedia && getFirstLetters(stickerSet.title, 2)}\n {shouldRenderFullMedia && lottieData && (\n \n )}\n
\n );\n};\n\nexport default memo(StickerSetCoverAnimated);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiStickerSet } from '../../../api/types';\n\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport { getFirstLetters } from '../../../util/textFormat';\n\ntype OwnProps = {\n stickerSet: ApiStickerSet;\n observeIntersection: ObserveFn;\n};\n\nconst StickerSetCover: FC = ({ stickerSet, observeIntersection }) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaData = useMedia(stickerSet.hasThumbnail && `stickerSet${stickerSet.id}`, !isIntersecting);\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\n\n return (\n
\n {!shouldRenderFullMedia && getFirstLetters(stickerSet.title, 2)}\n {shouldRenderFullMedia && (\n \"\"\n )}\n
\n );\n};\n\nexport default memo(StickerSetCover);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiSticker } from '../../api/types';\n\nimport { useIsIntersecting, ObserveFn } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useFlag from '../../hooks/useFlag';\nimport buildClassName from '../../util/buildClassName';\n\nimport AnimatedSticker from './AnimatedSticker';\nimport Button from '../ui/Button';\n\nimport './StickerButton.scss';\n\ntype OwnProps = {\n sticker: ApiSticker;\n size: number;\n observeIntersection: ObserveFn;\n noAnimate?: boolean;\n title?: string;\n className?: string;\n onClick?: (arg: any) => void;\n clickArg?: any;\n onUnfaveClick?: (sticker: ApiSticker) => void;\n};\n\nconst StickerButton: FC = ({\n sticker, size, observeIntersection, noAnimate, title, className, onClick, clickArg, onUnfaveClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const localMediaHash = `sticker${sticker.id}`;\n const stickerSelector = `sticker-button-${sticker.id}`;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const thumbDataUri = sticker.thumbnail ? sticker.thumbnail.dataUri : undefined;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !isIntersecting, ApiMediaFormat.BlobUrl);\n\n const shouldPlay = isIntersecting && !noAnimate;\n const lottieData = useMedia(sticker.isAnimated && localMediaHash, !shouldPlay, ApiMediaFormat.Lottie);\n const [isAnimationLoaded, markLoaded, unmarkLoaded] = useFlag(Boolean(lottieData));\n const canAnimatedPlay = isAnimationLoaded && shouldPlay;\n\n const {\n shouldRenderThumb,\n shouldRenderFullMedia: shouldRenderPreview,\n transitionClassNames: previewTransitionClassNames,\n } = useTransitionForMedia(previewBlobUrl || canAnimatedPlay, 'slow');\n\n // To avoid flickering\n useEffect(() => {\n if (!shouldPlay) {\n unmarkLoaded();\n }\n }, [unmarkLoaded, shouldPlay]);\n\n function handleClick() {\n if (onClick) {\n onClick(clickArg);\n }\n }\n\n function handleUnfaveClick(e: ReactMouseEvent) {\n e.stopPropagation();\n e.preventDefault();\n\n onUnfaveClick!(sticker);\n }\n\n const fullClassName = buildClassName(\n 'StickerButton',\n sticker.isAnimated && 'animated',\n stickerSelector,\n className,\n );\n\n const style = shouldRenderThumb && thumbDataUri ? `background-image: url('${thumbDataUri}');` : '';\n\n return (\n \n {shouldRenderPreview && !canAnimatedPlay && (\n // eslint-disable-next-line jsx-a11y/alt-text\n \n )}\n {shouldPlay && lottieData && (\n \n )}\n {onUnfaveClick && (\n \n \n \n )}\n \n );\n};\n\nexport default memo(StickerButton);\n","import React, {\n FC, memo,\n} from '../../../lib/teact/teact';\nimport { ApiSticker, ApiStickerSet } from '../../../api/types';\n\nimport { STICKER_SIZE_GENERAL_SETTINGS } from '../../../config';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Button from '../../ui/Button';\nimport StickerSetCoverAnimated from '../../middle/composer/StickerSetCoverAnimated';\nimport StickerSetCover from '../../middle/composer/StickerSetCover';\nimport StickerButton from '../../common/StickerButton';\n\nimport './SettingsStickerSet.scss';\n\ntype OwnProps = {\n stickerSet?: ApiStickerSet;\n observeIntersection: ObserveFn;\n onClick: (value: ApiSticker) => void;\n};\n\nconst SettingsStickerSet: FC = ({\n stickerSet,\n observeIntersection,\n onClick,\n}) => {\n const lang = useLang();\n\n if (!stickerSet || !stickerSet.stickers) {\n return undefined;\n }\n\n const firstSticker = stickerSet.stickers && stickerSet.stickers[0];\n\n if (stickerSet.hasThumbnail || !firstSticker) {\n return (\n firstSticker && onClick(firstSticker)}\n >\n \n {stickerSet.isAnimated ? (\n \n ) : (\n \n )}\n \n
\n
{stickerSet.title}
\n
{lang('StickerPack.StickerCount', stickerSet.count, 'i')}
\n
\n \n );\n } else {\n return (\n onClick(firstSticker)}\n >\n \n
\n
{stickerSet.title}
\n
{lang('StickerPack.StickerCount', stickerSet.count, 'i')}
\n
\n \n );\n }\n};\n\nexport default memo(SettingsStickerSet);\n","import React, {\n FC, useCallback, memo, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ISettings } from '../../../types';\nimport { ApiSticker, ApiStickerSet } from '../../../api/types';\n\nimport { IS_MAC_OS, IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\n\nimport ListItem from '../../ui/ListItem';\nimport RangeSlider from '../../ui/RangeSlider';\nimport Checkbox from '../../ui/Checkbox';\nimport RadioGroup from '../../ui/RadioGroup';\nimport SettingsStickerSet from './SettingsStickerSet';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = ISettings['byKey'] & {\n stickerSetIds?: string[];\n stickerSetsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [\n 'Solid and Steady',\n 'Nice and Fast',\n 'Lots of Stuff',\n];\n\nconst SettingsGeneral: FC = ({\n onScreenSelect,\n stickerSetIds,\n stickerSetsById,\n messageTextSize,\n animationLevel,\n messageSendKeyCombo,\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n shouldAutoPlayGifs,\n shouldAutoPlayVideos,\n shouldSuggestStickers,\n shouldLoopStickers,\n setSettingOption,\n loadStickerSets,\n loadAddedStickers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const stickerSettingsRef = useRef(null);\n const { observe: observeIntersectionForCovers } = useIntersectionObserver({ rootRef: stickerSettingsRef });\n const [isModalOpen, openModal, closeModal] = useFlag();\n const [sticker, setSticker] = useState();\n\n const lang = useLang();\n\n const KEYBOARD_SEND_OPTIONS = !IS_TOUCH_ENV ? [\n { value: 'enter', label: lang('lng_settings_send_enter'), subLabel: 'New line by Shift + Enter' },\n {\n value: 'ctrl-enter',\n label: lang(IS_MAC_OS ? 'lng_settings_send_cmdenter' : 'lng_settings_send_ctrlenter'),\n subLabel: 'New line by Enter',\n },\n ] : undefined;\n\n useEffect(() => {\n loadStickerSets();\n }, [loadStickerSets]);\n\n useEffect(() => {\n if (stickerSetIds && stickerSetIds.length) {\n loadAddedStickers();\n }\n }, [stickerSetIds, loadAddedStickers]);\n\n const handleAnimationLevelChange = useCallback((newLevel: number) => {\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [setSettingOption]);\n\n const handleMessageTextSizeChange = useCallback((newSize: number) => {\n document.documentElement.style.setProperty('--message-text-size', `${newSize}px`);\n\n setSettingOption({ messageTextSize: newSize });\n }, [setSettingOption]);\n\n const handleStickerSetClick = useCallback((value: ApiSticker) => {\n setSticker(value);\n openModal();\n }, [openModal]);\n\n const stickerSets = stickerSetIds && stickerSetIds.map((id: string) => {\n return stickerSetsById && stickerSetsById[id] && stickerSetsById[id].installedDate ? stickerSetsById[id] : false;\n }).filter(Boolean);\n\n return (\n
\n
\n

{lang('SETTINGS')}

\n\n \n\n onScreenSelect(SettingsScreens.GeneralChatBackground)}\n >\n {lang('ChatBackground')}\n \n
\n\n
\n

\n Animation Level\n

\n

\n Choose the desired animations amount.\n

\n\n \n
\n\n {KEYBOARD_SEND_OPTIONS && (\n
\n

{lang('Keyboard')}

\n\n setSettingOption({ messageSendKeyCombo: value })}\n selected={messageSendKeyCombo}\n />\n
\n )}\n\n
\n

{lang('AutoDownloadMedia')}

\n\n setSettingOption({ shouldAutoDownloadMediaFromContacts: isChecked })}\n />\n setSettingOption({ shouldAutoDownloadMediaInPrivateChats: isChecked })}\n />\n setSettingOption({ shouldAutoDownloadMediaInGroups: isChecked })}\n />\n setSettingOption({ shouldAutoDownloadMediaInChannels: isChecked })}\n />\n
\n\n
\n

{lang('AutoplayMedia')}

\n\n setSettingOption({ shouldAutoPlayGifs: isChecked })}\n />\n setSettingOption({ shouldAutoPlayVideos: isChecked })}\n />\n
\n\n
\n

{lang('AccDescrStickers')}

\n\n setSettingOption({ shouldSuggestStickers: isChecked })}\n />\n setSettingOption({ shouldLoopStickers: isChecked })}\n />\n\n
\n {stickerSets && stickerSets.map((stickerSet: ApiStickerSet) => (\n \n ))}\n
\n {sticker && (\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n ...pick(global.settings.byKey,\n [\n 'messageTextSize',\n 'animationLevel',\n 'messageSendKeyCombo',\n 'shouldAutoDownloadMediaFromContacts',\n 'shouldAutoDownloadMediaInPrivateChats',\n 'shouldAutoDownloadMediaInGroups',\n 'shouldAutoDownloadMediaInChannels',\n 'shouldAutoPlayGifs',\n 'shouldAutoPlayVideos',\n 'shouldSuggestStickers',\n 'shouldLoopStickers',\n ]),\n stickerSetIds: global.stickers.added.setIds,\n stickerSetsById: global.stickers.setsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setSettingOption', 'loadStickerSets', 'loadAddedStickers',\n ]),\n)(SettingsGeneral));\n","let fileSelector: HTMLInputElement;\n\nexport function openSystemFilesDialog(accept = '*', callback: (e: Event) => void, noMultiple = false) {\n if (!fileSelector) {\n fileSelector = document.createElement('input');\n fileSelector.setAttribute('type', 'file');\n }\n\n fileSelector.setAttribute('accept', accept);\n\n if (noMultiple) {\n fileSelector.removeAttribute('multiple');\n } else {\n fileSelector.setAttribute('multiple', 'multiple');\n }\n\n // eslint-disable-next-line no-null/no-null\n fileSelector.onchange = null;\n fileSelector.value = '';\n fileSelector.onchange = callback;\n\n fileSelector.click();\n}\n","/* eslint-disable eqeqeq */\n/* eslint-disable prefer-template */\n/* eslint-disable prefer-const */\n/* eslint-disable prefer-destructuring */\n/* eslint-disable one-var */\n/* eslint-disable one-var-declaration-per-line */\n\nimport { preloadImage } from './files';\n\n/**\n * HEX > RGB\n * input: 'xxxxxx' (ex. 'ed15fa') case-insensitive\n * output: [r, g, b] ([0-255, 0-255, 0-255])\n */\nexport function hex2rgb(param: string): [number, number, number] {\n return [\n parseInt(param.substring(0, 2), 16),\n parseInt(param.substring(2, 4), 16),\n parseInt(param.substring(4, 6), 16),\n ];\n}\n\n/**\n * RGB > HEX\n * input: [r, g, b] ([0-255, 0-255, 0-255])\n * output: 'xxxxxx' (ex. 'ff0000')\n */\nexport function rgb2hex(param: [number, number, number]) {\n const p0 = param[0].toString(16);\n const p1 = param[1].toString(16);\n const p2 = param[2].toString(16);\n return (p0.length == 1 ? '0' + p0 : p0) + (p1.length == 1 ? '0' + p1 : p1) + (p2.length == 1 ? '0' + p2 : p2);\n}\n\n/**\n * Converts an RGB color value to HSV. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSV_color_space.\n * Assumes r, g, and b are contained in the set [0, 255] and\n * returns h, s, and v in the set [0, 1].\n *\n * @param Number r The red color value\n * @param Number g The green color value\n * @param Number b The blue color value\n * @return Array The HSV representation\n */\nexport function rgb2hsb([r, g, b]: [number, number, number]): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n\n let max = Math.max(r, g, b), min = Math.min(r, g, b);\n let h!: number, s: number, v: number = max;\n\n let d = max - min;\n s = max == 0 ? 0 : d / max;\n\n if (max == min) {\n h = 0; // achromatic\n } else {\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n\n h /= 6;\n }\n\n return [h, s, v];\n}\n\n/**\n * Converts an HSV color value to RGB. Conversion formula\n * adapted from http://en.wikipedia.org/wiki/HSV_color_space.\n * Assumes h, s, and v are contained in the set [0, 1] and\n * returns r, g, and b in the set [0, 255].\n *\n * @param Number h The hue\n * @param Number s The saturation\n * @param Number v The value\n * @return Array The RGB representation\n */\nexport function hsb2rgb([h, s, v]: [number, number, number]): [number, number, number] {\n let r!: number, g!: number, b!: number;\n\n let i = Math.floor(h * 6);\n let f = h * 6 - i;\n let p = v * (1 - s);\n let q = v * (1 - f * s);\n let t = v * (1 - (1 - f) * s);\n\n switch (i % 6) {\n case 0:\n r = v;\n g = t;\n b = p;\n break;\n case 1:\n r = q;\n g = v;\n b = p;\n break;\n case 2:\n r = p;\n g = v;\n b = t;\n break;\n case 3:\n r = p;\n g = q;\n b = v;\n break;\n case 4:\n r = t;\n g = p;\n b = v;\n break;\n case 5:\n r = v;\n g = p;\n b = q;\n break;\n }\n\n return [\n Math.round(r * 255),\n Math.round(g * 255),\n Math.round(b * 255),\n ];\n}\n\nexport async function getAverageColor(url: string): Promise<[number, number, number]> {\n // Only visit every 5 pixels\n const blockSize = 5;\n const defaultRGB: [number, number, number] = [0, 0, 0];\n let data;\n let width;\n let height;\n let i = -4;\n let length;\n let rgb: [number, number, number] = [0, 0, 0];\n let count = 0;\n\n const canvas = document.createElement('canvas');\n const context = canvas.getContext && canvas.getContext('2d');\n if (!context) {\n return defaultRGB;\n }\n\n const image = await preloadImage(url);\n height = image.naturalHeight || image.offsetHeight || image.height;\n width = image.naturalWidth || image.offsetWidth || image.width;\n canvas.height = height;\n canvas.width = width;\n\n context.drawImage(image, 0, 0);\n\n try {\n data = context.getImageData(0, 0, width, height);\n } catch (e) {\n return defaultRGB;\n }\n\n length = data.data.length;\n\n // eslint-disable-next-line no-cond-assign\n while ((i += blockSize * 4) < length) {\n ++count;\n rgb[0] += data.data[i];\n rgb[1] += data.data[i + 1];\n rgb[2] += data.data[i + 2];\n }\n\n rgb[0] = Math.floor(rgb[0] / count);\n rgb[1] = Math.floor(rgb[1] / count);\n rgb[2] = Math.floor(rgb[2] / count);\n\n return rgb;\n}\n\n// eslint-disable-next-line max-len\n// Function was adapted from https://github.com/telegramdesktop/tdesktop/blob/35ff621b5b52f7e3553fb0f990ea13ade7101b8e/Telegram/SourceFiles/data/data_wall_paper.cpp#L518\nexport function getPatternColor(rgbColor: [number, number, number]) {\n let [hue, saturation, value] = rgb2hsb(rgbColor);\n\n saturation = Math.min(1, saturation + 0.05 + 0.1 * (1 - saturation));\n value = value > 0.5\n ? Math.max(0, value * 0.65)\n : Math.max(0, Math.min(1, 1 - value * 0.65));\n\n return `hsla(${hue * 360}, ${saturation * 100}%, ${value * 100}%, .4)`;\n}\n","import React, {\n FC, memo, useCallback, useEffect, useState, useRef,\n} from '../../../lib/teact/teact';\nimport { ApiWallpaper } from '../../../api/types';\nimport { ThemeKey, UPLOADING_WALLPAPER_SLUG } from '../../../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../../../config';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { fetchBlob } from '../../../util/files';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport useMedia from '../../../hooks/useMedia';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useCanvasBlur from '../../../hooks/useCanvasBlur';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './WallpaperTile.scss';\n\ntype OwnProps = {\n wallpaper: ApiWallpaper;\n theme: ThemeKey;\n isSelected: boolean;\n onClick: (slug: string) => void;\n};\n\nconst WallpaperTile: FC = ({\n wallpaper,\n theme,\n isSelected,\n onClick,\n}) => {\n const { slug, document } = wallpaper;\n const localMediaHash = `wallpaper${document.id!}`;\n const localBlobUrl = document.previewBlobUrl;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`);\n const thumbRef = useCanvasBlur(\n document.thumbnail && document.thumbnail.dataUri,\n Boolean(previewBlobUrl),\n true,\n );\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(previewBlobUrl || localBlobUrl, 'slow');\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(false);\n const {\n mediaData: fullMedia, downloadProgress,\n } = useMediaWithDownloadProgress(localMediaHash, !isDownloadAllowed);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const { shouldRender: shouldRenderSpinner, transitionClassNames: spinnerClassNames } = useShowTransition(\n (isDownloadAllowed && !fullMedia) || slug === UPLOADING_WALLPAPER_SLUG,\n undefined,\n wasDownloadDisabled,\n 'slow',\n );\n // To prevent triggering of the effect for useCallback\n const cacheKeyRef = useRef();\n cacheKeyRef.current = theme;\n\n const handleSelect = useCallback(() => {\n (async () => {\n const blob = await fetchBlob(fullMedia!);\n await cacheApi.save(CUSTOM_BG_CACHE_NAME, cacheKeyRef.current!, blob);\n onClick(slug);\n })();\n }, [fullMedia, onClick, slug]);\n\n useEffect(() => {\n if (fullMedia) {\n handleSelect();\n }\n }, [fullMedia, handleSelect]);\n\n const handleClick = useCallback(() => {\n if (fullMedia) {\n handleSelect();\n } else {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n }\n }, [fullMedia, handleSelect]);\n\n const className = buildClassName(\n 'WallpaperTile',\n isSelected && 'selected',\n );\n\n return (\n
\n
\n {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n
\n
\n );\n};\n\nexport default memo(WallpaperTile);\n","import React, {\n FC, memo, useEffect, useCallback, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ThemeKey, UPLOADING_WALLPAPER_SLUG } from '../../../types';\nimport { ApiWallpaper } from '../../../api/types';\n\nimport { DARK_THEME_PATTERN_COLOR, DEFAULT_PATTERN_COLOR } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { throttle } from '../../../util/schedulers';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport { getAverageColor, getPatternColor, rgb2hex } from '../../../util/colors';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Loading from '../../ui/Loading';\nimport WallpaperTile from './WallpaperTile';\n\nimport './SettingsGeneralBackground.scss';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n background?: string;\n isBlurred?: boolean;\n loadedWallpapers?: ApiWallpaper[];\n theme: ThemeKey;\n};\n\ntype DispatchProps = Pick;\n\nconst SUPPORTED_TYPES = 'image/jpeg';\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst SettingsGeneralBackground: FC = ({\n onScreenSelect,\n background,\n isBlurred,\n loadedWallpapers,\n theme,\n loadWallpapers,\n uploadWallpaper,\n setThemeSettings,\n}) => {\n const themeRef = useRef();\n themeRef.current = theme;\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadWallpapers();\n });\n }, [loadWallpapers]);\n\n const handleFileSelect = useCallback((e: Event) => {\n const { files } = e.target as HTMLInputElement;\n\n if (files && files.length > 0) {\n uploadWallpaper(files[0]);\n }\n }, [uploadWallpaper]);\n\n const handleUploadWallpaper = useCallback(() => {\n openSystemFilesDialog(SUPPORTED_TYPES, handleFileSelect, true);\n }, [handleFileSelect]);\n\n const handleSetColor = useCallback(() => {\n onScreenSelect(SettingsScreens.GeneralChatBackgroundColor);\n }, [onScreenSelect]);\n\n const handleResetToDefault = useCallback(() => {\n setThemeSettings({\n theme,\n background: undefined,\n backgroundColor: undefined,\n isBlurred: true,\n patternColor: theme === 'dark' ? DARK_THEME_PATTERN_COLOR : DEFAULT_PATTERN_COLOR,\n });\n }, [setThemeSettings, theme]);\n\n const handleWallPaperSelect = useCallback((slug: string) => {\n setThemeSettings({ theme: themeRef.current, background: slug });\n const currentWallpaper = loadedWallpapers && loadedWallpapers.find((wallpaper) => wallpaper.slug === slug);\n if (currentWallpaper && currentWallpaper.document.thumbnail) {\n getAverageColor(currentWallpaper.document.thumbnail.dataUri)\n .then((color) => {\n const patternColor = getPatternColor(color);\n const rgbColor = `#${rgb2hex(color)}`;\n setThemeSettings({ theme: themeRef.current, backgroundColor: rgbColor, patternColor });\n });\n }\n }, [loadedWallpapers, setThemeSettings]);\n\n const handleWallPaperBlurChange = useCallback((e: React.ChangeEvent) => {\n setThemeSettings({ theme: themeRef.current, isBlurred: e.target.checked });\n }, [setThemeSettings]);\n\n const lang = useLang();\n\n const isUploading = loadedWallpapers && loadedWallpapers[0] && loadedWallpapers[0].slug === UPLOADING_WALLPAPER_SLUG;\n\n return (\n
\n
\n \n {lang('UploadImage')}\n \n\n \n {lang('SetColor')}\n \n\n \n {lang('ThemeResetToDefaults')}\n \n\n \n
\n\n {loadedWallpapers ? (\n
\n {loadedWallpapers.map((wallpaper) => (\n \n ))}\n
\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { background, isBlurred } = global.settings.themes[theme] || {};\n const { loadedWallpapers } = global.settings;\n\n return {\n background,\n isBlurred,\n loadedWallpapers,\n theme,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWallpapers', 'uploadWallpaper', 'setThemeSettings',\n ]),\n)(SettingsGeneralBackground));\n","import { ChangeEvent, MutableRefObject, RefObject } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { SettingsScreens, ThemeKey } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport {\n getPatternColor, hex2rgb, hsb2rgb, rgb2hex, rgb2hsb,\n} from '../../../util/colors';\nimport { captureEvents, RealTouchEvent } from '../../../util/captureEvents';\nimport useFlag from '../../../hooks/useFlag';\nimport buildClassName from '../../../util/buildClassName';\n\nimport InputText from '../../ui/InputText';\n\nimport './SettingsGeneralBackgroundColor.scss';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n backgroundColor?: string;\n theme: ThemeKey;\n};\n\ntype DispatchProps = Pick;\n\ninterface CanvasRects {\n colorRect: {\n offsetLeft: number;\n top: number;\n width: number;\n height: number;\n };\n hueRect: {\n offsetLeft: number;\n width: number;\n };\n}\n\nconst DEFAULT_HSB = rgb2hsb(hex2rgb('e6ebee'));\nconst PREDEFINED_COLORS = [\n '#e6ebee', '#b2cee1', '#008dd0', '#c6e7cb', '#c4e1a6', '#60b16e',\n '#ccd0af', '#a6a997', '#7a7072', '#fdd7af', '#fdb76e', '#dd8851',\n];\n\nconst SettingsGeneralBackground: FC = ({\n theme,\n backgroundColor,\n setThemeSettings,\n}) => {\n const themeRef = useRef();\n themeRef.current = theme;\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 colorPickerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const huePickerRef = useRef(null);\n const isFirstRunRef = useRef(true);\n\n const [hsb, setHsb] = useState(getInitialHsb(backgroundColor));\n // Cache for drag handlers\n const hsbRef = useRef(hsb);\n useEffect(() => {\n hsbRef.current = hsb;\n }, [hsb]);\n\n const [isDragging, markIsDragging, unmarkIsDragging] = useFlag();\n const [rgbInput, setRgbInput] = useState('');\n const [hexInput, setHexInput] = useState('');\n\n const rectsRef = useRef();\n const colorCtxRef = useRef();\n\n // Setup: cache rects, subscribe for drag events\n useEffect(() => {\n // We use `offsetLeft` instead of `left` to support screen transition\n const colorRect = {\n offsetLeft: colorPickerRef.current!.offsetLeft,\n ...pick(colorPickerRef.current!.getBoundingClientRect(), ['top', 'width', 'height']),\n };\n const hueRect = {\n offsetLeft: huePickerRef.current!.offsetLeft,\n ...pick(huePickerRef.current!.getBoundingClientRect(), ['width']),\n };\n\n rectsRef.current = { colorRect, hueRect };\n\n function handleColorDrag(e: MouseEvent | RealTouchEvent) {\n const colorPosition = [\n Math.min(Math.max(0, e.pageX! - colorRect.offsetLeft), colorRect.width - 1),\n Math.min(Math.max(0, e.pageY! - colorRect.top + containerRef.current!.scrollTop), colorRect.height - 1),\n ];\n\n const { huePosition } = hsb2positions(hsbRef.current, rectsRef.current!);\n\n setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!));\n markIsDragging();\n }\n\n captureEvents(colorPickerRef.current!, {\n onCapture: handleColorDrag,\n onDrag: handleColorDrag,\n onRelease: unmarkIsDragging,\n onClick: unmarkIsDragging,\n withCursor: true,\n });\n\n function handleHueDrag(e: MouseEvent | RealTouchEvent) {\n const { colorPosition } = hsb2positions(hsbRef.current, rectsRef.current!);\n const huePosition = Math.min(Math.max(0, e.pageX! - hueRect.offsetLeft), hueRect.width - 1);\n\n setHsb(positions2hsb({ colorPosition, huePosition }, rectsRef.current!));\n markIsDragging();\n }\n\n captureEvents(huePickerRef.current!, {\n onCapture: handleHueDrag,\n onDrag: handleHueDrag,\n onRelease: unmarkIsDragging,\n onClick: unmarkIsDragging,\n withCursor: true,\n });\n }, [markIsDragging, unmarkIsDragging]);\n\n const { colorPosition = [0, 0], huePosition = 0 } = rectsRef.current ? hsb2positions(hsb, rectsRef.current) : {};\n const hex = rgb2hex(hsb2rgb(hsb));\n const hue = hsb[0];\n const hueHex = rgb2hex(hsb2rgb([hue, 1, 1]));\n\n // Save value and update inputs when HSL changes\n useEffect(() => {\n const rgb = hsb2rgb(hsb);\n const color = `#${rgb2hex(rgb)}`;\n\n setRgbInput(rgb.join(', '));\n setHexInput(color);\n\n if (!isFirstRunRef.current) {\n const patternColor = getPatternColor(rgb);\n setThemeSettings({\n theme: themeRef.current,\n background: undefined,\n backgroundColor: color,\n patternColor,\n });\n }\n isFirstRunRef.current = false;\n }, [hsb, setThemeSettings]);\n\n // Redraw color picker when hue changes\n useEffect(() => {\n drawColor(colorPickerRef.current!.firstChild as HTMLCanvasElement, hue, colorCtxRef, rectsRef);\n }, [hue]);\n\n // Initially draw hue picker\n useEffect(() => {\n drawHue(huePickerRef.current!.firstChild as HTMLCanvasElement);\n }, []);\n\n const handleRgbChange = useCallback((e: ChangeEvent) => {\n const rgbValue = e.currentTarget.value.replace(/[^\\d, ]/g, '').slice(0, 13);\n\n if (rgbValue.match(/^\\d{1,3},\\s?\\d{1,3},\\s?\\d{1,3}$/)) {\n const rgb = rgbValue.split(',').map((channel) => Number(channel.trim())) as [number, number, number];\n setHsb(rgb2hsb(rgb));\n }\n\n e.currentTarget.value = rgbValue;\n }, []);\n\n const handleHexChange = useCallback((e: ChangeEvent) => {\n const hexValue = e.currentTarget.value.replace(/[^0-9a-fA-F]/g, '').slice(0, 6);\n\n if (hexValue.match(/^#?[0-9a-fA-F]{6}$/)) {\n setHsb(rgb2hsb(hex2rgb(hexValue.replace('#', ''))));\n }\n\n e.currentTarget.value = hexValue;\n }, []);\n\n const handlePredefinedColorClick = useCallback((e: React.MouseEvent) => {\n setHsb(rgb2hsb(hex2rgb(e.currentTarget.dataset.color!.replace('#', ''))));\n }, []);\n\n const className = buildClassName(\n 'SettingsGeneralBackgroundColor settings-content custom-scroll',\n isDragging && 'is-dragging',\n );\n\n return (\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n {PREDEFINED_COLORS.map((color) => (\n \n ))}\n
\n
\n );\n};\n\nfunction getInitialHsb(backgroundColor?: string) {\n return backgroundColor && backgroundColor.startsWith('#')\n ? rgb2hsb(hex2rgb(backgroundColor.replace('#', '')))\n : DEFAULT_HSB;\n}\n\nfunction hsb2positions(hsb: [number, number, number], rects: CanvasRects) {\n return {\n colorPosition: [\n Math.round((hsb[1]) * (rects.colorRect.width - 1)),\n Math.round((1 - hsb[2]) * (rects.colorRect.height - 1)),\n ],\n huePosition: Math.round(hsb[0] * (rects.hueRect.width - 1)),\n };\n}\n\nfunction positions2hsb(\n { colorPosition, huePosition }: { colorPosition: number[]; huePosition: number },\n rects: CanvasRects,\n): [number, number, number] {\n return [\n huePosition / (rects.hueRect.width - 1),\n colorPosition[0] / (rects.colorRect.width - 1),\n 1 - colorPosition[1] / (rects.colorRect.height - 1),\n ];\n}\n\nfunction drawColor(\n canvas: HTMLCanvasElement,\n hue: number,\n colorCtxRef: MutableRefObject,\n rectsRef: RefObject,\n) {\n let w: number;\n let h: number;\n let ctx: CanvasRenderingContext2D;\n\n if (!colorCtxRef.current || !rectsRef.current) {\n // First run\n w = canvas.offsetWidth;\n h = canvas.offsetHeight;\n ctx = canvas.getContext('2d')!;\n\n canvas.width = w;\n canvas.height = h;\n\n colorCtxRef.current = ctx;\n } else {\n w = rectsRef.current.colorRect.width;\n h = rectsRef.current.colorRect.height;\n ctx = colorCtxRef.current;\n }\n\n const imgData = ctx!.createImageData(w, h);\n const pixels = imgData.data;\n const col = hsb2rgb([hue, 1, 1]);\n\n let index = 0;\n\n for (let y = 0; y < h; y++) {\n const perY = 1 - y / (h - 1);\n const st = [255 * perY, 255 * perY, 255 * perY];\n const ed = [col[0] * perY, col[1] * perY, col[2] * perY];\n for (let x = 0; x < w; x++) {\n const perX = x / (w - 1);\n pixels[index++] = st[0] + (ed[0] - st[0]) * perX;\n pixels[index++] = st[1] + (ed[1] - st[1]) * perX;\n pixels[index++] = st[2] + (ed[2] - st[2]) * perX;\n pixels[index++] = 255;\n }\n }\n\n ctx!.putImageData(imgData, 0, 0);\n}\n\nfunction drawHue(canvas: HTMLCanvasElement) {\n const w = canvas.offsetWidth;\n const h = 1;\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext('2d')!;\n\n const imgData = ctx.createImageData(w, h);\n const pixels = imgData.data;\n\n let index = 0;\n\n for (let x = 0; x < w; x++) {\n const hue = x / (w - 1);\n const rgb = hsb2rgb([hue, 1, 1]);\n /* eslint-disable prefer-destructuring */\n pixels[index++] = rgb[0];\n pixels[index++] = rgb[1];\n pixels[index++] = rgb[2];\n /* eslint-enable prefer-destructuring */\n pixels[index++] = 255;\n }\n\n ctx.putImageData(imgData, 0, 0);\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const { backgroundColor } = global.settings.themes[theme] || {};\n return {\n backgroundColor,\n theme,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setThemeSettings']),\n)(SettingsGeneralBackground));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport Checkbox from '../../ui/Checkbox';\n\ntype StateProps = {\n hasPrivateChatsNotifications: boolean;\n hasPrivateChatsMessagePreview: boolean;\n hasGroupNotifications: boolean;\n hasGroupMessagePreview: boolean;\n hasBroadcastNotifications: boolean;\n hasBroadcastMessagePreview: boolean;\n hasContactJoinedNotifications: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsNotifications: FC = ({\n hasPrivateChatsNotifications,\n hasPrivateChatsMessagePreview,\n hasGroupNotifications,\n hasGroupMessagePreview,\n hasBroadcastNotifications,\n hasBroadcastMessagePreview,\n hasContactJoinedNotifications,\n loadNotificationSettings,\n updateContactSignUpNotification,\n updateNotificationSettings,\n}) => {\n useEffect(() => {\n loadNotificationSettings();\n }, [loadNotificationSettings]);\n\n const handleSettingsChange = useCallback((\n e: ChangeEvent,\n peerType: 'contact' | 'group' | 'broadcast',\n setting: 'silent' | 'showPreviews',\n ) => {\n const currentIsSilent = peerType === 'contact'\n ? !hasPrivateChatsNotifications\n : !(peerType === 'group' ? hasGroupNotifications : hasBroadcastNotifications);\n const currentShouldShowPreviews = peerType === 'contact'\n ? hasPrivateChatsMessagePreview\n : (peerType === 'group' ? hasGroupMessagePreview : hasBroadcastMessagePreview);\n\n updateNotificationSettings({\n peerType,\n ...(setting === 'silent' && { isSilent: !e.target.checked, shouldShowPreviews: currentShouldShowPreviews }),\n ...(setting === 'showPreviews' && { shouldShowPreviews: e.target.checked, isSilent: currentIsSilent }),\n });\n }, [\n hasBroadcastMessagePreview, hasBroadcastNotifications,\n hasGroupMessagePreview, hasGroupNotifications,\n hasPrivateChatsMessagePreview, hasPrivateChatsNotifications,\n updateNotificationSettings,\n ]);\n\n const handleContactNotificationChange = useCallback((e: ChangeEvent) => {\n updateContactSignUpNotification({\n isSilent: !e.target.checked,\n });\n }, [updateContactSignUpNotification]);\n\n const lang = useLang();\n\n return (\n
\n
\n

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

\n\n { handleSettingsChange(e, 'contact', 'silent'); }}\n />\n { handleSettingsChange(e, 'contact', 'showPreviews'); }}\n />\n
\n\n
\n

{lang('FilterGroups')}

\n\n { handleSettingsChange(e, 'group', 'silent'); }}\n />\n { handleSettingsChange(e, 'group', 'showPreviews'); }}\n />\n
\n\n
\n

{lang('FilterChannels')}

\n\n { handleSettingsChange(e, 'broadcast', 'silent'); }}\n />\n { handleSettingsChange(e, 'broadcast', 'showPreviews'); }}\n />\n
\n\n
\n

{lang('PhoneOther')}

\n\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global): StateProps => {\n return {\n hasPrivateChatsNotifications: Boolean(global.settings.byKey.hasPrivateChatsNotifications),\n hasPrivateChatsMessagePreview: Boolean(global.settings.byKey.hasPrivateChatsMessagePreview),\n hasGroupNotifications: Boolean(global.settings.byKey.hasGroupNotifications),\n hasGroupMessagePreview: Boolean(global.settings.byKey.hasGroupMessagePreview),\n hasBroadcastNotifications: Boolean(global.settings.byKey.hasBroadcastNotifications),\n hasBroadcastMessagePreview: Boolean(global.settings.byKey.hasBroadcastMessagePreview),\n hasContactJoinedNotifications: Boolean(global.settings.byKey.hasContactJoinedNotifications),\n };\n},\n(setGlobal, actions): DispatchProps => pick(actions, [\n 'loadNotificationSettings',\n 'updateContactSignUpNotification',\n 'updateNotificationSettings',\n]))(SettingsNotifications));\n","import React, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { PrivacyVisibility, SettingsScreens } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n hasPassword?: boolean;\n blockedCount: number;\n sessionsCount: number;\n visibilityPrivacyPhoneNumber?: PrivacyVisibility;\n visibilityPrivacyLastSeen?: PrivacyVisibility;\n visibilityPrivacyProfilePhoto?: PrivacyVisibility;\n visibilityPrivacyForwarding?: PrivacyVisibility;\n visibilityPrivacyGroupChats?: PrivacyVisibility;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacy: FC = ({\n onScreenSelect,\n hasPassword,\n blockedCount,\n sessionsCount,\n visibilityPrivacyPhoneNumber,\n visibilityPrivacyLastSeen,\n visibilityPrivacyProfilePhoto,\n visibilityPrivacyForwarding,\n visibilityPrivacyGroupChats,\n loadPrivacySettings,\n loadBlockedContacts,\n loadAuthorizations,\n}) => {\n useEffect(() => {\n loadBlockedContacts();\n loadAuthorizations();\n loadPrivacySettings();\n }, [loadBlockedContacts, loadAuthorizations, loadPrivacySettings]);\n\n const lang = useLang();\n\n function getVisibilityValue(visibility?: PrivacyVisibility) {\n switch (visibility) {\n case 'everybody':\n return lang('P2PEverybody');\n\n case 'contacts':\n return lang('P2PContacts');\n\n case 'nobody':\n return lang('P2PNobody');\n }\n\n return undefined;\n }\n\n return (\n
\n
\n onScreenSelect(SettingsScreens.PrivacyBlockedUsers)}\n >\n
\n {lang('BlockedUsers')}\n {blockedCount > 0 && (\n \n {lang('Users', blockedCount)}\n \n )}\n
\n \n onScreenSelect(\n hasPassword ? SettingsScreens.TwoFaEnabled : SettingsScreens.TwoFaDisabled,\n )}\n >\n
\n {lang('TwoStepVerification')}\n \n {lang(hasPassword ? 'PasswordOn' : 'PasswordOff')}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyActiveSessions)}\n >\n
\n {lang('SessionsTitle')}\n {sessionsCount > 0 && (\n \n {sessionsCount === 1 ? '1 session' : `${sessionsCount} sessions`}\n \n )}\n
\n \n
\n\n
\n

{lang('PrivacyTitle')}

\n\n onScreenSelect(SettingsScreens.PrivacyPhoneNumber)}\n >\n
\n {lang('PrivacyPhoneTitle')}\n \n {getVisibilityValue(visibilityPrivacyPhoneNumber)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyLastSeen)}\n >\n
\n {lang('LastSeenTitle')}\n \n {getVisibilityValue(visibilityPrivacyLastSeen)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyProfilePhoto)}\n >\n
\n {lang('PrivacyProfilePhotoTitle')}\n \n {getVisibilityValue(visibilityPrivacyProfilePhoto)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyForwarding)}\n >\n
\n {lang('PrivacyForwardsTitle')}\n \n {getVisibilityValue(visibilityPrivacyForwarding)}\n \n
\n \n onScreenSelect(SettingsScreens.PrivacyGroupChats)}\n >\n
\n {lang('WhoCanAddMe')}\n \n {getVisibilityValue(visibilityPrivacyGroupChats)}\n \n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n settings: {\n byKey: { hasPassword },\n privacy,\n },\n blocked,\n activeSessions,\n } = global;\n\n return {\n hasPassword,\n blockedCount: blocked.totalCount,\n sessionsCount: activeSessions.length,\n visibilityPrivacyPhoneNumber: privacy.phoneNumber && privacy.phoneNumber.visibility,\n visibilityPrivacyLastSeen: privacy.lastSeen && privacy.lastSeen.visibility,\n visibilityPrivacyProfilePhoto: privacy.profilePhoto && privacy.profilePhoto.visibility,\n visibilityPrivacyForwarding: privacy.forwards && privacy.forwards.visibility,\n visibilityPrivacyGroupChats: privacy.chatInvite && privacy.chatInvite.visibility,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadBlockedContacts', 'loadAuthorizations', 'loadPrivacySettings',\n ]),\n)(SettingsPrivacy));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ISettings } from '../../../types';\nimport { ApiLanguage } from '../../../api/types';\n\nimport { setLanguage } from '../../../util/langProvider';\nimport { pick } from '../../../util/iteratees';\n\nimport RadioGroup from '../../ui/RadioGroup';\nimport Loading from '../../ui/Loading';\nimport useFlag from '../../../hooks/useFlag';\n\ntype StateProps = Pick;\n\ntype DispatchProps = Pick;\n\nconst SettingsLanguage: FC = ({\n languages,\n language,\n loadLanguages,\n setSettingOption,\n}) => {\n const [selectedLanguage, setSelectedLanguage] = useState(language);\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n // TODO Throttle\n useEffect(() => {\n loadLanguages();\n }, [loadLanguages]);\n\n const handleChange = useCallback((langCode: string) => {\n setSelectedLanguage(langCode);\n markIsLoading();\n\n setLanguage(langCode, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: langCode });\n });\n }, [markIsLoading, unmarkIsLoading, setSettingOption]);\n\n const options = useMemo(() => {\n return languages ? buildOptions(languages) : undefined;\n }, [languages]);\n\n return (\n
\n {options ? (\n \n ) : (\n \n )}\n
\n );\n};\n\nfunction buildOptions(languages: ApiLanguage[]) {\n const currentLangCode = (window.navigator.language || 'en').toLowerCase();\n const shortLangCode = currentLangCode.substr(0, 2);\n\n return languages.map(({ langCode, nativeName, name }) => ({\n value: langCode,\n label: nativeName,\n subLabel: name,\n })).sort((a) => {\n return currentLangCode && (a.value === currentLangCode || a.value === shortLangCode) ? -1 : 0;\n });\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n languages: global.settings.byKey.languages,\n language: global.settings.byKey.language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadLanguages', 'setSettingOption',\n ]),\n)(SettingsLanguage));\n","import { ApiPrivacyKey, SettingsScreens } from '../../../../types';\n\nexport function getPrivacyKey(screen: SettingsScreens): ApiPrivacyKey | undefined {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n return 'phoneNumber';\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n return 'lastSeen';\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n return 'profilePhoto';\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n return 'forwards';\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return 'chatInvite';\n }\n\n return undefined;\n}\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\nimport { ApiPrivacySettings, SettingsScreens } from '../../../types';\n\nimport useLang from '../../../hooks/useLang';\nimport { pick } from '../../../util/iteratees';\n\nimport ListItem from '../../ui/ListItem';\nimport RadioGroup from '../../ui/RadioGroup';\nimport { getPrivacyKey } from './helper/privacy';\n\ntype OwnProps = {\n screen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = Partial & {\n chatsById?: Record;\n usersById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyVisibility: FC = ({\n screen,\n onScreenSelect,\n visibility,\n allowUserIds,\n allowChatIds,\n blockUserIds,\n blockChatIds,\n chatsById,\n setPrivacyVisibility,\n}) => {\n const lang = useLang();\n\n const visibilityOptions = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyGroupChats:\n return [\n { value: 'everybody', label: lang('P2PEverybody') },\n { value: 'contacts', label: lang('P2PContacts') },\n ];\n\n default:\n return [\n { value: 'everybody', label: lang('P2PEverybody') },\n { value: 'contacts', label: lang('P2PContacts') },\n { value: 'nobody', label: lang('P2PNobody') },\n ];\n }\n }, [lang, screen]);\n\n const exceptionLists = {\n shouldShowDenied: visibility !== 'nobody',\n shouldShowAllowed: visibility !== 'everybody',\n };\n\n const privacyKey = getPrivacyKey(screen);\n\n const headerText = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return lang('PrivacyPhoneTitle');\n case SettingsScreens.PrivacyLastSeen:\n return lang('LastSeenTitle');\n case SettingsScreens.PrivacyProfilePhoto:\n return lang('PrivacyProfilePhotoTitle');\n case SettingsScreens.PrivacyForwarding:\n return lang('PrivacyForwardsTitle');\n case SettingsScreens.PrivacyGroupChats:\n return lang('WhoCanAddMe');\n default:\n return undefined;\n }\n }, [lang, screen]);\n\n const descriptionText = useMemo(() => {\n switch (screen) {\n case SettingsScreens.PrivacyLastSeen:\n return lang('CustomHelp');\n default:\n return undefined;\n }\n }, [lang, screen]);\n\n const allowedContactsScreen = (() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return SettingsScreens.PrivacyPhoneNumberAllowedContacts;\n case SettingsScreens.PrivacyLastSeen:\n return SettingsScreens.PrivacyLastSeenAllowedContacts;\n case SettingsScreens.PrivacyProfilePhoto:\n return SettingsScreens.PrivacyProfilePhotoAllowedContacts;\n case SettingsScreens.PrivacyForwarding:\n return SettingsScreens.PrivacyForwardingAllowedContacts;\n default:\n return SettingsScreens.PrivacyGroupChatsAllowedContacts;\n }\n })();\n\n const deniedContactsScreen = (() => {\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n return SettingsScreens.PrivacyPhoneNumberDeniedContacts;\n case SettingsScreens.PrivacyLastSeen:\n return SettingsScreens.PrivacyLastSeenDeniedContacts;\n case SettingsScreens.PrivacyProfilePhoto:\n return SettingsScreens.PrivacyProfilePhotoDeniedContacts;\n case SettingsScreens.PrivacyForwarding:\n return SettingsScreens.PrivacyForwardingDeniedContacts;\n default:\n return SettingsScreens.PrivacyGroupChatsDeniedContacts;\n }\n })();\n\n const allowedCount = useMemo(() => {\n if (!allowUserIds || !allowChatIds || !chatsById) {\n return 0;\n }\n\n return allowChatIds.reduce((result, chatId) => {\n return result + (chatsById[chatId] ? chatsById[chatId].membersCount! : 0);\n }, allowUserIds.length);\n }, [allowChatIds, allowUserIds, chatsById]);\n\n const blockCount = useMemo(() => {\n if (!blockUserIds || !blockChatIds || !chatsById) {\n return 0;\n }\n\n return blockChatIds.reduce((result, chatId) => {\n return result + (chatsById[chatId] ? chatsById[chatId].membersCount! : 0);\n }, blockUserIds.length);\n }, [blockChatIds, blockUserIds, chatsById]);\n\n const handleVisibilityChange = useCallback((value) => {\n setPrivacyVisibility({\n privacyKey,\n visibility: value,\n });\n }, [privacyKey, setPrivacyVisibility]);\n\n return (\n
\n
\n

{headerText}

\n\n \n\n {descriptionText && (\n

{descriptionText}

\n )}\n
\n\n
\n

{lang('PrivacyExceptions')}

\n\n {exceptionLists.shouldShowAllowed && (\n { onScreenSelect(allowedContactsScreen); }}\n >\n
\n {allowedCount > 0 && +{allowedCount}}\n {lang('AlwaysShareWith')}\n {lang('EditAdminAddUsers')}\n
\n \n )}\n {exceptionLists.shouldShowDenied && (\n { onScreenSelect(deniedContactsScreen); }}\n >\n
\n {blockCount > 0 && −{blockCount}}\n {lang('NeverShareWith')}\n {lang('EditAdminAddUsers')}\n
\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { screen }): StateProps => {\n let privacySettings: ApiPrivacySettings | undefined;\n\n const {\n chats: { byId: chatsById },\n settings: { privacy },\n } = global;\n\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumber:\n privacySettings = privacy.phoneNumber;\n break;\n\n case SettingsScreens.PrivacyLastSeen:\n privacySettings = privacy.lastSeen;\n break;\n\n case SettingsScreens.PrivacyProfilePhoto:\n privacySettings = privacy.profilePhoto;\n break;\n\n case SettingsScreens.PrivacyForwarding:\n privacySettings = privacy.forwards;\n break;\n\n case SettingsScreens.PrivacyGroupChats:\n privacySettings = privacy.chatInvite;\n break;\n }\n\n if (!privacySettings) {\n return {};\n }\n\n return {\n ...privacySettings,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setPrivacyVisibility']),\n)(SettingsPrivacyVisibility));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiSession } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { formatPastTimeShort } from '../../../util/dateFormat';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype StateProps = {\n activeSessions: ApiSession[];\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyActiveSessions: FC = ({\n activeSessions,\n loadAuthorizations,\n terminateAuthorization,\n terminateAllAuthorizations,\n}) => {\n const [isConfirmTerminateAllDialogOpen, openConfirmTerminateAllDialog, closeConfirmTerminateAllDialog] = useFlag();\n useEffect(() => {\n loadAuthorizations();\n }, [loadAuthorizations]);\n\n const handleTerminateSessionClick = useCallback((hash: string) => {\n terminateAuthorization({ hash });\n }, [terminateAuthorization]);\n\n const handleTerminateAllSessions = useCallback(() => {\n closeConfirmTerminateAllDialog();\n terminateAllAuthorizations();\n }, [closeConfirmTerminateAllDialog, terminateAllAuthorizations]);\n\n const currentSession = useMemo(() => {\n return activeSessions.find((session) => session.isCurrent);\n }, [activeSessions]);\n\n const otherSessions = useMemo(() => {\n return activeSessions.filter((session) => !session.isCurrent);\n }, [activeSessions]);\n\n const lang = useLang();\n\n function renderCurrentSession(session: ApiSession) {\n return (\n
\n

\n {lang('AuthSessions.CurrentSession')}\n

\n\n \n
\n {session.appName}\n {getDeviceEnvironment(session)}\n {session.ip} - {getLocation(session)}\n
\n
\n\n \n {lang('TerminateAllSessions')}\n \n
\n );\n }\n\n function renderOtherSessions(sessions: ApiSession[]) {\n return (\n
\n

Other Sessions

\n\n {sessions.map(renderSession)}\n
\n );\n }\n\n function renderSession(session: ApiSession) {\n return (\n {\n handleTerminateSessionClick(session.hash);\n },\n }]}\n >\n
\n {formatPastTimeShort(lang, session.dateActive * 1000)}\n {session.appName}\n {getDeviceEnvironment(session)}\n {session.ip} - {getLocation(session)}\n
\n \n );\n }\n\n return (\n
\n {currentSession && renderCurrentSession(currentSession)}\n\n {otherSessions && renderOtherSessions(otherSessions)}\n\n {otherSessions && (\n \n )};\n
\n );\n};\n\nfunction getLocation(session: ApiSession) {\n return [session.region, session.country].filter(Boolean).join(', ');\n}\n\nfunction getDeviceEnvironment(session: ApiSession) {\n return `${session.deviceModel}${session.deviceModel ? ', ' : ''} ${session.platform} ${session.systemVersion}`;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n activeSessions: global.activeSessions,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadAuthorizations', 'terminateAuthorization', 'terminateAllAuthorizations',\n ]),\n)(SettingsPrivacyActiveSessions));\n","import React, {\n FC, memo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { CHAT_HEIGHT_PX } from '../../../config';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport { pick } from '../../../util/iteratees';\nimport {\n getChatTitle, getUserFullName, isChatPrivate,\n} from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport buildClassName from '../../../util/buildClassName';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Avatar from '../../common/Avatar';\nimport Loading from '../../ui/Loading';\n\ntype StateProps = {\n chatsByIds: Record;\n usersByIds: Record;\n blockedIds: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyBlockedUsers: FC = ({\n chatsByIds,\n usersByIds,\n blockedIds,\n unblockContact,\n}) => {\n const handleUnblockClick = useCallback((contactId: number) => {\n unblockContact({ contactId });\n }, [unblockContact]);\n\n const lang = useLang();\n\n function renderContact(contactId: number, i: number, viewportOffset: number) {\n const isPrivate = isChatPrivate(contactId);\n const user = isPrivate ? usersByIds[contactId] : undefined;\n const chat = !isPrivate ? chatsByIds[contactId] : undefined;\n\n const className = buildClassName(\n 'Chat chat-item-clickable blocked-list-item',\n isPrivate ? 'private' : 'group',\n );\n\n return (\n {\n handleUnblockClick(contactId);\n },\n }]}\n style={`top: ${(viewportOffset + i) * CHAT_HEIGHT_PX}px;`}\n >\n \n
\n

{renderText((isPrivate ? getUserFullName(user) : getChatTitle(lang, chat!)) || '')}

\n {user && user.phoneNumber && (\n
{formatPhoneNumberWithCode(user.phoneNumber)}
\n )}\n {user && !user.phoneNumber && user.username && (\n
@{user.username}
\n )}\n
\n \n );\n }\n\n return (\n
\n
\n
\n

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

\n
\n\n
\n {blockedIds && blockedIds.length ? (\n
\n {blockedIds!.map((contactId, i) => renderContact(contactId, i, 0))}\n
\n ) : blockedIds && !blockedIds.length ? (\n
\n List is empty\n
\n ) : (\n \n )}\n
\n
\n\n {\n }}\n className=\"not-implemented\"\n ariaLabel=\"Add a blocked user\"\n >\n \n \n
\n );\n};\n\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: {\n byId: chatsByIds,\n },\n users: {\n byId: usersByIds,\n },\n blocked: {\n ids,\n },\n } = global;\n\n return {\n chatsByIds,\n usersByIds,\n blockedIds: ids,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['unblockContact']),\n)(SettingsPrivacyBlockedUsers));\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport ListItem from '../../../ui/ListItem';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport renderText from '../../../common/helpers/renderText';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaEnabled: FC = ({ animatedEmoji, onScreenSelect }) => {\n const lang = useLang();\n\n return (\n
\n
\n \n\n

\n {renderText(lang('EnabledPasswordText'), ['br'])}\n

\n
\n\n
\n onScreenSelect(SettingsScreens.TwoFaChangePasswordCurrent)}\n >\n {lang('ChangePassword')}\n \n onScreenSelect(SettingsScreens.TwoFaTurnOff)}\n >\n {lang('TurnPasswordOff')}\n \n onScreenSelect(SettingsScreens.TwoFaRecoveryEmailCurrentPassword)}\n >\n {lang('SetRecoveryEmail')}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🔐'),\n };\n})(SettingsTwoFaEnabled));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../../../lib/teact/teact';\n\nimport useLang from '../../../../hooks/useLang';\n\nimport PasswordMonkey from '../../../common/PasswordMonkey';\nimport PasswordForm from '../../../common/PasswordForm';\n\ntype OwnProps = {\n error?: string;\n isLoading?: boolean;\n expectedPassword?: string;\n placeholder?: string;\n hint?: string;\n submitLabel?: string;\n clearError?: NoneToVoidFunction;\n onSubmit: (password: string) => void;\n};\n\nconst EQUAL_PASSWORD_ERROR = 'Passwords Should Be Equal';\n\nconst SettingsTwoFaPassword: FC = ({\n error,\n isLoading,\n expectedPassword,\n placeholder = 'Current Password',\n hint,\n submitLabel,\n clearError,\n onSubmit,\n}) => {\n const [validationError, setValidationError] = useState('');\n const [shouldShowPassword, setShouldShowPassword] = useState(false);\n\n const handleSubmit = useCallback((newPassword) => {\n if (expectedPassword && newPassword !== expectedPassword) {\n setValidationError(EQUAL_PASSWORD_ERROR);\n } else {\n onSubmit(newPassword);\n }\n }, [onSubmit, expectedPassword]);\n\n const handleClearError = useCallback(() => {\n if (clearError) {\n clearError();\n }\n setValidationError('');\n }, [clearError]);\n\n const lang = useLang();\n\n return (\n
\n
\n \n
\n\n
\n \n
\n
\n );\n};\n\nexport default memo(SettingsTwoFaPassword);\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\n\ntype OwnProps = {\n onStart: NoneToVoidFunction;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaStart: FC = ({ animatedEmoji, onStart }) => {\n const lang = useLang();\n\n return (\n
\n
\n \n\n

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

\n
\n\n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🔐'),\n };\n})(SettingsTwoFaStart));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../../util/environment';\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useFlag from '../../../../hooks/useFlag';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport Modal from '../../../ui/Modal';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport InputText from '../../../ui/InputText';\nimport renderText from '../../../common/helpers/renderText';\n\ntype OwnProps = {\n icon: 'hint' | 'email';\n type?: 'text' | 'email';\n isLoading?: boolean;\n error?: string;\n placeholder: string;\n shouldConfirm?: boolean;\n clearError?: NoneToVoidFunction;\n onSubmit: (value?: string) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst SettingsTwoFaSkippableForm: FC = ({\n animatedEmoji,\n type = 'text',\n isLoading,\n error,\n placeholder,\n shouldConfirm,\n clearError,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [value, setValue] = useState('');\n const [isConfirmShown, markIsConfirmShown, unmarkIsConfirmShown] = useFlag(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n const handleInputChange = (e: React.ChangeEvent) => {\n if (error && clearError) {\n clearError();\n }\n\n setValue(e.target.value);\n };\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault();\n\n if (!inputRef.current) {\n return;\n }\n\n onSubmit(value);\n };\n\n const handleSkip = () => {\n onSubmit();\n };\n\n const handleSkipConfirm = () => {\n unmarkIsConfirmShown();\n onSubmit();\n };\n\n const lang = useLang();\n\n return (\n
\n
\n \n
\n\n
\n
\n \n\n {value ? (\n \n ) : (\n \n {lang('YourEmailSkip')}\n \n )}\n \n {shouldConfirm && (\n \n {renderText(lang('YourEmailSkipWarningText'), ['br', 'simple_markdown'])}\n
\n \n {lang('YourEmailSkip')}\n \n \n {lang('Cancel')}\n \n
\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal((global, { icon }) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, icon === 'email' ? '💌' : '💡'),\n };\n})(SettingsTwoFaSkippableForm));\n","import React, { FC, memo } from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport Button from '../../../ui/Button';\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n};\n\nconst SettingsTwoFaCongratulations: FC = ({ animatedEmoji, onScreenSelect }) => {\n const lang = useLang();\n\n const handleClick = () => {\n onScreenSelect(SettingsScreens.Privacy);\n };\n\n return (\n
\n
\n \n\n

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

\n
\n\n
\n \n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '🥳'),\n };\n})(SettingsTwoFaCongratulations));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../../util/environment';\nimport { selectAnimatedEmoji } from '../../../../modules/selectors';\nimport useLang from '../../../../hooks/useLang';\n\nimport AnimatedEmoji from '../../../common/AnimatedEmoji';\nimport InputText from '../../../ui/InputText';\nimport Loading from '../../../ui/Loading';\n\ntype OwnProps = {\n isLoading?: boolean;\n error?: string;\n clearError: NoneToVoidFunction;\n onSubmit: (hint: string) => void;\n};\n\ntype StateProps = {\n animatedEmoji: ApiSticker;\n codeLength: number;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst SettingsTwoFaEmailCode: FC = ({\n animatedEmoji,\n codeLength,\n isLoading,\n error,\n clearError,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [value, setValue] = useState('');\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n const lang = useLang();\n\n const handleInputChange = (e: React.ChangeEvent) => {\n if (error && clearError) {\n clearError();\n }\n\n const newValue = e.target.value.slice(0, codeLength);\n\n if (newValue.length === codeLength) {\n onSubmit(newValue);\n }\n\n setValue(newValue);\n e.target.value = newValue;\n };\n\n return (\n
\n
\n \n
\n\n
\n \n {isLoading && }\n
\n
\n );\n};\n\nexport default memo(withGlobal((global) => {\n return {\n animatedEmoji: selectAnimatedEmoji(global, '💌'),\n codeLength: global.twoFaSettings.waitingEmailCodeLength,\n };\n})(SettingsTwoFaEmailCode));\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../../../global/types';\nimport { SettingsScreens } from '../../../../types';\n\nimport { pick } from '../../../../util/iteratees';\nimport { TwoFaDispatch, TwoFaState } from '../../../../hooks/reducers/useTwoFaReducer';\nimport useLang from '../../../../hooks/useLang';\n\nimport SettingsTwoFaEnabled from './SettingsTwoFaEnabled';\nimport SettingsTwoFaPassword from './SettingsTwoFaPassword';\nimport SettingsTwoFaStart from './SettingsTwoFaStart';\nimport SettingsTwoFaSkippableForm from './SettingsTwoFaSkippableForm';\nimport SettingsTwoFaCongratulations from './SettingsTwoFaCongratulations';\nimport SettingsTwoFaEmailCode from './SettingsTwoFaEmailCode';\n\nexport type OwnProps = {\n state: TwoFaState;\n currentScreen: SettingsScreens;\n dispatch: TwoFaDispatch;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = GlobalState['twoFaSettings'];\n\ntype DispatchProps = Pick;\n\nconst SettingsTwoFa: FC = ({\n currentScreen,\n state,\n hint,\n isLoading,\n error,\n waitingEmailCodeLength,\n dispatch,\n onScreenSelect,\n updatePassword,\n checkPassword,\n clearTwoFaError,\n updateRecoveryEmail,\n provideTwoFaEmailCode,\n clearPassword,\n}) => {\n useEffect(() => {\n if (waitingEmailCodeLength) {\n if (currentScreen === SettingsScreens.TwoFaNewPasswordEmail) {\n onScreenSelect(SettingsScreens.TwoFaNewPasswordEmailCode);\n } else if (currentScreen === SettingsScreens.TwoFaRecoveryEmail) {\n onScreenSelect(SettingsScreens.TwoFaRecoveryEmailCode);\n }\n }\n }, [currentScreen, onScreenSelect, waitingEmailCodeLength]);\n\n const handleStartWizard = useCallback(() => {\n dispatch({ type: 'reset' });\n onScreenSelect(SettingsScreens.TwoFaNewPassword);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPassword = useCallback((value: string) => {\n dispatch({ type: 'setPassword', payload: value });\n onScreenSelect(SettingsScreens.TwoFaNewPasswordConfirm);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPasswordConfirm = useCallback(() => {\n onScreenSelect(SettingsScreens.TwoFaNewPasswordHint);\n }, [onScreenSelect]);\n\n const handleNewPasswordHint = useCallback((value?: string) => {\n dispatch({ type: 'setHint', payload: value });\n onScreenSelect(SettingsScreens.TwoFaNewPasswordEmail);\n }, [dispatch, onScreenSelect]);\n\n const handleNewPasswordEmail = useCallback((value?: string) => {\n dispatch({ type: 'setEmail', payload: value });\n updatePassword({\n ...state,\n email: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updatePassword]);\n\n const handleChangePasswordCurrent = useCallback((value: string) => {\n dispatch({ type: 'setCurrentPassword', payload: value });\n checkPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaChangePasswordNew);\n },\n });\n }, [checkPassword, dispatch, onScreenSelect]);\n\n const handleChangePasswordNew = useCallback((value: string) => {\n dispatch({ type: 'setPassword', payload: value });\n onScreenSelect(SettingsScreens.TwoFaChangePasswordConfirm);\n }, [dispatch, onScreenSelect]);\n\n const handleChangePasswordConfirm = useCallback(() => {\n onScreenSelect(SettingsScreens.TwoFaChangePasswordHint);\n }, [onScreenSelect]);\n\n const handleChangePasswordHint = useCallback((value?: string) => {\n dispatch({ type: 'setHint', payload: value });\n updatePassword({\n ...state,\n hint: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updatePassword]);\n\n const handleTurnOff = useCallback((value: string) => {\n clearPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.Privacy);\n },\n });\n }, [clearPassword, onScreenSelect]);\n\n const handleRecoveryEmailCurrentPassword = useCallback((value: string) => {\n dispatch({ type: 'setCurrentPassword', payload: value });\n checkPassword({\n currentPassword: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaRecoveryEmail);\n },\n });\n }, [checkPassword, dispatch, onScreenSelect]);\n\n const handleRecoveryEmail = useCallback((value?: string) => {\n dispatch({ type: 'setEmail', payload: value });\n updateRecoveryEmail({\n ...state,\n email: value,\n onSuccess: () => {\n onScreenSelect(SettingsScreens.TwoFaCongratulations);\n },\n });\n }, [dispatch, onScreenSelect, state, updateRecoveryEmail]);\n\n const handleEmailCode = useCallback((code: string) => {\n provideTwoFaEmailCode({ code });\n }, [provideTwoFaEmailCode]);\n\n const lang = useLang();\n\n switch (currentScreen) {\n case SettingsScreens.TwoFaDisabled:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPassword:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordConfirm:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordHint:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordEmail:\n return (\n \n );\n\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n return (\n \n );\n\n case SettingsScreens.TwoFaCongratulations:\n return (\n \n );\n\n case SettingsScreens.TwoFaEnabled:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordCurrent:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordNew:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordConfirm:\n return (\n \n );\n\n case SettingsScreens.TwoFaChangePasswordHint:\n return (\n \n );\n\n case SettingsScreens.TwoFaTurnOff:\n return (\n \n );\n\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n return (\n \n );\n\n case SettingsScreens.TwoFaRecoveryEmail:\n return (\n \n );\n\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return (\n \n );\n\n default:\n return undefined;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => ({ ...global.twoFaSettings }),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'updatePassword', 'updateRecoveryEmail', 'clearPassword', 'provideTwoFaEmailCode',\n 'checkPassword', 'clearTwoFaError',\n ]),\n)(SettingsTwoFa));\n","import React, {\n FC, useCallback, useRef, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport { isChatPrivate } from '../../modules/helpers';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from './PrivateChatInfo';\nimport GroupChatInfo from './GroupChatInfo';\nimport PickerSelectedItem from './PickerSelectedItem';\nimport useInfiniteScroll from '../../hooks/useInfiniteScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\n\nimport './Picker.scss';\n\ntype OwnProps = {\n itemIds: number[];\n selectedIds: number[];\n filterValue?: string;\n filterPlaceholder?: string;\n notFoundText?: string;\n searchInputId?: string;\n isLoading?: boolean;\n onSelectedIdsChange: (ids: number[]) => void;\n onFilterChange: (value: string) => void;\n onLoadMore?: () => void;\n};\n\n// Focus slows down animation, also it breaks transition layout in Chrome\nconst FOCUS_DELAY_MS = 500;\n\nconst MAX_FULL_ITEMS = 10;\nconst ALWAYS_FULL_ITEMS_COUNT = 5;\n\nconst Picker: FC = ({\n itemIds,\n selectedIds,\n filterValue,\n filterPlaceholder,\n notFoundText,\n searchInputId,\n isLoading,\n onSelectedIdsChange,\n onFilterChange,\n onLoadMore,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const shouldMinimize = selectedIds.length > MAX_FULL_ITEMS;\n\n useEffect(() => {\n setTimeout(() => {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n });\n }, FOCUS_DELAY_MS);\n }, []);\n\n const handleItemClick = useCallback((id: number) => {\n const newSelectedIds = [...selectedIds];\n if (newSelectedIds.includes(id)) {\n newSelectedIds.splice(newSelectedIds.indexOf(id), 1);\n } else {\n newSelectedIds.push(id);\n }\n onSelectedIdsChange(newSelectedIds);\n onFilterChange('');\n }, [selectedIds, onSelectedIdsChange, onFilterChange]);\n\n const handleFilterChange = useCallback((e: React.ChangeEvent) => {\n const { value } = e.currentTarget;\n onFilterChange(value);\n }, [onFilterChange]);\n\n const [viewportIds, getMore] = useInfiniteScroll(onLoadMore, itemIds, Boolean(filterValue));\n\n const lang = useLang();\n\n return (\n
\n
\n {selectedIds.map((id, i) => (\n \n ))}\n \n
\n\n {viewportIds && viewportIds.length ? (\n \n {viewportIds.map((id) => (\n handleItemClick(id)}\n ripple\n >\n \n {isChatPrivate(id) ? (\n \n ) : (\n \n )}\n \n ))}\n \n ) : !isLoading && viewportIds && !viewportIds.length ? (\n

{notFoundText || 'Sorry, nothing found.'}

\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(Picker);\n","import React, {\n FC, memo, useCallback, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ApiPrivacySettings, SettingsScreens } from '../../../types';\n\nimport useLang from '../../../hooks/useLang';\nimport { pick } from '../../../util/iteratees';\nimport searchWords from '../../../util/searchWords';\nimport { getPrivacyKey } from './helper/privacy';\nimport {\n getChatTitle, isChatGroup, isChatPrivate, prepareChatList,\n} from '../../../modules/helpers';\n\nimport Picker from '../../common/Picker';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\n\nexport type OwnProps = {\n isAllowList?: boolean;\n screen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n chatsById: Record;\n listIds?: number[];\n orderedPinnedIds?: number[];\n archivedListIds?: number[];\n archivedPinnedIds?: number[];\n settings?: ApiPrivacySettings;\n};\n\ntype DispatchProps = Pick;\n\nconst SettingsPrivacyVisibilityExceptionList: FC = ({\n currentUserId,\n isAllowList,\n screen,\n settings,\n chatsById,\n listIds,\n orderedPinnedIds,\n archivedListIds,\n archivedPinnedIds,\n setPrivacySettings,\n onScreenSelect,\n}) => {\n const lang = useLang();\n\n const selectedContactIds = useMemo(() => {\n if (!settings) {\n return [];\n }\n\n if (isAllowList) {\n return [...settings.allowUserIds, ...settings.allowChatIds];\n } else {\n return [...settings.blockUserIds, ...settings.blockChatIds];\n }\n }, [isAllowList, settings]);\n const [searchQuery, setSearchQuery] = useState('');\n const [isSubmitShown, setIsSubmitShown] = useState(false);\n const [newSelectedContactIds, setNewSelectedContactIds] = useState(selectedContactIds);\n\n const chats = useMemo(() => {\n const activeChatArrays = listIds\n ? prepareChatList(chatsById, listIds, orderedPinnedIds, 'all')\n : undefined;\n const archivedChatArrays = archivedListIds\n ? prepareChatList(chatsById, archivedListIds, archivedPinnedIds, 'archived')\n : undefined;\n\n if (!activeChatArrays && !archivedChatArrays) {\n return undefined;\n }\n\n return [\n ...(activeChatArrays\n ? [\n ...activeChatArrays.pinnedChats,\n ...activeChatArrays.otherChats,\n ]\n : []\n ),\n ...(archivedChatArrays ? archivedChatArrays.otherChats : []),\n ];\n }, [chatsById, listIds, orderedPinnedIds, archivedListIds, archivedPinnedIds]);\n\n const displayedIds = useMemo(() => {\n if (!chats) {\n return undefined;\n }\n\n return chats\n .filter((chat) => (\n ((isChatPrivate(chat.id) && chat.id !== currentUserId) || isChatGroup(chat))\n && (\n !searchQuery\n || searchWords(getChatTitle(lang, chat), searchQuery)\n || selectedContactIds.includes(chat.id)\n )\n ))\n .map(({ id }) => id);\n }, [chats, currentUserId, lang, searchQuery, selectedContactIds]);\n\n const handleSelectedContactIdsChange = useCallback((value: number[]) => {\n setNewSelectedContactIds(value);\n setIsSubmitShown(true);\n }, []);\n\n const handleSubmit = useCallback(() => {\n setPrivacySettings({\n privacyKey: getPrivacyKey(screen),\n isAllowList: Boolean(isAllowList),\n contactsIds: newSelectedContactIds,\n });\n\n onScreenSelect(SettingsScreens.Privacy);\n }, [isAllowList, newSelectedContactIds, onScreenSelect, screen, setPrivacySettings]);\n\n return (\n
\n \n\n \n \n \n
\n );\n};\n\nfunction getCurrentPrivacySettings(global: GlobalState, screen: SettingsScreens) {\n const { privacy } = global.settings;\n switch (screen) {\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n return privacy.phoneNumber;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n return privacy.lastSeen;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n return privacy.profilePhoto;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n return privacy.forwards;\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return privacy.chatInvite;\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n (global, { screen }): StateProps => {\n const {\n chats: {\n byId: chatsById,\n listIds,\n orderedPinnedIds,\n },\n currentUserId,\n } = global;\n\n return {\n currentUserId,\n chatsById,\n listIds: listIds.active,\n orderedPinnedIds: orderedPinnedIds.active,\n archivedPinnedIds: orderedPinnedIds.archived,\n archivedListIds: listIds.archived,\n settings: getCurrentPrivacySettings(global, screen),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setPrivacySettings']),\n)(SettingsPrivacyVisibilityExceptionList));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { SettingsScreens } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport useFoldersReducer from '../../../hooks/reducers/useFoldersReducer';\nimport useTwoFaReducer from '../../../hooks/reducers/useTwoFaReducer';\n\nimport Transition from '../../ui/Transition';\nimport SettingsHeader from './SettingsHeader';\nimport SettingsMain from './SettingsMain';\nimport SettingsEditProfile from './SettingsEditProfile';\nimport SettingsFolders from './folders/SettingsFolders';\nimport SettingsGeneral from './SettingsGeneral';\nimport SettingsGeneralBackground from './SettingsGeneralBackground';\nimport SettingsGeneralBackgroundColor from './SettingsGeneralBackgroundColor';\nimport SettingsNotifications from './SettingsNotifications';\nimport SettingsPrivacy from './SettingsPrivacy';\nimport SettingsLanguage from './SettingsLanguage';\nimport SettingsPrivacyVisibility from './SettingsPrivacyVisibility';\nimport SettingsPrivacyActiveSessions from './SettingsPrivacyActiveSessions';\nimport SettingsPrivacyBlockedUsers from './SettingsPrivacyBlockedUsers';\nimport SettingsTwoFa from './twoFa/SettingsTwoFa';\nimport SettingsPrivacyVisibilityExceptionList from './SettingsPrivacyVisibilityExceptionList';\n\nimport './Settings.scss';\n\nconst TRANSITION_RENDER_COUNT = Object.keys(SettingsScreens).length / 2;\nconst TRANSITION_DURATION = 200;\n\nexport type OwnProps = {\n currentScreen: SettingsScreens;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\nconst Settings: FC = ({\n currentScreen,\n onScreenSelect,\n onReset,\n}) => {\n const [foldersState, foldersDispatch] = useFoldersReducer();\n const [twoFaState, twoFaDispatch] = useTwoFaReducer();\n\n const handleReset = useCallback(() => {\n if (\n currentScreen === SettingsScreens.FoldersCreateFolder\n || currentScreen === SettingsScreens.FoldersEditFolder\n ) {\n setTimeout(() => {\n foldersDispatch({ type: 'reset' });\n }, TRANSITION_DURATION);\n }\n\n if (\n currentScreen === SettingsScreens.FoldersIncludedChats\n || currentScreen === SettingsScreens.FoldersExcludedChats\n ) {\n if (foldersState.mode === 'create') {\n onScreenSelect(SettingsScreens.FoldersCreateFolder);\n } else {\n onScreenSelect(SettingsScreens.FoldersEditFolder);\n }\n return;\n }\n\n onReset();\n }, [\n foldersState.mode, foldersDispatch,\n currentScreen, onReset, onScreenSelect,\n ]);\n\n const handleSaveFilter = useCallback(() => {\n foldersDispatch({ type: 'saveFilters' });\n handleReset();\n }, [foldersDispatch, handleReset]);\n\n function renderCurrentSectionContent() {\n switch (currentScreen) {\n case SettingsScreens.Main:\n return (\n \n );\n case SettingsScreens.EditProfile:\n return (\n \n );\n case SettingsScreens.General:\n return (\n \n );\n case SettingsScreens.Notifications:\n return (\n \n );\n case SettingsScreens.Privacy:\n return (\n \n );\n case SettingsScreens.Language:\n return (\n \n );\n case SettingsScreens.GeneralChatBackground:\n return (\n \n );\n case SettingsScreens.GeneralChatBackgroundColor:\n return (\n \n );\n case SettingsScreens.PrivacyActiveSessions:\n return (\n \n );\n case SettingsScreens.PrivacyBlockedUsers:\n return (\n \n );\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n return (\n \n );\n\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n return (\n \n );\n\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n return (\n \n );\n\n case SettingsScreens.Folders:\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n case SettingsScreens.FoldersIncludedChats:\n case SettingsScreens.FoldersExcludedChats:\n return (\n \n );\n\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaNewPassword:\n case SettingsScreens.TwoFaNewPasswordConfirm:\n case SettingsScreens.TwoFaNewPasswordHint:\n case SettingsScreens.TwoFaNewPasswordEmail:\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n case SettingsScreens.TwoFaCongratulations:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaChangePasswordNew:\n case SettingsScreens.TwoFaChangePasswordConfirm:\n case SettingsScreens.TwoFaChangePasswordHint:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n case SettingsScreens.TwoFaRecoveryEmail:\n case SettingsScreens.TwoFaRecoveryEmailCode:\n return (\n \n );\n\n default:\n return undefined;\n }\n }\n\n function renderCurrentSection() {\n return (\n <>\n \n {renderCurrentSectionContent()}\n \n );\n }\n\n return (\n \n {renderCurrentSection}\n \n );\n};\n\nexport default memo(Settings);\n","import React, {\n FC, useEffect, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser } from '../../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport { throttle } from '../../../util/schedulers';\nimport searchWords from '../../../util/searchWords';\nimport { pick } from '../../../util/iteratees';\nimport { getUserFullName, sortUserIds } from '../../../modules/helpers';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport InfiniteScroll from '../../ui/InfiniteScroll';\nimport ListItem from '../../ui/ListItem';\nimport Loading from '../../ui/Loading';\n\nexport type OwnProps = {\n filter: string;\n};\n\ntype StateProps = {\n usersById: Record;\n contactIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst ContactList: FC = ({\n filter, usersById, contactIds, loadContactList, openChat,\n}) => {\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadContactList();\n });\n });\n\n const handleClick = useCallback(\n (id: number) => {\n openChat({ id });\n },\n [openChat],\n );\n\n const listIds = useMemo(() => {\n if (!contactIds) {\n return undefined;\n }\n\n const resultIds = filter ? contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, filter);\n }) : contactIds;\n\n return sortUserIds(resultIds, usersById);\n }, [filter, usersById, contactIds]);\n\n const [viewportIds, getMore] = useInfiniteScroll(undefined, listIds, Boolean(filter));\n\n return (\n \n {viewportIds && viewportIds.length ? (\n viewportIds.map((id) => (\n handleClick(id)}\n ripple={!IS_MOBILE_SCREEN}\n >\n \n \n ))\n ) : viewportIds && !viewportIds.length ? (\n

\n {filter.length ? 'No contacts matched your search.' : 'Contact list is empty.'}\n

\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { userIds: contactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n\n return {\n usersById,\n contactIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'openChat']),\n)(ContactList));\n","import React, {\n FC, useCallback, useEffect, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick, unique } from '../../../util/iteratees';\nimport { throttle } from '../../../util/schedulers';\nimport searchWords from '../../../util/searchWords';\nimport { getUserFullName, sortChatIds } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\n\nimport Picker from '../../common/Picker';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Button from '../../ui/Button';\n\nexport type OwnProps = {\n isChannel?: boolean;\n selectedMemberIds: number[];\n onSelectedMemberIdsChange: (ids: number[]) => void;\n onNextStep: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n currentUserId?: number;\n usersById: Record;\n chatsById: Record;\n localContactIds?: number[];\n searchQuery?: string;\n isSearching?: boolean;\n localUserIds?: number[];\n globalUserIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst NewChatStep1: FC = ({\n isChannel,\n selectedMemberIds,\n onSelectedMemberIdsChange,\n onNextStep,\n onReset,\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching,\n localUserIds,\n globalUserIds,\n loadContactList,\n setGlobalSearchQuery,\n}) => {\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadContactList();\n });\n });\n\n const handleFilterChange = useCallback((query: string) => {\n setGlobalSearchQuery({ query });\n }, [setGlobalSearchQuery]);\n\n const displayedIds = useMemo(() => {\n const contactIds = localContactIds\n ? sortChatIds(localContactIds.filter((id) => id !== currentUserId), chatsById)\n : [];\n\n if (!searchQuery) {\n return contactIds;\n }\n\n const foundContactIds = contactIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n const fullName = getUserFullName(user);\n return fullName && searchWords(fullName, searchQuery);\n });\n\n return sortChatIds(\n unique([\n ...foundContactIds,\n ...(localUserIds || []),\n ...(globalUserIds || []),\n ]),\n chatsById,\n false,\n selectedMemberIds,\n );\n }, [\n localContactIds, searchQuery, localUserIds, globalUserIds, usersById, chatsById, selectedMemberIds, currentUserId,\n ]);\n\n const handleNextStep = useCallback(() => {\n if (selectedMemberIds.length || isChannel) {\n setGlobalSearchQuery({ query: '' });\n onNextStep();\n }\n }, [selectedMemberIds.length, isChannel, setGlobalSearchQuery, onNextStep]);\n\n const lang = useLang();\n\n return (\n
\n
\n \n \n \n

{lang('GroupAddMembers')}

\n
\n
\n \n\n \n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { userIds: localContactIds } = global.contactList || {};\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n const { currentUserId } = global;\n\n const {\n query: searchQuery,\n fetchingStatus,\n globalResults,\n localResults,\n } = global.globalSearch;\n const { userIds: globalUserIds } = globalResults || {};\n const { userIds: localUserIds } = localResults || {};\n\n return {\n currentUserId,\n usersById,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching: fetchingStatus && fetchingStatus.chats,\n globalUserIds,\n localUserIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadContactList', 'setGlobalSearchQuery']),\n)(NewChatStep1));\n","import React, {\n FC, useState, useCallback, useEffect, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ChatCreationProgress } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport InputText from '../../ui/InputText';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport Button from '../../ui/Button';\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\nexport type OwnProps = {\n isChannel?: boolean;\n memberIds: number[];\n onReset: (forceReturnToChatList?: boolean) => void;\n};\n\ntype StateProps = {\n creationProgress?: ChatCreationProgress;\n creationError?: string;\n};\n\ntype DispatchProps = Pick;\n\n// TODO @implement\nconst MAX_USERS_FOR_LEGACY_CHAT = 199; // Accounting for current user\n\nconst NewChatStep2: FC = ({\n isChannel,\n memberIds,\n onReset,\n creationProgress,\n creationError,\n createGroupChat,\n createChannel,\n}) => {\n const lang = useLang();\n\n const [title, setTitle] = useState('');\n const [about, setAbout] = useState('');\n const [photo, setPhoto] = useState();\n const [error, setError] = useState();\n\n const chatTitleEmptyError = 'Chat title can\\'t be empty';\n const channelTitleEmptyError = 'Channel title can\\'t be empty';\n const chatTooManyUsersError = 'Sorry, creating supergroups is not yet supported';\n\n const isLoading = creationProgress === ChatCreationProgress.InProgress;\n\n const handleTitleChange = useCallback((e: React.ChangeEvent) => {\n const { value } = e.currentTarget;\n const newValue = value.replace(/^\\s+/, '');\n\n setTitle(newValue);\n\n if (newValue !== value) {\n e.currentTarget.value = newValue;\n }\n }, []);\n\n const handleDescriptionChange = useCallback((e: React.ChangeEvent) => {\n setAbout(e.currentTarget.value);\n }, []);\n\n const handleCreateGroup = useCallback(() => {\n if (!title.length) {\n setError(chatTitleEmptyError);\n return;\n }\n\n if (memberIds.length > MAX_USERS_FOR_LEGACY_CHAT) {\n setError(chatTooManyUsersError);\n return;\n }\n\n createGroupChat({\n title,\n photo,\n memberIds,\n });\n }, [title, memberIds, createGroupChat, photo, chatTitleEmptyError, chatTooManyUsersError]);\n\n const handleCreateChannel = useCallback(() => {\n if (!title.length) {\n setError(channelTitleEmptyError);\n return;\n }\n\n createChannel({\n title,\n about,\n photo,\n memberIds,\n });\n }, [title, createChannel, about, photo, memberIds, channelTitleEmptyError]);\n\n useEffect(() => {\n if (creationProgress === ChatCreationProgress.Complete) {\n onReset(true);\n }\n }, [creationProgress, onReset]);\n\n const renderedError = creationError || (\n error !== chatTitleEmptyError && error !== channelTitleEmptyError\n ? error\n : undefined\n );\n\n return (\n
\n
\n onReset()}\n ariaLabel=\"Return to member selection\"\n >\n \n \n

{lang(isChannel ? 'NewChannel' : 'NewGroup')}

\n
\n
\n \n \n {isChannel && (\n <>\n \n

{lang('DescriptionInfo')}

\n \n )}\n\n {renderedError && (\n

{renderedError}

\n )}\n\n {memberIds.length > 0 && (\n <>\n

{lang('GroupInfo.ParticipantCount', memberIds.length, 'i')}

\n\n
\n {memberIds.map((id) => (\n \n \n \n ))}\n
\n \n )}\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n progress: creationProgress,\n error: creationError,\n } = global.chatCreation || {};\n\n return {\n creationProgress,\n creationError,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'createGroupChat', 'createChannel',\n ]),\n)(NewChatStep2));\n","import React, {\n FC, memo, useCallback, useState,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport NewChatStep1 from './NewChatStep1';\nimport NewChatStep2 from './NewChatStep2';\n\nimport './NewChat.scss';\n\nexport type OwnProps = {\n isChannel?: boolean;\n content: LeftColumnContent;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\nconst RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\n\nconst NewChat: FC = ({\n isChannel = false,\n content,\n onContentChange,\n onReset,\n}) => {\n const [newChatMemberIds, setNewChatMemberIds] = useState([]);\n\n const handleNextStep = useCallback(() => {\n onContentChange(isChannel ? LeftColumnContent.NewChannelStep2 : LeftColumnContent.NewGroupStep2);\n }, [isChannel, onContentChange]);\n\n return (\n \n {() => {\n switch (content) {\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewGroupStep1:\n return (\n \n );\n case LeftColumnContent.NewChannelStep2:\n case LeftColumnContent.NewGroupStep2:\n return (\n \n );\n default:\n return undefined;\n }\n }}\n \n );\n};\n\nexport default memo(NewChat);\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport ChatList from './main/ChatList';\n\nimport './ArchivedChats.scss';\n\nexport type OwnProps = {\n isActive: boolean;\n onReset: () => void;\n};\n\nconst ArchivedChats: FC = ({ isActive, onReset }) => {\n const lang = useLang();\n\n return (\n
\n
\n \n \n \n

{lang('ArchivedChats')}

\n
\n \n
\n );\n};\n\nexport default memo(ArchivedChats);\n","const IGNORED_KEYS: Record = {\n Down: true,\n ArrowDown: true,\n Up: true,\n ArrowUp: true,\n Left: true,\n ArrowLeft: true,\n Right: true,\n ArrowRight: true,\n ' ': true,\n PageUp: true,\n PageDown: true,\n End: true,\n Home: true,\n Tab: true,\n};\n\nconst preventDefault = (e: Event) => {\n e.preventDefault();\n};\n\nfunction preventDefaultForScrollKeys(e: KeyboardEvent) {\n if (IGNORED_KEYS[e.key]) {\n preventDefault(e);\n }\n}\n\nexport function disableScrolling() {\n // Disable scrolling in Chrome\n document.addEventListener('wheel', preventDefault, { passive: false });\n window.ontouchmove = preventDefault; // mobile\n document.onkeydown = preventDefaultForScrollKeys;\n}\n\nexport function enableScrolling() {\n document.removeEventListener('wheel', preventDefault); // Enable scrolling in Chrome\n // eslint-disable-next-line no-null/no-null\n window.ontouchmove = null;\n // eslint-disable-next-line no-null/no-null\n document.onkeydown = null;\n}\n","import { ApiMediaFormat, ApiMessage } from '../../../../api/types';\n\nimport * as mediaLoader from '../../../../util/mediaLoader';\nimport { getMessageMediaHash, getMessagePhoto, getMessageText } from '../../../../modules/helpers';\nimport { CLIPBOARD_ITEM_SUPPORTED, copyImageToClipboard, copyTextToClipboard } from '../../../../util/clipboard';\n\ntype ICopyOptions = {\n label: string;\n handler: () => void;\n}[];\n\nexport function getMessageCopyOptions(\n message: ApiMessage, afterEffect?: () => void, onCopyLink?: () => void,\n): ICopyOptions {\n const options: ICopyOptions = [];\n const text = getMessageText(message);\n const photo = getMessagePhoto(message);\n const mediaHash = getMessageMediaHash(message, 'inline')!;\n const canImageBeCopied = photo && mediaHash && CLIPBOARD_ITEM_SUPPORTED;\n const selection = window.getSelection();\n\n if (canImageBeCopied) {\n options.push({\n label: 'lng_context_copy_image',\n handler: () => {\n mediaLoader.fetch(mediaHash, ApiMediaFormat.BlobUrl).then(copyImageToClipboard);\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n if (text) {\n // Detect if the user has selection in the current message\n const hasSelection = Boolean((\n selection\n && selection.anchorNode\n && selection.anchorNode.parentNode\n && (selection.anchorNode.parentNode as HTMLElement).closest('.Message .content-inner')\n && selection.toString().replace(/(?:\\r\\n|\\r|\\n)/g, '') !== ''\n ));\n\n options.push({\n label: getCopyLabel(hasSelection, canImageBeCopied),\n handler: () => {\n const clipboardText = hasSelection && selection ? selection.toString() : text;\n copyTextToClipboard(clipboardText);\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n if (onCopyLink) {\n options.push({\n label: 'lng_context_copy_message_link',\n handler: () => {\n onCopyLink();\n\n if (afterEffect) {\n afterEffect();\n }\n },\n });\n }\n\n return options;\n}\n\nfunction getCopyLabel(hasSelection: boolean, canImageBeCopied: boolean): string {\n if (hasSelection) {\n return 'lng_context_copy_selected';\n }\n\n if (canImageBeCopied) {\n return 'lng_context_copy_text';\n }\n\n return 'Copy';\n}\n","import React, { FC, useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { IAnchorPosition } from '../../../types';\n\nimport { getMessageCopyOptions } from './helpers/copyOptions';\nimport useContextMenuPosition from '../../../hooks/useContextMenuPosition';\nimport { dispatchHeavyAnimationEvent } from '../../../hooks/useHeavyAnimationCheck';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './MessageContextMenu.scss';\n\ntype OwnProps = {\n isOpen: boolean;\n anchor: IAnchorPosition;\n message: ApiMessage;\n canSendNow?: boolean;\n canReschedule?: boolean;\n canReply?: boolean;\n canPin?: boolean;\n canUnpin?: boolean;\n canDelete?: boolean;\n canEdit?: boolean;\n canForward?: boolean;\n canFaveSticker?: boolean;\n canUnfaveSticker?: boolean;\n canCopy?: boolean;\n canCopyLink?: boolean;\n canSelect?: boolean;\n onReply: () => void;\n onEdit: () => void;\n onPin: () => void;\n onUnpin: () => void;\n onForward: () => void;\n onDelete: () => void;\n onFaveSticker: () => void;\n onUnfaveSticker: () => void;\n onSelect: () => void;\n onSend: () => void;\n onReschedule: () => void;\n onClose: () => void;\n onCloseAnimationEnd?: () => void;\n onCopyLink?: () => void;\n};\n\nconst ANIMATION_DURATION = 200;\nconst SCROLLBAR_WIDTH = 10;\n\nconst MessageContextMenu: FC = ({\n isOpen,\n message,\n anchor,\n canSendNow,\n canReschedule,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n onReply,\n onEdit,\n onPin,\n onUnpin,\n onForward,\n onDelete,\n onFaveSticker,\n onUnfaveSticker,\n onSelect,\n onSend,\n onReschedule,\n onClose,\n onCloseAnimationEnd,\n onCopyLink,\n}) => {\n useEffect(() => {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }, [isOpen]);\n\n const copyOptions = getMessageCopyOptions(message, onClose, canCopyLink ? onCopyLink : undefined);\n\n const getTriggerElement = useCallback(() => {\n return document.querySelector(`.active > .MessageList div[data-message-id=\"${message.id}\"]`);\n }, [message.id]);\n\n const getRootElement = useCallback(\n () => document.querySelector('.active > .MessageList'),\n [],\n );\n\n const getMenuElement = useCallback(\n () => document.querySelector('.MessageContextMenu .bubble'),\n [],\n );\n\n const { positionX, positionY, style } = useContextMenuPosition(\n anchor,\n getTriggerElement,\n getRootElement,\n getMenuElement,\n SCROLLBAR_WIDTH,\n (document.querySelector('.MiddleHeader') as HTMLElement).offsetHeight,\n );\n\n const lang = useLang();\n\n return (\n \n {canSendNow && {lang('MessageScheduleSend')}}\n {canReschedule && (\n {lang('MessageScheduleEditTime')}\n )}\n {canReply && {lang('Reply')}}\n {canEdit && {lang('Edit')}}\n {canFaveSticker && (\n {lang('AddToFavorites')}\n )}\n {canUnfaveSticker && (\n {lang('Stickers.RemoveFromFavorites')}\n )}\n {canCopy && copyOptions.map((options) => (\n {lang(options.label)}\n ))}\n {canPin && {lang('DialogPin')}}\n {canUnpin && {lang('DialogUnpin')}}\n {canForward && {lang('Forward')}}\n {canSelect && {lang('Common.Select')}}\n {canDelete && {lang('Delete')}}\n \n );\n};\n\nexport default MessageContextMenu;\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum, IAnchorPosition } from '../../../types';\nimport { selectAllowedMessageActions, selectCurrentMessageList } from '../../../modules/selectors';\nimport { disableScrolling, enableScrolling } from '../../../util/scrollLock';\nimport { pick } from '../../../util/iteratees';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal';\nimport PinMessageModal from '../../common/PinMessageModal';\nimport MessageContextMenu from './MessageContextMenu';\nimport CalendarModal from '../../common/CalendarModal';\nimport { getDayStartAt } from '../../../util/dateFormat';\n\nexport type OwnProps = {\n isOpen: boolean;\n message: ApiMessage;\n album?: IAlbum;\n anchor: IAnchorPosition;\n messageListType: MessageListType;\n onClose: () => void;\n onCloseAnimationEnd: () => void;\n};\n\ntype StateProps = {\n noOptions?: boolean;\n canSendNow?: boolean;\n canReschedule?: boolean;\n canReply?: boolean;\n canPin?: boolean;\n canUnpin?: boolean;\n canDelete?: boolean;\n canEdit?: boolean;\n canForward?: boolean;\n canFaveSticker?: boolean;\n canUnfaveSticker?: boolean;\n canCopy?: boolean;\n canCopyLink?: boolean;\n canSelect?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ContextMenuContainer: FC = ({\n isOpen,\n messageListType,\n message,\n album,\n anchor,\n onClose,\n onCloseAnimationEnd,\n noOptions,\n canSendNow,\n canReschedule,\n canReply,\n canPin,\n canUnpin,\n canDelete,\n canEdit,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n setReplyingToId,\n setEditingId,\n pinMessage,\n openForwardMenu,\n faveSticker,\n unfaveSticker,\n toggleMessageSelection,\n sendScheduledMessages,\n rescheduleMessage,\n loadMessageLink,\n}) => {\n const { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd, undefined, false);\n const [isMenuOpen, setIsMenuOpen] = useState(true);\n const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);\n const [isPinModalOpen, setIsPinModalOpen] = useState(false);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n\n const handleDelete = useCallback(() => {\n setIsMenuOpen(false);\n setIsDeleteModalOpen(true);\n }, []);\n\n const closeMenu = useCallback(() => {\n setIsMenuOpen(false);\n onClose();\n }, [onClose]);\n\n const closeDeleteModal = useCallback(() => {\n setIsDeleteModalOpen(false);\n onClose();\n }, [onClose]);\n\n const closePinModal = useCallback(() => {\n setIsPinModalOpen(false);\n onClose();\n }, [onClose]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n onClose();\n }, [closeCalendar, onClose]);\n\n const handleReply = useCallback(() => {\n setReplyingToId({ messageId: message.id });\n closeMenu();\n }, [setReplyingToId, message.id, closeMenu]);\n\n const handleEdit = useCallback(() => {\n setEditingId({ messageId: message.id });\n closeMenu();\n }, [setEditingId, message.id, closeMenu]);\n\n const handlePin = useCallback(() => {\n setIsMenuOpen(false);\n setIsPinModalOpen(true);\n }, []);\n\n const handleUnpin = useCallback(() => {\n pinMessage({ messageId: message.id, isUnpin: true });\n closeMenu();\n }, [pinMessage, message.id, closeMenu]);\n\n const handleForward = useCallback(() => {\n closeMenu();\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: message.chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: message.chatId, messageIds: [message.id] });\n }\n }, [openForwardMenu, message, closeMenu, album]);\n\n const handleFaveSticker = useCallback(() => {\n closeMenu();\n faveSticker({ sticker: message.content.sticker });\n }, [closeMenu, message.content.sticker, faveSticker]);\n\n const handleUnfaveSticker = useCallback(() => {\n closeMenu();\n unfaveSticker({ sticker: message.content.sticker });\n }, [closeMenu, message.content.sticker, unfaveSticker]);\n\n const handleSelectMessage = useCallback(() => {\n const params = album && album.messages\n ? {\n messageId: message.id,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: false,\n }\n : { messageId: message.id, withShift: false };\n\n toggleMessageSelection(params);\n closeMenu();\n }, [closeMenu, message.id, toggleMessageSelection, album]);\n\n const handleScheduledMessageSend = useCallback(() => {\n sendScheduledMessages({ chatId: message.chatId, id: message.id });\n closeMenu();\n }, [closeMenu, message.chatId, message.id, sendScheduledMessages]);\n\n const handleOpenCalendar = useCallback(() => {\n setIsMenuOpen(false);\n openCalendar();\n }, [openCalendar]);\n\n const handleRescheduleMessage = useCallback((date: Date) => {\n rescheduleMessage({\n chatId: message.chatId,\n messageId: message.id,\n scheduledAt: Math.round(date.getTime() / 1000),\n });\n }, [message.chatId, message.id, rescheduleMessage]);\n\n const handleCopyLink = useCallback(() => {\n loadMessageLink({\n messageId: message.id,\n chatId: message.chatId,\n });\n closeMenu();\n }, [closeMenu, loadMessageLink, message.chatId, message.id]);\n\n useEffect(() => {\n disableScrolling();\n\n return enableScrolling;\n }, []);\n\n if (noOptions) {\n closeMenu();\n\n return undefined;\n }\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n return (\n
\n \n \n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message, messageListType }): StateProps => {\n const { threadId } = selectCurrentMessageList(global) || {};\n const {\n noOptions,\n canReply,\n canPin,\n canUnpin,\n canDelete,\n canEdit,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n } = (threadId && selectAllowedMessageActions(global, message, threadId)) || {};\n const isPinned = messageListType === 'pinned';\n const isScheduled = messageListType === 'scheduled';\n\n return {\n noOptions,\n canSendNow: isScheduled,\n canReschedule: isScheduled,\n canReply: !isPinned && !isScheduled && canReply,\n canPin: !isScheduled && canPin,\n canUnpin: !isScheduled && canUnpin,\n canDelete,\n canEdit: !isPinned && canEdit,\n canForward: !isScheduled && canForward,\n canFaveSticker: !isScheduled && canFaveSticker,\n canUnfaveSticker: !isScheduled && canUnfaveSticker,\n canCopy,\n canCopyLink: !isScheduled && canCopyLink,\n canSelect,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'pinMessage',\n 'openForwardMenu',\n 'faveSticker',\n 'unfaveSticker',\n 'toggleMessageSelection',\n 'sendScheduledMessages',\n 'rescheduleMessage',\n 'loadMessageLink',\n ]),\n)(ContextMenuContainer));\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiSticker, ApiStickerSet } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { STICKER_SIZE_MODAL } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport { selectStickerSet } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\nimport Loading from '../ui/Loading';\nimport StickerButton from './StickerButton';\n\nimport './StickerSetModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n fromSticker: ApiSticker;\n onClose: () => void;\n};\n\ntype StateProps = {\n stickerSet?: ApiStickerSet;\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst StickerSetModal: FC = ({\n isOpen,\n fromSticker,\n stickerSet,\n onClose,\n loadStickers,\n toggleStickerSet,\n sendMessage,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const lang = useLang();\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE, isDisabled: !isOpen });\n\n useEffect(() => {\n if (isOpen) {\n const { stickerSetId, stickerSetAccessHash } = fromSticker;\n loadStickers({ stickerSetId, stickerSetAccessHash });\n }\n }, [isOpen, fromSticker, loadStickers]);\n\n const handleSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n sendMessage({ sticker });\n onClose();\n }, [onClose, sendMessage]);\n\n const handleButtonClick = useCallback(() => {\n toggleStickerSet({ stickerSetId: fromSticker.stickerSetId });\n onClose();\n }, [fromSticker.stickerSetId, onClose, toggleStickerSet]);\n\n return (\n \n {stickerSet && stickerSet.stickers ? (\n <>\n
\n {stickerSet.stickers.map((sticker) => (\n \n ))}\n
\n
\n \n {lang(\n stickerSet.installedDate ? 'StickerPack.RemoveStickerCount' : 'StickerPack.AddStickerCount',\n stickerSet.count,\n 'i',\n )}\n \n
\n \n ) : (\n \n )}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { fromSticker }: OwnProps) => {\n return { stickerSet: selectStickerSet(global, fromSticker.stickerSetId) };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadStickers',\n 'toggleStickerSet',\n 'sendMessage',\n ]),\n)(StickerSetModal));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { disableScrolling, enableScrolling } from '../../util/scrollLock';\nimport { selectChat } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { isChatPrivate, getCanDeleteChat } from '../../modules/helpers';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useLang from '../../hooks/useLang';\n\nimport Portal from '../ui/Portal';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\nimport DeleteChatModal from '../common/DeleteChatModal';\n\nimport './HeaderMenuContainer.scss';\n\ntype DispatchProps = Pick;\n\nexport type OwnProps = {\n chatId: number;\n threadId: number;\n isOpen: boolean;\n anchor: IAnchorPosition;\n isChannel?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n onSubscribeChannel: () => void;\n onSearchClick: () => void;\n onClose: () => void;\n onCloseAnimationEnd: () => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isPrivate?: boolean;\n isMuted?: boolean;\n canDeleteChat?: boolean;\n};\n\nconst HeaderMenuContainer: FC = ({\n chatId,\n isOpen,\n anchor,\n isChannel,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n chat,\n isPrivate,\n isMuted,\n canDeleteChat,\n onSubscribeChannel,\n onSearchClick,\n onClose,\n onCloseAnimationEnd,\n updateChatMutedState,\n enterMessageSelectMode,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(true);\n const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);\n const { x, y } = anchor;\n\n useShowTransition(isOpen, onCloseAnimationEnd, undefined, false);\n\n const handleDelete = useCallback(() => {\n setIsMenuOpen(false);\n setIsDeleteModalOpen(true);\n }, []);\n\n const closeMenu = useCallback(() => {\n setIsMenuOpen(false);\n onClose();\n }, [onClose]);\n\n const closeDeleteModal = useCallback(() => {\n setIsDeleteModalOpen(false);\n onClose();\n }, [onClose]);\n\n const handleToggleMuteClick = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !isMuted });\n closeMenu();\n }, [chatId, closeMenu, isMuted, updateChatMutedState]);\n\n const handleSubscribe = useCallback(() => {\n onSubscribeChannel();\n closeMenu();\n }, [closeMenu, onSubscribeChannel]);\n\n const handleSearch = useCallback(() => {\n onSearchClick();\n closeMenu();\n }, [closeMenu, onSearchClick]);\n\n const handleSelectMessages = useCallback(() => {\n enterMessageSelectMode();\n closeMenu();\n }, [closeMenu, enterMessageSelectMode]);\n\n useEffect(() => {\n disableScrolling();\n\n return enableScrolling;\n }, []);\n\n const lang = useLang();\n\n return (\n \n
\n \n {IS_MOBILE_SCREEN && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {IS_MOBILE_SCREEN && canSearch && (\n \n {lang('Search')}\n \n )}\n {canMute && (\n \n {lang(isMuted ? 'ChatsUnmute' : 'ChatsMute')}\n \n )}\n {canSelect && (\n \n {lang('ReportSelectMessages')}\n \n )}\n {canLeave && (\n \n {lang(isPrivate\n ? 'Delete'\n : (canDeleteChat ? 'GroupInfo.DeleteAndExit' : (isChannel ? 'LeaveChannel' : 'Group.LeaveGroup')))}\n \n )}\n \n {chat && (\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n return {\n chat,\n isMuted: chat.isMuted,\n isPrivate: isChatPrivate(chat.id),\n canDeleteChat: getCanDeleteChat(chat),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'updateChatMutedState',\n 'enterMessageSelectMode',\n ]),\n)(HeaderMenuContainer));\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState, useLayoutEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport { debounce } from '../../util/schedulers';\nimport { selectCurrentTextSearch, selectCurrentChat } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { getDayStartAt } from '../../util/dateFormat';\n\nimport Button from '../ui/Button';\nimport SearchInput from '../ui/SearchInput';\n\nimport './MobileSearch.scss';\n\nexport type OwnProps = {\n isActive: boolean;\n};\n\ntype StateProps = {\n isActive?: boolean;\n chat?: ApiChat;\n query?: string;\n totalCount?: number;\n foundIds?: number[];\n isHistoryCalendarOpen?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nconst MobileSearchFooter: FC = ({\n isActive,\n chat,\n query,\n totalCount,\n foundIds,\n isHistoryCalendarOpen,\n setLocalTextSearchQuery,\n searchTextMessagesLocal,\n focusMessage,\n closeLocalTextSearch,\n openHistoryCalendar,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const [focusedIndex, setFocusedIndex] = useState(0);\n\n // Fix for iOS keyboard\n useEffect(() => {\n const { visualViewport } = window as any;\n if (!visualViewport) {\n return undefined;\n }\n\n const mainEl = document.getElementById('Main') as HTMLDivElement;\n const handleResize = () => {\n const { activeElement } = document;\n if (activeElement && (activeElement === inputRef.current)) {\n const { pageTop, height } = visualViewport;\n mainEl.style.transform = `translateY(${pageTop}px)`;\n mainEl.style.height = `${height}px`;\n document.documentElement.scrollTop = pageTop;\n } else {\n mainEl.style.transform = '';\n mainEl.style.height = '';\n }\n };\n\n visualViewport.addEventListener('resize', handleResize);\n\n return () => {\n visualViewport.removeEventListener('resize', handleResize);\n };\n }, []);\n\n // Focus message\n useEffect(() => {\n if (chat && foundIds && foundIds.length) {\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1] });\n setFocusedIndex(0);\n } else {\n setFocusedIndex(-1);\n }\n }, [chat, focusMessage, foundIds]);\n\n // Disable native up/down buttons on iOS\n useEffect(() => {\n Array.from(document.querySelectorAll('input')).forEach((input) => {\n input.disabled = Boolean(isActive && input !== inputRef.current);\n });\n\n Array.from(document.querySelectorAll('div[contenteditable]')).forEach((div) => {\n div.contentEditable = isActive ? 'false' : 'true';\n });\n }, [isActive]);\n\n // Blur on exit\n useEffect(() => {\n if (!isActive) {\n inputRef.current!.blur();\n }\n }, [isActive]);\n\n useLayoutEffect(() => {\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.blur();\n }, [isHistoryCalendarOpen]);\n\n const handleMessageSearchQueryChange = useCallback((newQuery: string) => {\n setLocalTextSearchQuery({ query: newQuery });\n\n if (newQuery.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleUp = useCallback(() => {\n if (chat && foundIds) {\n const newFocusIndex = focusedIndex + 1;\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1 - newFocusIndex] });\n setFocusedIndex(newFocusIndex);\n }\n }, [chat, focusedIndex, focusMessage, foundIds]);\n\n const handleDown = useCallback(() => {\n if (chat && foundIds) {\n const newFocusIndex = focusedIndex - 1;\n focusMessage({ chatId: chat.id, messageId: foundIds[foundIds.length - 1 - newFocusIndex] });\n setFocusedIndex(newFocusIndex);\n }\n }, [chat, focusedIndex, focusMessage, foundIds]);\n\n return (\n
\n
\n \n \n \n \n
\n
\n
\n {query ? (\n foundIds && foundIds.length ? (\n `${focusedIndex + 1} of ${totalCount}`\n ) : foundIds && !foundIds.length ? (\n 'No results'\n ) : (\n ''\n )\n ) : (\n openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n \n \n )}\n
\n \n \n \n \n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return {};\n }\n\n const { query, results } = selectCurrentTextSearch(global) || {};\n const { totalCount, foundIds } = results || {};\n\n return {\n chat,\n query,\n totalCount,\n foundIds,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'searchTextMessagesLocal',\n 'focusMessage',\n 'closeLocalTextSearch',\n 'openHistoryCalendar',\n ]),\n)(MobileSearchFooter));\n","export default function findInViewport(\n container: HTMLElement,\n selectorOrElements: string | NodeListOf,\n margin = 0,\n isDense = false,\n shouldContainBottom = false,\n isHorizontal = false,\n) {\n const viewportY1 = container[isHorizontal ? 'scrollLeft' : 'scrollTop'];\n const viewportY2 = viewportY1 + container[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const allElements = typeof selectorOrElements === 'string'\n ? container.querySelectorAll(selectorOrElements)\n : selectorOrElements;\n const { length } = allElements;\n const visibleIndexes: number[] = [];\n let isFound = false;\n\n for (let i = 0; i < length; i++) {\n const element = allElements[i];\n const y1 = element[isHorizontal ? 'offsetLeft' : 'offsetTop'];\n const y2 = y1 + element[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const isVisible = shouldContainBottom\n ? y2 >= viewportY1 - margin && y2 <= viewportY2 + margin\n : y1 <= viewportY2 + margin && y2 >= viewportY1 - margin;\n\n if (isVisible) {\n visibleIndexes.push(i);\n isFound = true;\n } else if (isFound && !isDense) {\n break;\n }\n }\n\n return { allElements, visibleIndexes };\n}\n","function isFullyVisible(container: HTMLElement, element: HTMLElement, isHorizontal = false) {\n const viewportY1 = container[isHorizontal ? 'scrollLeft' : 'scrollTop'];\n const viewportY2 = viewportY1 + container[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n const y1 = element[isHorizontal ? 'offsetLeft' : 'offsetTop'];\n const y2 = y1 + element[isHorizontal ? 'offsetWidth' : 'offsetHeight'];\n return y1 > viewportY1 && y2 < viewportY2;\n}\n\nexport default isFullyVisible;\n","import React, {\n FC, useCallback, useEffect, useState, useRef, memo,\n} from '../../../lib/teact/teact';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\n\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport findInViewport from '../../../util/findInViewport';\nimport isFullyVisible from '../../../util/isFullyVisible';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport cycleRestrict from '../../../util/cycleRestrict';\n\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\nimport './MentionTooltip.scss';\n\nconst VIEWPORT_MARGIN = 8;\nconst SCROLL_MARGIN = 10;\n\nfunction setItemVisible(index: number, containerRef: Record) {\n const container = containerRef.current!;\n if (!container || index < 0) {\n return;\n }\n const { visibleIndexes, allElements } = findInViewport(\n container,\n '.chat-item-clickable',\n VIEWPORT_MARGIN,\n true,\n true,\n );\n if (!allElements.length || !allElements[index]) {\n return;\n }\n const first = visibleIndexes[0];\n if (!visibleIndexes.includes(index)\n || (index === first && !isFullyVisible(container, allElements[first]))) {\n const position = index > visibleIndexes[visibleIndexes.length - 1] ? 'start' : 'end';\n fastSmoothScroll(container, allElements[index], position, SCROLL_MARGIN);\n }\n}\n\nexport type OwnProps = {\n isOpen: boolean;\n filter: string;\n onClose: () => void;\n onInsertUserName: (user: ApiUser, forceFocus?: boolean) => void;\n filteredChatMembers?: ApiChatMember[];\n usersById?: Record;\n};\n\nconst MentionTooltip: FC = ({\n isOpen,\n filter,\n onClose,\n onInsertUserName,\n usersById,\n filteredChatMembers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n\n const getSelectedIndex = useCallback((newIndex: number) => {\n if (!filteredChatMembers) {\n return -1;\n }\n const membersCount = filteredChatMembers!.length;\n return cycleRestrict(membersCount, newIndex);\n }, [filteredChatMembers]);\n\n const [selectedMentionIndex, setSelectedMentionIndex] = useState(-1);\n\n const handleArrowKey = useCallback((value: number, e: KeyboardEvent) => {\n e.preventDefault();\n setSelectedMentionIndex((index) => (getSelectedIndex(index + value)));\n }, [setSelectedMentionIndex, getSelectedIndex]);\n\n const handleUserSelect = useCallback((userId: number, forceFocus = false) => {\n const user = usersById && usersById[userId];\n if (!user) {\n return;\n }\n\n onInsertUserName(user, forceFocus);\n }, [usersById, onInsertUserName]);\n\n const handleSelectMention = useCallback((e: KeyboardEvent) => {\n if (filteredChatMembers && filteredChatMembers.length && selectedMentionIndex > -1) {\n const member = filteredChatMembers[selectedMentionIndex];\n if (member) {\n e.preventDefault();\n handleUserSelect(member.userId, true);\n }\n }\n }, [filteredChatMembers, selectedMentionIndex, handleUserSelect]);\n\n useEffect(() => (isOpen ? captureKeyboardListeners({\n onEsc: onClose,\n onUp: (e: KeyboardEvent) => handleArrowKey(-1, e),\n onDown: (e: KeyboardEvent) => handleArrowKey(1, e),\n onEnter: handleSelectMention,\n onTab: handleSelectMention,\n }) : undefined), [isOpen, onClose, handleArrowKey, handleSelectMention]);\n\n useEffect(() => {\n if (filteredChatMembers && !filteredChatMembers.length) {\n onClose();\n }\n }, [filteredChatMembers, onClose]);\n\n useEffect(() => {\n setSelectedMentionIndex(0);\n }, [filter]);\n\n useEffect(() => {\n setItemVisible(selectedMentionIndex, containerRef);\n }, [selectedMentionIndex]);\n\n const prevChatMembers = usePrevious(\n filteredChatMembers && filteredChatMembers.length\n ? filteredChatMembers\n : undefined,\n shouldRender,\n );\n const renderedChatMembers = filteredChatMembers && !filteredChatMembers.length\n ? prevChatMembers\n : filteredChatMembers;\n\n if (!shouldRender || (renderedChatMembers && !renderedChatMembers.length)) {\n return undefined;\n }\n\n const className = buildClassName(\n 'MentionTooltip composer-tooltip custom-scroll',\n transitionClassNames,\n );\n\n return (\n
\n {renderedChatMembers && renderedChatMembers.map(({ userId }, index) => (\n handleUserSelect(userId)}\n focus={selectedMentionIndex === index}\n >\n \n \n ))}\n
\n );\n};\n\nexport default memo(MentionTooltip);\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiAttachment, ApiChatMember, ApiUser } from '../../../api/types';\nimport { LangCode } from '../../../types';\n\nimport { CONTENT_TYPES_FOR_QUICK_UPLOAD, EDITABLE_INPUT_MODAL_ID } from '../../../config';\nimport { getFileExtension } from '../../common/helpers/documentInfo';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Modal from '../../ui/Modal';\nimport File from '../../common/File';\nimport MessageInput from './MessageInput';\nimport MentionTooltip from './MentionTooltip';\nimport EmojiTooltip from './EmojiTooltip.async';\n\nimport './AttachmentModal.scss';\n\nexport type OwnProps = {\n attachments: ApiAttachment[];\n caption: string;\n canSuggestMembers?: boolean;\n canSuggestEmoji?: boolean;\n currentUserId?: number;\n groupChatMembers?: ApiChatMember[];\n usersById?: Record;\n recentEmojis: string[];\n language: LangCode;\n addRecentEmoji: AnyToVoidFunction;\n loadEmojiKeywords: AnyToVoidFunction;\n onCaptionUpdate: (html: string) => void;\n onSend: () => void;\n onFileAppend: (files: File[], isQuick: boolean) => void;\n onClear: () => void;\n};\n\nconst DROP_LEAVE_TIMEOUT_MS = 150;\n\nconst AttachmentModal: FC = ({\n attachments,\n caption,\n canSuggestMembers,\n groupChatMembers,\n currentUserId,\n usersById,\n recentEmojis,\n language,\n onCaptionUpdate,\n addRecentEmoji,\n loadEmojiKeywords,\n onSend,\n onFileAppend,\n onClear,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const hideTimeoutRef = useRef(null);\n const prevAttachments = usePrevious(attachments);\n const renderingAttachments = attachments.length ? attachments : prevAttachments;\n const isOpen = Boolean(attachments.length);\n const [isHovered, markHovered, unmarkHovered] = useFlag();\n const isQuick = renderingAttachments && renderingAttachments.every((a) => a.quick);\n const lang = useLang();\n\n const {\n isMentionTooltipOpen, mentionFilter,\n closeMentionTooltip, insertMention,\n mentionFilteredMembers,\n } = useMentionTooltip(\n canSuggestMembers && isOpen,\n caption,\n onCaptionUpdate,\n EDITABLE_INPUT_MODAL_ID,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n isOpen,\n caption,\n recentEmojis,\n EDITABLE_INPUT_MODAL_ID,\n onCaptionUpdate,\n );\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClear) : undefined), [isOpen, onClear]);\n\n const sendAttachments = useCallback(() => {\n if (isOpen) {\n onSend();\n }\n }, [isOpen, onSend]);\n\n const handleDragLeave = (e: React.DragEvent) => {\n const { relatedTarget: toTarget, target: fromTarget } = e;\n\n // Esc button pressed during drag event\n if ((fromTarget as HTMLDivElement).matches('.drop-target') && !toTarget) {\n hideTimeoutRef.current = window.setTimeout(unmarkHovered, DROP_LEAVE_TIMEOUT_MS);\n }\n\n // Prevent DragLeave event from firing when the pointer moves inside the AttachmentModal drop target\n if (fromTarget && (fromTarget as HTMLElement).closest('.AttachmentModal.hovered')) {\n return;\n }\n\n if (toTarget) {\n e.stopPropagation();\n }\n\n unmarkHovered();\n };\n\n const handleFilesDrop = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n unmarkHovered();\n\n const { dataTransfer: { files } } = e;\n\n if (files && files.length) {\n const newFiles = isQuick\n ? Array.from(files).filter((file) => {\n return file.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(file.type);\n })\n : Array.from(files);\n\n onFileAppend(newFiles, false);\n }\n }, [isQuick, onFileAppend, unmarkHovered]);\n\n function handleDragOver(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n\n if (hideTimeoutRef.current) {\n window.clearTimeout(hideTimeoutRef.current);\n }\n }\n\n if (!renderingAttachments) {\n return undefined;\n }\n\n const areAllPhotos = renderingAttachments.every((a) => a.mimeType.startsWith('image/'));\n const areAllVideos = renderingAttachments.every((a) => a.mimeType.startsWith('video/'));\n\n let title = '';\n if (areAllPhotos) {\n title = lang('PreviewSender.SendPhoto', renderingAttachments.length, 'i');\n } else if (areAllVideos) {\n title = lang('PreviewSender.SendVideo', renderingAttachments.length, 'i');\n } else {\n title = lang('PreviewSender.SendFile', renderingAttachments.length, 'i');\n }\n\n function renderHeader() {\n if (!renderingAttachments) {\n return undefined;\n }\n\n return (\n
\n \n
{title}
\n \n {lang('Send')}\n \n
\n );\n }\n\n return (\n \n \n {isQuick ? (\n
\n {renderingAttachments.map((attachment) => (\n attachment.mimeType.startsWith('image/')\n ? \"\"\n :
\n ) : (\n
\n {renderingAttachments.map((attachment) => (\n \n ))}\n
\n )}\n\n
\n \n \n \n
\n \n \n );\n};\n\nexport default memo(AttachmentModal);\n","import { ChangeEvent, RefObject } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiNewPoll } from '../../../api/types';\n\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Modal from '../../ui/Modal';\nimport InputText from '../../ui/InputText';\nimport Checkbox from '../../ui/Checkbox';\nimport RadioGroup from '../../ui/RadioGroup';\n\nimport './PollModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onSend: (pollSummary: ApiNewPoll) => void;\n onClear: () => void;\n};\n\nconst MAX_LIST_HEIGHT = 320;\nconst MAX_OPTIONS_COUNT = 10;\nconst MAX_OPTION_LENGTH = 100;\nconst MAX_QUESTION_LENGTH = 255;\nconst MAX_SOLUTION_LENGTH = 200;\n\nconst PollModal: FC = ({ isOpen, onSend, onClear }) => {\n // eslint-disable-next-line no-null/no-null\n const questionInputRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const optionsListRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const solutionRef = useRef(null);\n\n const [question, setQuestion] = useState('');\n const [options, setOptions] = useState(['']);\n const [isAnonymous, setIsAnonymous] = useState(true);\n const [isMultipleAnswers, setIsMultipleAnswers] = useState(false);\n const [isQuizMode, setIsQuizMode] = useState(false);\n const [solution, setSolution] = useState();\n const [correctOption, setCorrectOption] = useState();\n const [hasErrors, setHasErrors] = useState(false);\n\n const lang = useLang();\n\n const focusInput = useCallback((ref: RefObject) => {\n if (isOpen && ref.current) {\n ref.current.focus();\n }\n }, [isOpen]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(onClear) : undefined), [isOpen, onClear]);\n useEffect(() => {\n if (!isOpen) {\n setQuestion('');\n setOptions(['']);\n setIsAnonymous(true);\n setIsMultipleAnswers(false);\n setIsQuizMode(false);\n setSolution('');\n setCorrectOption('');\n setHasErrors(false);\n }\n }, [isOpen]);\n\n useEffect(() => focusInput(questionInputRef), [focusInput, isOpen]);\n\n useLayoutEffect(() => {\n const solutionEl = solutionRef.current;\n\n if (solutionEl && solution !== solutionEl.innerHTML) {\n solutionEl.innerHTML = solution;\n }\n }, [solution]);\n\n const addNewOption = useCallback((newOptions: string[] = []) => {\n setOptions([...newOptions, '']);\n requestAnimationFrame(() => {\n const list = optionsListRef.current;\n if (!list) {\n return;\n }\n\n list.classList.toggle('overflown', list.scrollHeight > MAX_LIST_HEIGHT);\n list.scrollTo({ top: list.scrollHeight, behavior: 'smooth' });\n });\n }, []);\n\n const handleCreate = useCallback(() => {\n setHasErrors(false);\n if (!isOpen) {\n return;\n }\n\n const questionTrimmed = question.trim().substring(0, MAX_QUESTION_LENGTH);\n const optionsTrimmed = options.map((o) => o.trim().substring(0, MAX_OPTION_LENGTH)).filter((o) => o.length);\n\n if (!questionTrimmed || optionsTrimmed.length < 2) {\n setQuestion(questionTrimmed);\n if (optionsTrimmed.length) {\n if (optionsTrimmed.length < 2) {\n addNewOption(optionsTrimmed);\n } else {\n setOptions(optionsTrimmed);\n }\n } else {\n addNewOption();\n }\n setHasErrors(true);\n return;\n }\n\n if (isQuizMode && (!correctOption || !optionsTrimmed[Number(correctOption)])) {\n setHasErrors(true);\n return;\n }\n\n const answers = optionsTrimmed\n .map((text, index) => ({\n text: text.trim(),\n option: String(index),\n ...(String(index) === correctOption && { correct: true }),\n }));\n\n const payload: ApiNewPoll = {\n summary: {\n question: questionTrimmed,\n answers,\n ...(!isAnonymous && { isPublic: true }),\n ...(isMultipleAnswers && { multipleChoice: true }),\n ...(isQuizMode && { quiz: true }),\n },\n };\n\n if (isQuizMode) {\n const { text, entities } = (solution && parseMessageInput(solution.substring(0, MAX_SOLUTION_LENGTH))) || {};\n\n payload.quiz = {\n correctAnswers: [correctOption],\n ...(text && { solution: text }),\n ...(entities && { solutionEntities: entities }),\n };\n }\n\n onSend(payload);\n }, [\n isOpen,\n question,\n options,\n isQuizMode,\n correctOption,\n isAnonymous,\n isMultipleAnswers,\n onSend,\n addNewOption,\n solution,\n ]);\n\n const updateOption = useCallback((index: number, text: string) => {\n const newOptions = [...options];\n newOptions[index] = text;\n if (newOptions[newOptions.length - 1].trim().length && newOptions.length < MAX_OPTIONS_COUNT) {\n addNewOption(newOptions);\n } else {\n setOptions(newOptions);\n }\n }, [options, addNewOption]);\n\n const removeOption = useCallback((index: number) => {\n const newOptions = [...options];\n newOptions.splice(index, 1);\n setOptions(newOptions);\n requestAnimationFrame(() => {\n if (!optionsListRef.current) {\n return;\n }\n\n optionsListRef.current.classList.toggle('overflown', optionsListRef.current.scrollHeight > MAX_LIST_HEIGHT);\n });\n }, [options]);\n\n const handleCorrectOptionChange = useCallback((newValue: string) => {\n setCorrectOption(newValue);\n }, [setCorrectOption]);\n\n const handleIsAnonymousChange = useCallback((e: ChangeEvent) => {\n setIsAnonymous(e.target.checked);\n }, []);\n\n const handleMultipleAnswersChange = useCallback((e: ChangeEvent) => {\n setIsMultipleAnswers(e.target.checked);\n }, []);\n\n const handleQuizModeChange = useCallback((e: ChangeEvent) => {\n setIsQuizMode(e.target.checked);\n }, []);\n\n const handleKeyPress = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode === 13) {\n handleCreate();\n }\n }, [handleCreate]);\n\n const getQuestionError = useCallback(() => {\n if (hasErrors && !question.trim().length) {\n return lang('lng_polls_choose_question');\n }\n\n return undefined;\n }, [hasErrors, lang, question]);\n\n const getOptionsError = useCallback((index: number) => {\n const optionsTrimmed = options.map((o) => o.trim()).filter((o) => o.length);\n if (hasErrors && optionsTrimmed.length < 2 && !options[index].trim().length) {\n return lang('lng_polls_choose_answers');\n }\n return undefined;\n }, [hasErrors, lang, options]);\n\n function renderHeader() {\n return (\n
\n \n
{lang('NewPoll')}
\n \n {lang('Create')}\n \n
\n );\n }\n\n function renderOptions() {\n return options.map((option, index) => (\n
\n updateOption(index, e.currentTarget.value)}\n onKeyPress={handleKeyPress}\n />\n {index !== options.length - 1 && (\n removeOption(index)}\n >\n \n \n )}\n
\n ));\n }\n\n function renderRadioOptions() {\n return renderOptions()\n .map((label, index) => ({ value: String(index), label, hidden: index === options.length - 1 }));\n }\n\n function renderQuizNoOptionError() {\n const optionsTrimmed = options.map((o) => o.trim()).filter((o) => o.length);\n\n return isQuizMode && (!correctOption || !optionsTrimmed[Number(correctOption)]) && (\n

{lang('lng_polls_choose_correct')}

\n );\n }\n\n return (\n \n setQuestion(e.currentTarget.value)}\n onKeyPress={handleKeyPress}\n />\n
\n\n
\n

Options

\n\n {hasErrors && renderQuizNoOptionError()}\n {isQuizMode ? (\n \n ) : (\n renderOptions()\n )}\n\n
\n\n
\n\n
\n \n \n \n {isQuizMode && (\n <>\n

Solution

\n setSolution(e.currentTarget.innerHTML)}\n />\n
{lang('CreatePoll.ExplanationInfo')}
\n \n )}\n
\n \n );\n};\n\nexport default memo(PollModal);\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../util/environment';\n\nconst MENU_CLOSE_TIMEOUT = 250;\nlet closeTimeout: number | undefined;\n\nexport default function useMouseInside(\n isOpen: boolean, onClose: NoneToVoidFunction, menuCloseTimeout = MENU_CLOSE_TIMEOUT,\n) {\n const isMouseInside = useRef(false);\n\n useEffect(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n if (isOpen && !IS_TOUCH_ENV) {\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n onClose();\n }\n }, menuCloseTimeout * 2);\n }\n }, [isOpen, menuCloseTimeout, onClose]);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n }, []);\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 onClose();\n }\n }, menuCloseTimeout);\n }, [menuCloseTimeout, onClose]);\n\n return [handleMouseEnter, handleMouseLeave];\n}\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\n\nimport './EmojiButton.scss';\n\ntype OwnProps = {\n emoji: Emoji;\n focus?: boolean;\n onClick: (emoji: string, name: string) => void;\n};\n\nconst EmojiButton: FC = ({ emoji, focus, onClick }) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n // Preventing safari from losing focus on Composer MessageInput\n e.preventDefault();\n\n onClick(emoji.native, emoji.id);\n }, [emoji, onClick]);\n\n return (\n \n {IS_EMOJI_SUPPORTED\n ? {emoji.native}\n : \"\"}\n
\n );\n};\n\nexport default memo(EmojiButton);\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport windowSize from '../../../util/windowSize';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\n\nimport EmojiButton from './EmojiButton';\n\nconst EMOJIS_PER_ROW_ON_DESKTOP = 9;\nconst EMOJI_MARGIN = 4;\nconst MOBILE_CONTAINER_PADDING = 8;\nconst EMOJI_SIZE = 40;\n\ntype OwnProps = {\n category: EmojiCategory;\n index: number;\n allEmojis: AllEmojis;\n observeIntersection: ObserveFn;\n shouldRender: boolean;\n onEmojiSelect: (emoji: string, name: string) => void;\n};\n\nconst EmojiCategory: FC = ({\n category, index, allEmojis, observeIntersection, shouldRender, onEmojiSelect,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n\n const { transitionClassNames } = useShowTransition(shouldRender, undefined, undefined, 'slow');\n\n const lang = useLang();\n\n const emojisPerRow = IS_MOBILE_SCREEN\n ? Math.floor((windowSize.get().width - MOBILE_CONTAINER_PADDING) / (EMOJI_SIZE + EMOJI_MARGIN))\n : EMOJIS_PER_ROW_ON_DESKTOP;\n const height = Math.ceil(category.emojis.length / emojisPerRow) * (EMOJI_SIZE + EMOJI_MARGIN);\n\n return (\n \n

\n {lang(category.id === 'recent' ? 'RecentStickers' : `Emoji${index}`)}\n

\n \n {shouldRender && category.emojis.map((name) => {\n const emoji = allEmojis[name];\n // Some emojis have multiple skins and are represented as an Object with emojis for all skins.\n // For now, we select only the first emoji with 'neutral' skin.\n const displayedEmoji = 'id' in emoji ? emoji : emoji[1];\n\n return (\n \n );\n })}\n
\n \n );\n};\n\nexport default memo(EmojiCategory);\n","import React, {\n FC, useState, useEffect, memo, useRef, useMemo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { MENU_TRANSITION_DURATION } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport {\n EmojiModule,\n EmojiRawData,\n EmojiData,\n uncompressEmoji,\n} from '../../../util/emoji';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Loading from '../../ui/Loading';\nimport EmojiCategory from './EmojiCategory';\n\nimport './EmojiPicker.scss';\n\ntype OwnProps = {\n className?: string;\n onEmojiSelect: (emoji: string, name: string) => void;\n};\n\ntype StateProps = Pick;\ntype EmojiCategoryData = { id: string; name: string; emojis: string[] };\n\nconst ICONS_BY_CATEGORY: Record = {\n recent: 'icon-recent',\n people: 'icon-smile',\n nature: 'icon-animals',\n foods: 'icon-eats',\n activity: 'icon-sport',\n places: 'icon-car',\n objects: 'icon-lamp',\n symbols: 'icon-language',\n flags: 'icon-flag',\n};\n\nconst OPEN_ANIMATION_DELAY = 200;\n// Only a few categories are above this height.\nconst SMOOTH_SCROLL_DISTANCE = 800;\nconst FOCUS_MARGIN = 50;\nconst HEADER_BUTTON_WIDTH = 42; // px. Includes margins\nconst INTERSECTION_THROTTLE = 200;\n\nconst categoryIntersections: boolean[] = [];\n\nlet emojiDataPromise: Promise;\nlet emojiRawData: EmojiRawData;\nlet emojiData: EmojiData;\n\nconst EmojiPicker: FC = ({\n className, onEmojiSelect, recentEmojis,\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 headerRef = useRef(null);\n\n const [categories, setCategories] = useState();\n const [emojis, setEmojis] = useState();\n const [activeCategoryIndex, setActiveCategoryIndex] = useState(0);\n\n const { observe: observeIntersection } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE,\n }, (entries) => {\n entries.forEach((entry) => {\n const { id } = entry.target as HTMLDivElement;\n if (!id || !id.startsWith('emoji-category-')) {\n return;\n }\n\n const index = Number(id.replace('emoji-category-', ''));\n categoryIntersections[index] = entry.isIntersecting;\n });\n\n const intersectingWithIndexes = categoryIntersections\n .map((isIntersecting, index) => ({ index, isIntersecting }))\n .filter(({ isIntersecting }) => isIntersecting);\n\n if (!intersectingWithIndexes.length) {\n return;\n }\n\n setActiveCategoryIndex(intersectingWithIndexes[Math.floor(intersectingWithIndexes.length / 2)].index);\n });\n\n useHorizontalScroll(headerRef, !IS_MOBILE_SCREEN);\n\n // Scroll header when active set updates\n useEffect(() => {\n if (!categories) {\n return;\n }\n\n const header = headerRef.current;\n if (!header) {\n return;\n }\n\n const newLeft = activeCategoryIndex * HEADER_BUTTON_WIDTH - header.offsetWidth / 2 + HEADER_BUTTON_WIDTH / 2;\n\n fastSmoothScrollHorizontal(header, newLeft);\n }, [categories, activeCategoryIndex]);\n\n const lang = useLang();\n\n const allCategories = useMemo(() => {\n if (!categories) {\n return MEMO_EMPTY_ARRAY;\n }\n const themeCategories = [...categories];\n if (recentEmojis && recentEmojis.length) {\n themeCategories.unshift({\n id: 'recent',\n name: lang('RecentStickers'),\n emojis: recentEmojis,\n });\n }\n\n return themeCategories;\n }, [categories, lang, recentEmojis]);\n\n // Initialize data on first render.\n useEffect(() => {\n setTimeout(() => {\n const exec = () => {\n setCategories(emojiData.categories);\n\n setEmojis(emojiData.emojis as AllEmojis);\n };\n\n if (emojiData) {\n exec();\n } else {\n ensureEmojiData()\n .then(exec);\n }\n }, OPEN_ANIMATION_DELAY);\n }, []);\n\n const selectCategory = useCallback((index: number) => {\n setActiveCategoryIndex(index);\n const categoryEl = document.getElementById(`emoji-category-${index}`)!;\n fastSmoothScroll(containerRef.current!, categoryEl, 'start', FOCUS_MARGIN, SMOOTH_SCROLL_DISTANCE);\n }, []);\n\n const handleEmojiSelect = useCallback((emoji: string, name: string) => {\n onEmojiSelect(emoji, name);\n }, [onEmojiSelect]);\n\n const canRenderContents = useAsyncRendering([], MENU_TRANSITION_DURATION);\n\n function renderCategoryButton(category: EmojiCategoryData, index: number) {\n const icon = ICONS_BY_CATEGORY[category.id];\n\n return icon && (\n selectCategory(index)}\n ariaLabel={category.name}\n >\n \n \n );\n }\n\n const containerClassName = buildClassName('EmojiPicker', className);\n\n if (!emojis || !canRenderContents) {\n return (\n
\n \n
\n );\n }\n\n return (\n
\n
\n {allCategories.map(renderCategoryButton)}\n
\n
\n {allCategories.map((category, i) => (\n = i - 1 && activeCategoryIndex <= i + 1}\n onEmojiSelect={handleEmojiSelect}\n />\n ))}\n
\n
\n );\n};\n\nasync function ensureEmojiData() {\n if (!emojiDataPromise) {\n emojiDataPromise = import('emoji-data-ios/emoji-data.json') as unknown as Promise;\n emojiRawData = (await emojiDataPromise).default;\n\n emojiData = uncompressEmoji(emojiRawData);\n }\n\n return emojiDataPromise;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['recentEmojis']),\n)(EmojiPicker));\n","import React, { FC, memo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiSticker } from '../../../api/types';\nimport { StickerSetOrRecent } from '../../../types';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\n\nimport { STICKER_SIZE_PICKER } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport windowSize from '../../../util/windowSize';\nimport StickerButton from '../../common/StickerButton';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n stickerSet: StickerSetOrRecent;\n loadAndPlay: boolean;\n index: number;\n observeIntersection: ObserveFn;\n shouldRender: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n onStickerUnfave: (sticker: ApiSticker) => void;\n};\n\nconst STICKERS_PER_ROW_ON_DESKTOP = 5;\nconst STICKER_MARGIN = IS_MOBILE_SCREEN ? 8 : 16;\nconst MOBILE_CONTAINER_PADDING = 8;\n\nconst StickerSet: FC = ({\n stickerSet,\n loadAndPlay,\n index,\n observeIntersection,\n shouldRender,\n onStickerSelect,\n onStickerUnfave,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n\n const { transitionClassNames } = useShowTransition(shouldRender, undefined, undefined, 'slow');\n\n const stickersPerRow = IS_MOBILE_SCREEN\n ? Math.floor((windowSize.get().width - MOBILE_CONTAINER_PADDING) / (STICKER_SIZE_PICKER + STICKER_MARGIN))\n : STICKERS_PER_ROW_ON_DESKTOP;\n const height = Math.ceil(stickerSet.count / stickersPerRow) * (STICKER_SIZE_PICKER + STICKER_MARGIN);\n\n return (\n \n

{stickerSet.title}

\n \n {shouldRender && stickerSet.stickers && stickerSet.stickers.map((sticker) => (\n \n ))}\n \n \n );\n};\n\nexport default memo(StickerSet);\n","import React, {\n FC, useState, useEffect, memo, useRef, useMemo, useCallback,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiStickerSet, ApiSticker } from '../../../api/types';\nimport { StickerSetOrRecent } from '../../../types';\n\nimport { SLIDE_TRANSITION_DURATION, STICKER_SIZE_PICKER_HEADER } from '../../../config';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useHorizontalScroll from '../../../hooks/useHorizontalScroll';\nimport useLang from '../../../hooks/useLang';\n\nimport Loading from '../../ui/Loading';\nimport Button from '../../ui/Button';\nimport StickerButton from '../../common/StickerButton';\nimport StickerSet from './StickerSet';\nimport StickerSetCover from './StickerSetCover';\nimport StickerSetCoverAnimated from './StickerSetCoverAnimated';\n\nimport './StickerPicker.scss';\n\ntype OwnProps = {\n className: string;\n loadAndPlay: boolean;\n canSendStickers: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n};\n\ntype StateProps = {\n recentStickers: ApiSticker[];\n favoriteStickers: ApiSticker[];\n stickerSetsById: Record;\n addedSetIds?: string[];\n shouldPlay?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SMOOTH_SCROLL_DISTANCE = 500;\nconst HEADER_BUTTON_WIDTH = 52; // px (including margin)\nconst STICKER_INTERSECTION_THROTTLE = 200;\n\nconst stickerSetIntersections: boolean[] = [];\n\nconst StickerPicker: FC = ({\n className,\n loadAndPlay,\n canSendStickers,\n recentStickers,\n favoriteStickers,\n addedSetIds,\n stickerSetsById,\n shouldPlay,\n onStickerSelect,\n loadStickerSets,\n loadRecentStickers,\n loadFavoriteStickers,\n loadAddedStickers,\n addRecentSticker,\n unfaveSticker,\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 headerRef = useRef(null);\n const [activeSetIndex, setActiveSetIndex] = useState(0);\n\n const { observe: observeIntersection } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: STICKER_INTERSECTION_THROTTLE,\n }, (entries) => {\n entries.forEach((entry) => {\n const { id } = entry.target as HTMLDivElement;\n if (!id || !id.startsWith('sticker-set-')) {\n return;\n }\n\n const index = Number(id.replace('sticker-set-', ''));\n stickerSetIntersections[index] = entry.isIntersecting;\n });\n\n const intersectingWithIndexes = stickerSetIntersections\n .map((isIntersecting, index) => ({ index, isIntersecting }))\n .filter(({ isIntersecting }) => isIntersecting);\n\n if (!intersectingWithIndexes.length) {\n return;\n }\n\n setActiveSetIndex(intersectingWithIndexes[Math.floor(intersectingWithIndexes.length / 2)].index);\n });\n const { observe: observeIntersectionForCovers } = useIntersectionObserver({ rootRef: headerRef });\n\n const lang = useLang();\n\n const areAddedLoaded = Boolean(addedSetIds);\n\n const allSets = useMemo(() => {\n if (!addedSetIds) {\n return MEMO_EMPTY_ARRAY;\n }\n\n return [\n {\n id: 'recent',\n title: lang('RecentStickers'),\n stickers: recentStickers,\n count: recentStickers.length,\n },\n {\n id: 'favorite',\n title: lang('FavoriteStickers'),\n stickers: favoriteStickers,\n count: favoriteStickers.length,\n },\n ...addedSetIds.map((id) => stickerSetsById[id]).filter(Boolean),\n ];\n }, [addedSetIds, lang, recentStickers, favoriteStickers, stickerSetsById]);\n\n const noPopulatedSets = useMemo(() => (\n areAddedLoaded\n && allSets.filter((set) => set.stickers && set.stickers.length).length === 0\n ), [allSets, areAddedLoaded]);\n\n useEffect(() => {\n if (loadAndPlay) {\n loadStickerSets();\n loadRecentStickers();\n loadFavoriteStickers();\n }\n }, [loadAndPlay, loadFavoriteStickers, loadRecentStickers, loadStickerSets]);\n\n useEffect(() => {\n if (addedSetIds && addedSetIds.length) {\n loadAddedStickers();\n }\n }, [addedSetIds, loadAddedStickers]);\n\n useHorizontalScroll(headerRef);\n\n // Scroll container and header when active set changes\n useEffect(() => {\n if (!areAddedLoaded) {\n return;\n }\n\n const header = headerRef.current;\n if (!header) {\n return;\n }\n\n const newLeft = activeSetIndex * HEADER_BUTTON_WIDTH - (header.offsetWidth / 2 - HEADER_BUTTON_WIDTH / 2);\n\n fastSmoothScrollHorizontal(header, newLeft);\n }, [areAddedLoaded, activeSetIndex]);\n\n const selectStickerSet = useCallback((index: number) => {\n setActiveSetIndex(index);\n const stickerSetEl = document.getElementById(`sticker-set-${index}`)!;\n fastSmoothScroll(containerRef.current!, stickerSetEl, 'start', undefined, SMOOTH_SCROLL_DISTANCE);\n }, []);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n onStickerSelect(sticker);\n addRecentSticker({ sticker });\n }, [addRecentSticker, onStickerSelect]);\n\n const handleStickerUnfave = useCallback((sticker: ApiSticker) => {\n unfaveSticker({ sticker });\n }, [unfaveSticker]);\n\n const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION);\n\n function renderCover(stickerSet: StickerSetOrRecent, index: number) {\n const firstSticker = stickerSet.stickers && stickerSet.stickers[0];\n const buttonClassName = buildClassName(\n 'symbol-set-button sticker-set-button',\n index === activeSetIndex && 'activated',\n );\n\n if (stickerSet.id === 'recent' || stickerSet.id === 'favorite' || stickerSet.hasThumbnail || !firstSticker) {\n return (\n selectStickerSet(index)}\n >\n {stickerSet.id === 'recent' ? (\n \n ) : stickerSet.id === 'favorite' ? (\n \n ) : stickerSet.isAnimated ? (\n \n ) : (\n \n )}\n \n );\n } else {\n return (\n \n );\n }\n }\n\n const fullClassName = buildClassName('StickerPicker', className);\n\n if (!areAddedLoaded || !canRenderContents || noPopulatedSets || !canSendStickers) {\n return (\n
\n {!canSendStickers ? (\n
Sending stickers is not allowed in this chat.
\n ) : noPopulatedSets ? (\n
You have no saved Stickers.
\n ) : (\n \n )}\n
\n );\n }\n\n return (\n
\n \n {allSets.map(renderCover)}\n
\n
\n {allSets.map((stickerSet, i) => (\n = i - 1 && activeSetIndex <= i + 1}\n onStickerSelect={handleStickerSelect}\n onStickerUnfave={handleStickerUnfave}\n />\n ))}\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n setsById,\n added,\n recent,\n favorite,\n } = global.stickers;\n\n return {\n recentStickers: recent.stickers,\n favoriteStickers: favorite.stickers,\n stickerSetsById: setsById,\n addedSetIds: added.setIds,\n shouldPlay: global.settings.byKey.shouldLoopStickers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadStickerSets',\n 'loadRecentStickers',\n 'loadFavoriteStickers',\n 'loadAddedStickers',\n 'addRecentSticker',\n 'unfaveSticker',\n ]),\n)(StickerPicker));\n","import React, {\n FC, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { ApiMediaFormat, ApiVideo } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useTransitionForMedia from '../../hooks/useTransitionForMedia';\nimport useVideoCleanup from '../../hooks/useVideoCleanup';\nimport useBuffering from '../../hooks/useBuffering';\nimport useCanvasBlur from '../../hooks/useCanvasBlur';\n\nimport Spinner from '../ui/Spinner';\n\nimport './GifButton.scss';\n\ntype OwnProps = {\n gif: ApiVideo;\n observeIntersection: ObserveFn;\n isDisabled?: boolean;\n onClick: (gif: ApiVideo) => void;\n};\n\nconst GifButton: FC = ({\n gif, observeIntersection, isDisabled, onClick,\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 hasThumbnail = gif.thumbnail && !!gif.thumbnail.dataUri;\n const localMediaHash = `gif${gif.id}`;\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n const loadAndPlay = isIntersecting && !isDisabled;\n const previewBlobUrl = useMedia(`${localMediaHash}?size=m`, !loadAndPlay, ApiMediaFormat.BlobUrl);\n const thumbRef = useCanvasBlur(gif.thumbnail && gif.thumbnail.dataUri, Boolean(previewBlobUrl));\n const videoData = useMedia(localMediaHash, !loadAndPlay, ApiMediaFormat.BlobUrl);\n const shouldRenderVideo = Boolean(loadAndPlay && videoData);\n const { transitionClassNames } = useTransitionForMedia(hasThumbnail || previewBlobUrl || videoData, 'slow');\n const { isBuffered, bufferingHandlers } = useBuffering(true);\n const shouldRenderSpinner = loadAndPlay && !isBuffered;\n\n useVideoCleanup(videoRef, [shouldRenderVideo]);\n\n const handleClick = useCallback(\n () => onClick({\n ...gif,\n blobUrl: videoData,\n }),\n [onClick, gif, videoData],\n );\n\n const className = buildClassName(\n 'GifButton',\n gif.width && gif.height && gif.width < gif.height ? 'vertical' : 'horizontal',\n transitionClassNames,\n localMediaHash,\n );\n\n return (\n \n {hasThumbnail && (\n \n )}\n {!hasThumbnail && previewBlobUrl && (\n \n )}\n {(shouldRenderVideo || previewBlobUrl) && (\n \n \n \n )}\n {shouldRenderSpinner && (\n \n )}\n \n );\n};\n\nexport default memo(GifButton);\n","import React, {\n FC, useEffect, memo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiVideo } from '../../../api/types';\n\nimport { SLIDE_TRANSITION_DURATION } from '../../../config';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\n\nimport Loading from '../../ui/Loading';\nimport GifButton from '../../common/GifButton';\n\nimport './GifPicker.scss';\n\ntype OwnProps = {\n className: string;\n loadAndPlay: boolean;\n canSendGifs: boolean;\n onGifSelect: (gif: ApiVideo) => void;\n};\n\ntype StateProps = {\n savedGifs?: ApiVideo[];\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_DEBOUNCE = 300;\n\nconst GifPicker: FC = ({\n className,\n loadAndPlay,\n canSendGifs,\n savedGifs,\n onGifSelect,\n loadSavedGifs,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE });\n\n useEffect(() => {\n if (loadAndPlay) {\n loadSavedGifs();\n }\n }, [loadAndPlay, loadSavedGifs]);\n\n const canRenderContents = useAsyncRendering([], SLIDE_TRANSITION_DURATION);\n\n return (\n
\n {!canSendGifs ? (\n
Sending GIFs is not allowed in this chat.
\n ) : canRenderContents && savedGifs && savedGifs.length ? (\n savedGifs.map((gif) => (\n \n ))\n ) : canRenderContents && savedGifs ? (\n
No saved GIFs.
\n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n return {\n savedGifs: global.gifs.saved.gifs,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadSavedGifs']),\n)(GifPicker));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\ntype OwnProps = {\n activeTab: SymbolMenuTabs;\n onSwitchTab: (tab: SymbolMenuTabs) => void;\n onRemoveSymbol: () => void;\n onSearchOpen: (type: 'stickers' | 'gifs') => void;\n};\n\nexport enum SymbolMenuTabs {\n 'Emoji',\n 'Stickers',\n 'GIFs',\n}\n\n// Getting enum string values for display in Tabs.\n// See: https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\nexport const SYMBOL_MENU_TAB_TITLES = Object.values(SymbolMenuTabs)\n .filter((value): value is string => typeof value === 'string');\n\nconst SYMBOL_MENU_TAB_ICONS = {\n [SymbolMenuTabs.Emoji]: 'icon-smile',\n [SymbolMenuTabs.Stickers]: 'icon-stickers',\n [SymbolMenuTabs.GIFs]: 'icon-gifs',\n};\n\nconst SymbolMenuFooter: FC = ({\n activeTab, onSwitchTab, onRemoveSymbol, onSearchOpen,\n}) => {\n const lang = useLang();\n\n function renderTabButton(tab: SymbolMenuTabs) {\n return (\n onSwitchTab(tab)}\n ariaLabel={SYMBOL_MENU_TAB_TITLES[tab]}\n round\n faded\n color=\"translucent\"\n >\n \n \n );\n }\n\n const handleSearchOpen = useCallback(() => {\n onSearchOpen(activeTab === SymbolMenuTabs.Stickers ? 'stickers' : 'gifs');\n }, [activeTab, onSearchOpen]);\n\n function stopPropagation(event: any) {\n event.stopPropagation();\n }\n\n return (\n
\n {activeTab !== SymbolMenuTabs.Emoji && (\n \n \n \n )}\n\n {renderTabButton(SymbolMenuTabs.Emoji)}\n {renderTabButton(SymbolMenuTabs.Stickers)}\n {renderTabButton(SymbolMenuTabs.GIFs)}\n\n {activeTab === SymbolMenuTabs.Emoji && (\n \n \n \n )}\n
\n );\n};\n\nexport default memo(SymbolMenuFooter);\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiSticker, ApiVideo } from '../../../api/types';\n\nimport { IAllowedAttachmentOptions } from '../../../modules/helpers';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV } from '../../../util/environment';\nimport { fastRaf } from '../../../util/schedulers';\nimport buildClassName from '../../../util/buildClassName';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Menu from '../../ui/Menu';\nimport Transition from '../../ui/Transition';\nimport EmojiPicker from './EmojiPicker';\nimport StickerPicker from './StickerPicker';\nimport GifPicker from './GifPicker';\nimport SymbolMenuFooter, { SYMBOL_MENU_TAB_TITLES, SymbolMenuTabs } from './SymbolMenuFooter';\nimport Portal from '../../ui/Portal';\n\nimport './SymbolMenu.scss';\n\nconst ANIMATION_DURATION = 350;\n\nexport type OwnProps = {\n isOpen: boolean;\n allowedAttachmentOptions: IAllowedAttachmentOptions;\n onLoad: () => void;\n onClose: () => void;\n onEmojiSelect: (emoji: string) => void;\n onStickerSelect: (sticker: ApiSticker) => void;\n onGifSelect: (gif: ApiVideo) => void;\n onRemoveSymbol: () => void;\n onSearchOpen: (type: 'stickers' | 'gifs') => void;\n addRecentEmoji: AnyToVoidFunction;\n};\n\nlet isActivated = false;\n\nconst SymbolMenu: FC = ({\n isOpen, allowedAttachmentOptions,\n onLoad, onClose,\n onEmojiSelect, onStickerSelect, onGifSelect,\n onRemoveSymbol, onSearchOpen, addRecentEmoji,\n}) => {\n const [activeTab, setActiveTab] = useState(0);\n const [recentEmojis, setRecentEmojis] = useState([]);\n\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, onClose, false, false);\n\n if (!isActivated && isOpen) {\n isActivated = true;\n }\n\n useEffect(() => {\n onLoad();\n }, [onLoad]);\n\n useLayoutEffect(() => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n if (isOpen) {\n document.body.classList.add('enable-symbol-menu-transforms');\n document.body.classList.add('is-symbol-menu-open');\n }\n\n return () => {\n if (isOpen) {\n fastRaf(() => {\n document.body.classList.remove('is-symbol-menu-open');\n setTimeout(() => {\n document.body.classList.remove('enable-symbol-menu-transforms');\n }, ANIMATION_DURATION);\n });\n }\n };\n }, [isOpen]);\n\n const recentEmojisRef = useRef(recentEmojis);\n recentEmojisRef.current = recentEmojis;\n useEffect(() => {\n if (!recentEmojisRef.current.length) {\n return;\n }\n\n recentEmojisRef.current.forEach((name) => {\n addRecentEmoji({ emoji: name });\n });\n\n setRecentEmojis([]);\n }, [isOpen, activeTab, addRecentEmoji]);\n\n const handleEmojiSelect = useCallback((emoji: string, name: string) => {\n setRecentEmojis((emojis) => {\n return [...emojis, name];\n });\n\n onEmojiSelect(emoji);\n }, [onEmojiSelect]);\n\n const handleSearch = useCallback((type: 'stickers' | 'gifs') => {\n onClose();\n onSearchOpen(type);\n }, [onClose, onSearchOpen]);\n\n const lang = useLang();\n\n const { canSendStickers, canSendGifs } = allowedAttachmentOptions;\n\n function renderContent(isActive: boolean, isFrom: boolean) {\n switch (activeTab) {\n case SymbolMenuTabs.Emoji:\n return (\n \n );\n case SymbolMenuTabs.Stickers:\n return (\n \n );\n case SymbolMenuTabs.GIFs:\n return (\n \n );\n }\n\n return undefined;\n }\n\n function stopPropagation(event: any) {\n event.stopPropagation();\n }\n\n const content = (\n <>\n
\n {isActivated && (\n \n {renderContent}\n \n )}\n
\n {IS_MOBILE_SCREEN && (\n \n \n \n )}\n \n \n );\n\n if (IS_MOBILE_SCREEN) {\n if (!shouldRender) {\n return undefined;\n }\n\n const className = buildClassName(\n 'SymbolMenu mobile-menu',\n transitionClassNames,\n );\n\n return (\n \n
\n {content}\n
\n
\n );\n }\n\n return (\n \n {content}\n \n );\n};\n\nexport default memo(SymbolMenu);\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { CONTENT_TYPES_FOR_QUICK_UPLOAD } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { openSystemFilesDialog } from '../../../util/systemFilesDialog';\nimport { IAllowedAttachmentOptions } from '../../../modules/helpers';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './AttachMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n allowedAttachmentOptions: IAllowedAttachmentOptions;\n onFileSelect: (files: File[], isQuick: boolean) => void;\n onPollCreate: () => void;\n onClose: () => void;\n};\n\nconst AttachMenu: FC = ({\n isOpen, allowedAttachmentOptions, onFileSelect, onPollCreate, onClose,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\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 CONTENT_TYPES_FOR_QUICK_UPLOAD,\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 const { canAttachMedia, canAttachPolls } = allowedAttachmentOptions;\n\n return (\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\nexport default memo(AttachMenu);\n","import React, {\n FC, memo, useEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { STICKER_SIZE_PICKER } from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\n\nimport Loading from '../../ui/Loading';\nimport StickerButton from '../../common/StickerButton';\n\nimport './StickerTooltip.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onStickerSelect: (sticker: ApiSticker) => void;\n};\n\ntype StateProps = {\n stickers?: ApiSticker[];\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst StickerTooltip: FC = ({\n isOpen,\n onStickerSelect,\n stickers,\n clearStickersForEmoji,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n const prevStickers = usePrevious(stickers, true);\n const displayedStickers = stickers || prevStickers;\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE });\n\n useEffect(() => (isOpen ? captureEscKeyListener(clearStickersForEmoji) : undefined), [isOpen, clearStickersForEmoji]);\n\n const handleMouseEnter = () => {\n document.body.classList.add('no-select');\n };\n\n const handleMouseLeave = () => {\n document.body.classList.remove('no-select');\n };\n\n const className = buildClassName(\n 'StickerTooltip composer-tooltip custom-scroll',\n transitionClassNames,\n !(displayedStickers && displayedStickers.length) && 'hidden',\n );\n\n return (\n \n {shouldRender && displayedStickers ? (\n displayedStickers.map((sticker) => (\n \n ))\n ) : shouldRender ? (\n \n ) : undefined}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { stickers } = global.stickers.forEmoji;\n\n return { stickers };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['clearStickersForEmoji']),\n)(StickerTooltip));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../modules/selectors';\nimport useMouseInside from '../../../hooks/useMouseInside';\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\ntype DispatchProps = Pick;\n\nconst BotKeyboardMenu: FC = ({\n isOpen, message, onClose, clickInlineButton,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\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 (setGlobal, actions): DispatchProps => pick(actions, [\n 'clickInlineButton',\n ]),\n)(BotKeyboardMenu));\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useLang from '../../../hooks/useLang';\n\nimport Menu from '../../ui/Menu';\nimport MenuItem from '../../ui/MenuItem';\n\nimport './CustomSendMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onSilentSend?: NoneToVoidFunction;\n onScheduleSend?: NoneToVoidFunction;\n onClose: NoneToVoidFunction;\n onCloseAnimationEnd?: NoneToVoidFunction;\n};\n\nconst CustomSendMenu: FC = ({\n isOpen, onSilentSend, onScheduleSend, onClose, onCloseAnimationEnd,\n}) => {\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n\n const lang = useLang();\n\n return (\n \n {onSilentSend && {lang('SendWithoutSound')}}\n {onScheduleSend && {lang('ScheduleMessage')}}\n \n );\n};\n\nexport default memo(CustomSendMenu);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport cycleRestrict from '../../../util/cycleRestrict';\nimport captureKeyboardListeners from '../../../util/captureKeyboardListeners';\nimport findInViewport from '../../../util/findInViewport';\nimport isFullyVisible from '../../../util/isFullyVisible';\nimport fastSmoothScrollHorizontal from '../../../util/fastSmoothScrollHorizontal';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevDuringAnimation from '../../../hooks/usePrevDuringAnimation';\n\nimport Loading from '../../ui/Loading';\nimport EmojiButton from './EmojiButton';\n\nimport './EmojiTooltip.scss';\nimport { LangCode } from '../../../types';\n\nconst VIEWPORT_MARGIN = 8;\nconst EMOJI_BUTTON_WIDTH = 44;\n\nfunction setItemVisible(index: number, containerRef: Record) {\n const container = containerRef.current!;\n if (!container) {\n return;\n }\n\n const { visibleIndexes, allElements } = findInViewport(\n container,\n '.EmojiButton',\n VIEWPORT_MARGIN,\n true,\n true,\n true,\n );\n\n if (!allElements.length || !allElements[index]) {\n return;\n }\n const first = visibleIndexes[0];\n if (!visibleIndexes.includes(index)\n || (index === first && !isFullyVisible(container, allElements[first], true))) {\n const position = index > visibleIndexes[visibleIndexes.length - 1] ? 'start' : 'end';\n const newLeft = position === 'start' ? index * EMOJI_BUTTON_WIDTH : 0;\n\n fastSmoothScrollHorizontal(container, newLeft);\n }\n}\n\nexport type OwnProps = {\n isOpen: boolean;\n language: LangCode;\n onEmojiSelect: (text: string) => void;\n onClose: NoneToVoidFunction;\n addRecentEmoji: AnyToVoidFunction;\n loadEmojiKeywords: AnyToVoidFunction;\n emojis: Emoji[];\n};\n\nconst CLOSE_DURATION = 350;\n\nconst EmojiTooltip: FC = ({\n isOpen,\n language,\n emojis,\n onClose,\n onEmojiSelect,\n addRecentEmoji,\n loadEmojiKeywords,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const { shouldRender, transitionClassNames } = useShowTransition(isOpen, undefined, undefined, false);\n const listEmojis: Emoji[] = usePrevDuringAnimation(emojis.length ? emojis : undefined, CLOSE_DURATION) || [];\n\n const [selectedIndex, setSelectedIndex] = useState(-1);\n\n useEffect(() => {\n loadEmojiKeywords({ language });\n }, [loadEmojiKeywords, language]);\n\n useEffect(() => {\n setSelectedIndex(0);\n }, [emojis]);\n\n useEffect(() => {\n setItemVisible(selectedIndex, containerRef);\n }, [selectedIndex]);\n\n const getSelectedIndex = useCallback((newIndex: number) => {\n if (!emojis.length) {\n return -1;\n }\n\n const emojisCount = emojis.length;\n return cycleRestrict(emojisCount, newIndex);\n }, [emojis]);\n\n\n const handleArrowKey = useCallback((value: number, e: KeyboardEvent) => {\n e.preventDefault();\n setSelectedIndex((index) => (getSelectedIndex(index + value)));\n }, [setSelectedIndex, getSelectedIndex]);\n\n const handleSelectEmoji = useCallback((e: KeyboardEvent) => {\n if (emojis.length && selectedIndex > -1) {\n const emoji = emojis[selectedIndex];\n if (emoji) {\n e.preventDefault();\n onEmojiSelect(emoji.native);\n addRecentEmoji({ emoji: emoji.id });\n }\n }\n }, [addRecentEmoji, emojis, onEmojiSelect, selectedIndex]);\n\n useEffect(() => (isOpen ? captureKeyboardListeners({\n onEsc: onClose,\n onLeft: (e: KeyboardEvent) => handleArrowKey(-1, e),\n onRight: (e: KeyboardEvent) => handleArrowKey(1, e),\n onEnter: handleSelectEmoji,\n }) : undefined), [handleArrowKey, handleSelectEmoji, isOpen, onClose]);\n\n const handleMouseEnter = () => {\n document.body.classList.add('no-select');\n };\n\n const handleMouseLeave = () => {\n document.body.classList.remove('no-select');\n };\n\n const className = buildClassName(\n 'EmojiTooltip composer-tooltip custom-scroll-x',\n transitionClassNames,\n );\n\n return (\n \n {shouldRender && listEmojis ? (\n listEmojis.map((emoji, index) => (\n \n ))\n ) : shouldRender ? (\n \n ) : undefined}\n \n );\n};\n\nexport default memo(EmojiTooltip);\n","import React, {\n FC, useMemo, memo, useRef,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiUser, ApiChat } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\n\nimport {\n selectUser,\n selectChatMessages,\n selectChat,\n selectCurrentTextSearch,\n} from '../../modules/selectors';\nimport {\n getMessageSummaryText,\n getChatTitle,\n getUserFullName,\n isChatChannel,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport { orderBy, pick } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport ListItem from '../ui/ListItem';\nimport LastMessageMeta from '../common/LastMessageMeta';\nimport Avatar from '../common/Avatar';\n\nimport './RightSearch.scss';\n\nexport type OwnProps = {\n chatId: number;\n threadId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n messagesById?: Record;\n query?: string;\n totalCount?: number;\n foundIds?: number[];\n};\n\ntype DispatchProps = Pick;\n\ninterface Result {\n message: ApiMessage;\n senderUser?: ApiUser;\n senderChat?: ApiChat;\n onClick: NoneToVoidFunction;\n}\n\nconst RightSearch: FC = ({\n chatId,\n threadId,\n chat,\n messagesById,\n query,\n totalCount,\n foundIds,\n searchTextMessagesLocal,\n focusMessage,\n}) => {\n const lang = useLang();\n\n const foundResults = useMemo(() => {\n if (!query || !foundIds || !foundIds.length || !messagesById) {\n return MEMO_EMPTY_ARRAY;\n }\n\n const results = foundIds.map((id) => {\n const message = messagesById[id];\n if (!message) {\n return undefined;\n }\n\n const senderUser = message.senderId ? selectUser(getGlobal(), message.senderId) : undefined;\n\n let senderChat;\n if (chat && isChatChannel(chat)) {\n senderChat = chat;\n } else if (message.forwardInfo) {\n const { isChannelPost, fromChatId } = message.forwardInfo;\n senderChat = isChannelPost && fromChatId ? selectChat(getGlobal(), fromChatId) : undefined;\n } else {\n senderChat = message.senderId ? selectChat(getGlobal(), message.senderId) : undefined;\n }\n\n return {\n message,\n senderUser,\n senderChat,\n onClick: () => focusMessage({ chatId, threadId, messageId: id }),\n };\n }).filter(Boolean) as Result[];\n\n return orderBy(results, ({ message }) => message.date, 'desc');\n }, [chatId, threadId, focusMessage, foundIds, chat, messagesById, query]);\n\n const renderSearchResult = ({\n message, senderUser, senderChat, onClick,\n }: Result) => {\n const title = senderChat ? getChatTitle(lang, senderChat) : getUserFullName(senderUser);\n const text = getMessageSummaryText(lang, message);\n\n return (\n \n \n
\n
\n

{title && renderText(title)}

\n \n
\n
\n {renderText(text, ['emoji', 'highlight'], { highlight: query })}\n
\n
\n \n );\n };\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const handleKeyDown = useKeyboardListNavigation(containerRef, true, (index) => {\n if (foundResults && foundResults[index]) {\n foundResults[index].onClick();\n }\n }, '.ListItem-button', true);\n\n return (\n \n

\n {!query ? (\n lang('lng_dlg_search_for_messages')\n ) : (totalCount === 0 || !foundResults.length) ? (\n lang('lng_search_no_results')\n ) : totalCount === 1 ? (\n '1 message found'\n ) : (\n `${(foundResults.length && (totalCount || foundResults.length))} messages found`\n )}\n

\n {foundResults.map(renderSearchResult)}\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const messagesById = chat && selectChatMessages(global, chat.id);\n if (!chat || !messagesById) {\n return {};\n }\n\n const { query, results } = selectCurrentTextSearch(global) || {};\n const { totalCount, foundIds } = results || {};\n\n return {\n chat,\n messagesById,\n query,\n totalCount,\n foundIds,\n };\n },\n (global, actions): DispatchProps => pick(actions, ['searchTextMessagesLocal', 'focusMessage']),\n)(RightSearch));\n","import React, {\n FC, useEffect, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiStickerSet } from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport { ObserveFn } from '../../hooks/useIntersectionObserver';\n\nimport { STICKER_SIZE_SEARCH } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport { selectShouldLoopStickers, selectStickerSet } from '../../modules/selectors';\nimport useFlag from '../../hooks/useFlag';\nimport useOnChange from '../../hooks/useOnChange';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport StickerButton from '../common/StickerButton';\nimport StickerSetModal from '../common/StickerSetModal.async';\nimport Spinner from '../ui/Spinner';\n\ntype OwnProps = {\n stickerSetId: string;\n observeIntersection: ObserveFn;\n isSomeModalOpen: boolean;\n onModalToggle: (isOpen: boolean) => void;\n};\n\ntype StateProps = {\n set?: ApiStickerSet;\n shouldPlay?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst STICKERS_TO_DISPLAY = 5;\n\nconst StickerSetResult: FC = ({\n stickerSetId, observeIntersection, set, shouldPlay,\n loadStickers, toggleStickerSet, isSomeModalOpen, onModalToggle,\n}) => {\n const lang = useLang();\n const isAdded = set && Boolean(set.installedDate);\n const areStickersLoaded = Boolean(set && set.stickers);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n useOnChange(() => {\n onModalToggle(isModalOpen);\n }, [isModalOpen, onModalToggle]);\n\n const displayedStickers = useMemo(() => {\n if (!set) {\n return [];\n }\n\n const coverStickerIds = (set.covers || []).map(({ id }) => id);\n const otherStickers = set.stickers ? set.stickers.filter(({ id }) => !coverStickerIds.includes(id)) : [];\n\n return [...set.covers || [], ...otherStickers].slice(0, STICKERS_TO_DISPLAY);\n }, [set]);\n\n useEffect(() => {\n // Featured stickers are initialized with one sticker in collection (cover of SickerSet)\n if (!areStickersLoaded && displayedStickers.length < STICKERS_TO_DISPLAY) {\n loadStickers({ stickerSetId });\n }\n }, [areStickersLoaded, displayedStickers.length, loadStickers, stickerSetId]);\n\n const handleAddClick = useCallback(() => {\n toggleStickerSet({ stickerSetId });\n }, [toggleStickerSet, stickerSetId]);\n\n if (!set) {\n return undefined;\n }\n\n const canRenderStickers = displayedStickers.length > 0;\n\n return (\n
\n
\n
\n

{set.title}

\n

{lang('Stickers', set.count, 'i')}

\n
\n \n {lang(isAdded ? 'Stickers.Installed' : 'Stickers.Install')}\n \n
\n
\n {!canRenderStickers && }\n {canRenderStickers && displayedStickers.map((sticker) => (\n \n ))}\n
\n {canRenderStickers && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { stickerSetId }): StateProps => {\n return {\n set: selectStickerSet(global, stickerSetId),\n shouldPlay: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadStickers', 'toggleStickerSet']),\n)(StickerSetResult));\n","import React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport { throttle } from '../../util/schedulers';\nimport { selectCurrentStickerSearch } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport Loading from '../ui/Loading';\nimport StickerSetResult from './StickerSetResult';\n\nimport './StickerSearch.scss';\n\ntype StateProps = {\n query?: string;\n featuredIds?: string[];\n resultIds?: string[];\n};\n\ntype DispatchProps = Pick;\n\nconst INTERSECTION_THROTTLE = 200;\n\nconst runThrottled = throttle((cb) => cb(), 60000, true);\n\nconst StickerSearch: FC = ({\n query,\n featuredIds,\n resultIds,\n loadFeaturedStickers,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const lang = useLang();\n\n const [isModalOpen, setIsModalOpen] = useState(false);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, throttleMs: INTERSECTION_THROTTLE });\n\n // Due to the parent Transition, this component never gets unmounted,\n // that's why we use throttled API call on every update.\n useEffect(() => {\n runThrottled(() => {\n loadFeaturedStickers();\n });\n });\n\n function renderContent() {\n if (query === undefined) {\n return undefined;\n }\n\n if (!query && featuredIds) {\n return featuredIds.map((id) => (\n \n ));\n }\n\n if (resultIds) {\n if (!resultIds.length) {\n return

Nothing found.

;\n }\n\n return resultIds.map((id) => (\n \n ));\n }\n\n return ;\n }\n\n return (\n
\n {renderContent()}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentSearch = selectCurrentStickerSearch(global);\n const { query, resultIds } = currentSearch || {};\n const { featured } = global.stickers;\n\n return {\n query,\n featuredIds: featured.setIds,\n resultIds,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFeaturedStickers']),\n)(StickerSearch));\n","import React, {\n FC, memo, useRef, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiVideo } from '../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n selectCurrentGifSearch,\n selectChat,\n selectIsChatWithBot,\n selectCurrentMessageList,\n} from '../../modules/selectors';\nimport { getAllowedAttachmentOptions } from '../../modules/helpers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\n\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport GifButton from '../common/GifButton';\nimport Loading from '../ui/Loading';\n\nimport './GifSearch.scss';\n\ntype StateProps = {\n query?: string;\n results?: ApiVideo[];\n chat?: ApiChat;\n isChatWithBot?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst PRELOAD_BACKWARDS = 96; // GIF Search bot results are multiplied by 24\nconst INTERSECTION_DEBOUNCE = 300;\n\nconst GifSearch: FC = ({\n query,\n results,\n chat,\n isChatWithBot,\n searchMoreGifs,\n sendMessage,\n setGifSearchQuery,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({ rootRef: containerRef, debounceMs: INTERSECTION_DEBOUNCE });\n\n const { canSendGifs } = getAllowedAttachmentOptions(chat, isChatWithBot);\n\n const handleGifClick = useCallback((gif: ApiVideo) => {\n if (canSendGifs) {\n sendMessage({ gif });\n }\n\n if (IS_TOUCH_ENV) {\n setGifSearchQuery({ query: undefined });\n }\n }, [canSendGifs, sendMessage, setGifSearchQuery]);\n\n const lang = useLang();\n\n function renderContent() {\n if (query === undefined) {\n return undefined;\n }\n\n if (!results) {\n return (\n \n );\n }\n\n if (!results.length) {\n return (\n

{lang('NoGIFsFound')}

\n );\n }\n\n return results.map((gif) => (\n \n ));\n }\n\n const hasResults = Boolean(query !== undefined && results && results.length);\n\n return (\n
\n \n {renderContent()}\n \n\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentSearch = selectCurrentGifSearch(global);\n const { query, results } = currentSearch || {};\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n\n return {\n query,\n results,\n chat,\n isChatWithBot,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['searchMoreGifs', 'sendMessage', 'setGifSearchQuery']),\n)(GifSearch));\n","import React, {\n FC, useCallback, useState, memo, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiChat,\n ApiMessage,\n ApiPollAnswer,\n ApiPollResult,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport { pick } from '../../util/iteratees';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport ShowMoreButton from '../ui/ShowMoreButton';\nimport Loading from '../ui/Loading';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\n\nimport './PollAnswerResults.scss';\n\ntype OwnProps = {\n chat: ApiChat;\n message: ApiMessage;\n answer: ApiPollAnswer;\n answerVote: ApiPollResult;\n totalVoters: number;\n};\n\ntype StateProps = {\n voters?: number[];\n offset: string;\n};\n\ntype DispatchProps = Pick;\n\nconst INITIAL_LIMIT = 4;\nconst VIEW_MORE_LIMIT = 50;\n\nconst PollAnswerResults: FC = ({\n chat,\n message,\n answer,\n answerVote,\n totalVoters,\n voters,\n offset,\n loadPollOptionResults,\n openChat,\n closePollResults,\n}) => {\n const prevVotersCount = usePrevious(answerVote.votersCount);\n const [isLoading, setIsLoading] = useState(true);\n const areVotersLoaded = Boolean(voters);\n const { option, text } = answer;\n const lang = useLang();\n\n useEffect(() => {\n // For update when new votes arrive or when the user takes back his vote\n if (!areVotersLoaded || prevVotersCount !== answerVote.votersCount) {\n loadPollOptionResults({\n chat, messageId: message.id, option, offset, limit: INITIAL_LIMIT, shouldResetVoters: true,\n });\n }\n // eslint-disable-next-line\n }, [answerVote.votersCount, areVotersLoaded]);\n\n const handleViewMoreClick = useCallback(() => {\n setIsLoading(true);\n loadPollOptionResults({\n chat, messageId: message.id, option, offset, limit: VIEW_MORE_LIMIT,\n });\n }, [chat, loadPollOptionResults, message.id, offset, option]);\n\n useEffect(() => {\n setIsLoading(false);\n }, [voters]);\n\n const handleMemberClick = useCallback((id: number) => {\n openChat({ id });\n closePollResults();\n }, [closePollResults, openChat]);\n\n function renderViewMoreButton() {\n const leftVotersCount = answerVote.votersCount - voters!.length;\n\n return answerVote.votersCount > INITIAL_LIMIT && leftVotersCount > 0 && (\n \n );\n }\n\n return (\n
\n
\n {voters\n ? voters.map((id) => (\n handleMemberClick(id)}\n >\n \n \n ))\n : }\n {voters && renderViewMoreButton()}\n
\n
\n {text}\n \n {getPercentage(answerVote.votersCount, totalVoters)}%\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 memo(withGlobal(\n (global, { answer }: OwnProps): StateProps => {\n const { voters, offsets } = global.pollResults;\n\n return {\n voters: voters && voters[answer.option],\n offset: (offsets && offsets[answer.option]) || '',\n };\n },\n (global, actions): DispatchProps => pick(actions, ['loadPollOptionResults', 'openChat', 'closePollResults']),\n)(PollAnswerResults));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiChat } from '../../api/types';\nimport { selectChat, selectChatMessage } from '../../modules/selectors';\nimport { buildCollectionByKey } from '../../util/iteratees';\nimport { getMessagePoll } from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\n\nimport PollAnswerResults from './PollAnswerResults';\nimport Loading from '../ui/Loading';\n\nimport './PollResults.scss';\n\ntype StateProps = {\n chat?: ApiChat;\n message?: ApiMessage;\n lastSyncTime?: number;\n};\n\nconst PollResults: FC = ({\n chat,\n message,\n lastSyncTime,\n}) => {\n const lang = useLang();\n if (!message || !chat) {\n return ;\n }\n\n const { summary, results } = getMessagePoll(message)!;\n if (!results.results) {\n return undefined;\n }\n\n const resultsByOption = buildCollectionByKey(results.results, 'option');\n\n return (\n
\n

{summary.question}

\n
\n {lastSyncTime && summary.answers.map((answer) => (\n \n ))}\n {!lastSyncTime && }\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n pollResults: { chatId, messageId },\n lastSyncTime,\n } = global;\n\n if (!chatId || !messageId) {\n return {};\n }\n\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n return {\n chat,\n message,\n lastSyncTime,\n };\n },\n)(PollResults));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat, selectUser } from '../../../modules/selectors';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\nimport './Management.scss';\n\ntype OwnProps = {\n userId: number;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat: ApiChat;\n progress?: ManagementProgress;\n};\n\ntype DispatchProps = Pick;\n\nconst ERROR_FIRST_NAME_MISSING = 'Please provide first name';\n\nconst ManageUser: FC = ({\n userId,\n user,\n chat,\n progress,\n updateContact,\n deleteUser,\n deleteHistory,\n closeManagement,\n openChat,\n}) => {\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [error, setError] = useState();\n const lang = useLang();\n\n const currentFirstName = user ? (user.firstName || '') : '';\n const currentLastName = user ? (user.lastName || '') : '';\n const currentIsMuted = chat ? chat.isMuted : undefined;\n\n const [firstName, setFirstName] = useState(currentFirstName);\n const [lastName, setLastName] = useState(currentLastName);\n const [isNotificationsEnabled, setIsNotificationsEnabled] = useState(!currentIsMuted);\n\n useEffect(() => {\n setIsNotificationsEnabled(!currentIsMuted);\n }, [currentIsMuted]);\n\n useEffect(() => {\n setIsProfileFieldsTouched(false);\n closeDeleteDialog();\n }, [closeDeleteDialog, userId]);\n\n useEffect(() => {\n setFirstName(currentFirstName);\n setLastName(currentLastName);\n }, [currentFirstName, currentLastName, user]);\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n closeDeleteDialog();\n }\n }, [closeDeleteDialog, progress]);\n\n const handleFirstNameChange = useCallback((e: ChangeEvent) => {\n setFirstName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleLastNameChange = useCallback((e: ChangeEvent) => {\n setLastName(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleNotificationChange = useCallback((e: ChangeEvent) => {\n setIsNotificationsEnabled(e.target.checked);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleProfileSave = useCallback(() => {\n const trimmedFirstName = firstName.trim();\n const trimmedLastName = lastName.trim();\n\n if (!trimmedFirstName.length) {\n setError(ERROR_FIRST_NAME_MISSING);\n }\n\n updateContact({\n userId,\n isMuted: !isNotificationsEnabled,\n firstName: trimmedFirstName,\n lastName: trimmedLastName,\n });\n }, [firstName, lastName, updateContact, userId, isNotificationsEnabled]);\n\n const handleDeleteContact = useCallback(() => {\n deleteHistory({\n chatId: chat.id,\n shouldDeleteForAll: false,\n });\n deleteUser({ userId });\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [chat.id, closeDeleteDialog, closeManagement, deleteHistory, deleteUser, openChat, userId]);\n\n if (!user) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n \n \n \n
\n \n
\n
\n
\n \n {lang('DeleteContact')}\n \n
\n
\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId }): StateProps => {\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId)!;\n const { progress } = global.management;\n\n return {\n user, chat, progress,\n };\n },\n (global, actions): DispatchProps => pick(actions, [\n 'updateContact', 'deleteUser', 'closeManagement', 'openChat', 'deleteHistory',\n ]),\n)(ManageUser));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens, ManagementProgress } from '../../../types';\nimport { ApiChat, ApiChatBannedRights, ApiMediaFormat } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { getChatAvatarHash, getHasAdminRight, isChatBasicGroup } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\nimport { selectChat } from '../../../modules/selectors';\nimport { formatInteger } from '../../../util/textFormat';\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\nimport './Management.scss';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n progress?: ManagementProgress;\n isBasicGroup: boolean;\n hasLinkedChannel: boolean;\n canChangeInfo?: boolean;\n canBanUsers?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst GROUP_TITLE_EMPTY = 'Group title can\\'t be empty';\n\n// Some checkboxes control multiple rights, and some rights are not controlled from Permissions screen,\n// so we need to define the amount manually\nconst TOTAL_PERMISSIONS_COUNT = 8;\n\nconst ManageGroup: FC = ({\n chatId,\n chat,\n progress,\n isBasicGroup,\n hasLinkedChannel,\n canChangeInfo,\n canBanUsers,\n onScreenSelect,\n togglePreHistoryHidden,\n updateChat,\n deleteHistory,\n leaveChannel,\n deleteChannel,\n closeManagement,\n openChat,\n}) => {\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const currentTitle = chat.title;\n const currentAbout = chat.fullInfo ? (chat.fullInfo.about || '') : '';\n\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [title, setTitle] = useState(currentTitle);\n const [about, setAbout] = useState(currentAbout);\n const [photo, setPhoto] = useState();\n const [error, setError] = useState();\n const imageHash = getChatAvatarHash(chat);\n const currentAvatarBlobUrl = useMedia(imageHash, false, ApiMediaFormat.BlobUrl);\n const lang = useLang();\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const handleClickEditType = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatPrivacyType);\n }, [onScreenSelect]);\n\n const handleClickDiscussion = useCallback(() => {\n onScreenSelect(ManagementScreens.Discussion);\n }, [onScreenSelect]);\n\n const handleClickPermissions = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupPermissions);\n }, [onScreenSelect]);\n\n const handleClickAdministrators = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }, [onScreenSelect]);\n\n const handleSetPhoto = useCallback((file: File) => {\n setPhoto(file);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleTitleChange = useCallback((e: ChangeEvent) => {\n setTitle(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleAboutChange = useCallback((e: ChangeEvent) => {\n setAbout(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUpdateGroup = useCallback(() => {\n const trimmedTitle = title.trim();\n const trimmedAbout = about.trim();\n\n if (!trimmedTitle.length) {\n setError(GROUP_TITLE_EMPTY);\n return;\n }\n\n updateChat({\n chatId,\n title: trimmedTitle,\n about: trimmedAbout,\n photo,\n });\n }, [about, chatId, photo, title, updateChat]);\n\n const handleClickMembers = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupMembers);\n }, [onScreenSelect]);\n\n const handleTogglePreHistory = useCallback(() => {\n if (!chat.fullInfo) {\n return;\n }\n\n const { isPreHistoryHidden } = chat.fullInfo;\n\n togglePreHistoryHidden({ chatId: chat.id, isEnabled: !isPreHistoryHidden });\n }, [chat, togglePreHistoryHidden]);\n\n const enabledPermissionsCount = useMemo(() => {\n if (!chat.defaultBannedRights) {\n return 0;\n }\n\n let totalCount = [\n 'sendMessages',\n 'sendMedia',\n 'embedLinks',\n 'sendPolls',\n 'changeInfo',\n 'inviteUsers',\n 'pinMessages',\n ].filter(\n (key) => !chat.defaultBannedRights![key as keyof ApiChatBannedRights],\n ).length;\n\n const { sendStickers, sendGifs } = chat.defaultBannedRights;\n\n // These two rights are controlled with a single checkbox\n if (!sendStickers && !sendGifs) {\n totalCount += 1;\n }\n\n return totalCount;\n }, [chat]);\n\n const adminsCount = (chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0;\n\n const handleDeleteGroup = useCallback(() => {\n if (isBasicGroup) {\n deleteHistory({ chatId: chat.id, shouldDeleteForAll: false });\n } else if (!chat.isCreator) {\n leaveChannel({ chatId: chat.id });\n } else {\n deleteChannel({ chatId: chat.id });\n }\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [\n isBasicGroup, chat.isCreator, chat.id,\n closeDeleteDialog, closeManagement, deleteHistory, leaveChannel, deleteChannel, openChat,\n ]);\n\n if (chat.isRestricted) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n \n \n \n {chat.isCreator && (\n \n {lang('GroupType')}\n {chat.username ? lang('TypePublic') : lang('TypePrivate')}\n \n )}\n {hasLinkedChannel && (\n \n {lang('LinkedChannel')}\n {lang('DiscussionUnlink')}\n \n )}\n \n {lang('ChannelPermissions')}\n \n {enabledPermissionsCount}/{TOTAL_PERMISSIONS_COUNT}\n \n \n \n {lang('ChannelAdministrators')}\n {formatInteger(adminsCount)}\n \n
\n
\n \n {lang('GroupMembers')}\n {formatInteger(chat.membersCount!)}\n \n\n {chat.fullInfo && (\n
\n \n
\n )}\n
\n
\n \n {lang('DeleteMega')}\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 { progress } = global.management;\n const hasLinkedChannel = Boolean(chat.fullInfo && chat.fullInfo.linkedChatId);\n\n return {\n chat,\n progress,\n isBasicGroup: isChatBasicGroup(chat),\n hasLinkedChannel,\n canChangeInfo: getHasAdminRight(chat, 'changeInfo'),\n canBanUsers: getHasAdminRight(chat, 'banUsers'),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'togglePreHistoryHidden', 'updateChat', 'closeManagement',\n 'deleteHistory', 'leaveChannel', 'deleteChannel', 'openChat',\n ]),\n)(ManageGroup));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens } from '../../../types';\nimport { ApiChat, ApiChatBannedRights, ApiChatMember } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n currentUserId?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FLOATING_BUTTON_ANIMATION_TIMEOUT_MS = 250;\n\nfunction getLangKeyForBannedRightKey(key: string) {\n switch (key) {\n case 'sendMessages':\n return 'UserRestrictionsNoSend';\n case 'sendMedia':\n return 'UserRestrictionsNoSendMedia';\n case 'sendStickers':\n return 'UserRestrictionsNoSendStickers';\n case 'embedLinks':\n return 'UserRestrictionsNoEmbedLinks';\n case 'sendPolls':\n return 'UserRestrictionsNoSendPolls';\n case 'changeInfo':\n return 'UserRestrictionsNoChangeInfo';\n case 'inviteUsers':\n return 'UserRestrictionsInviteUsers';\n case 'pinMessages':\n return 'UserRestrictionsPinMessages';\n default:\n return undefined;\n }\n}\n\nconst ManageGroupPermissions: FC = ({\n onScreenSelect,\n onChatMemberSelect,\n chat,\n currentUserId,\n updateChatDefaultBannedRights,\n}) => {\n const [permissions, setPermissions] = useState({});\n const [havePermissionChanged, setHavePermissionChanged] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const lang = useLang();\n\n const handleRemovedUsersClick = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupRemovedUsers);\n }, [onScreenSelect]);\n\n const handleAddExceptionClick = useCallback(() => {\n onScreenSelect(ManagementScreens.GroupUserPermissionsCreate);\n }, [onScreenSelect]);\n\n const handleExceptionMemberClick = useCallback((member: ApiChatMember) => {\n onChatMemberSelect(member.userId, member.promotedByUserId === currentUserId);\n onScreenSelect(ManagementScreens.GroupUserPermissions);\n }, [currentUserId, onChatMemberSelect, onScreenSelect]);\n\n useEffect(() => {\n setPermissions((chat && chat.defaultBannedRights) || {});\n setHavePermissionChanged(false);\n setTimeout(() => {\n setIsLoading(false);\n }, FLOATING_BUTTON_ANIMATION_TIMEOUT_MS);\n }, [chat]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatBannedRights]),\n ...(name === 'sendStickers' && {\n sendGifs: getUpdatedPermissionValue(p[name]),\n }),\n }));\n setHavePermissionChanged(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!chat) {\n return;\n }\n\n setIsLoading(true);\n updateChatDefaultBannedRights({ chatId: chat.id, bannedRights: permissions });\n }, [chat, permissions, updateChatDefaultBannedRights]);\n\n const removedUsersCount = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.kickedMembers) {\n return 0;\n }\n\n return chat.fullInfo.kickedMembers.length;\n }, [chat]);\n\n const exceptionMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.members) {\n return [];\n }\n\n return chat.fullInfo.members.filter(({ bannedRights }) => !!bannedRights);\n }, [chat]);\n\n const getMemberExceptions = useCallback((member: ApiChatMember) => {\n const { bannedRights } = member;\n if (!bannedRights || !chat) {\n return undefined;\n }\n\n const { defaultBannedRights } = chat;\n\n return Object.keys(bannedRights).reduce((result, key) => {\n if (\n !bannedRights[key as keyof ApiChatBannedRights]\n || (defaultBannedRights && defaultBannedRights[key as keyof ApiChatBannedRights])\n || key === 'sendInline' || key === 'viewMessages' || key === 'sendGames'\n ) {\n return result;\n }\n\n const langKey = getLangKeyForBannedRightKey(key);\n\n if (!langKey) {\n return result;\n }\n\n const translatedString = lang(langKey);\n\n return `${result}${!result.length ? translatedString : `, ${translatedString}`}`;\n }, '');\n }, [chat, lang]);\n\n return (\n
\n
\n
\n

{lang('ChannelPermissionsHeader')}

\n\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n
\n \n {lang('ChannelBlockedUsers')}\n {removedUsersCount}\n \n
\n\n
\n

{lang('PrivacyExceptions')}

\n\n \n {lang('ChannelAddException')}\n \n\n {exceptionMembers.map((member) => (\n handleExceptionMemberClick(member)}\n >\n \n \n ))}\n
\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n return { chat, currentUserId: global.currentUserId };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatDefaultBannedRights']),\n)(ManageGroupPermissions));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatMember, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { selectChat } from '../../../modules/selectors';\nimport { getUserFullName } from '../../../modules/helpers';\nimport { pick } from '../../../util/iteratees';\nimport useLang from '../../../hooks/useLang';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n usersById: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageGroupRemovedUsers: FC = ({\n chat,\n usersById,\n updateChatMemberBannedRights,\n}) => {\n const lang = useLang();\n\n const removedMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.kickedMembers) {\n return [];\n }\n\n return chat.fullInfo.kickedMembers;\n }, [chat]);\n\n const getRemovedBy = useCallback((member: ApiChatMember) => {\n if (!member.kickedByUserId) {\n return undefined;\n }\n\n const kickedByUser = usersById[member.kickedByUserId];\n if (!kickedByUser) {\n return undefined;\n }\n\n return lang('UserRemovedBy', getUserFullName(kickedByUser));\n }, [lang, usersById]);\n\n const getContextActions = useCallback((member: ApiChatMember) => {\n if (!chat) {\n return undefined;\n }\n\n return [{\n title: lang('Unblock'),\n icon: 'delete',\n destructive: true,\n handler: () => updateChatMemberBannedRights({\n chatId: chat.id,\n userId: member.userId,\n bannedRights: {},\n }),\n }];\n }, [lang, chat, updateChatMemberBannedRights]);\n\n return (\n
\n
\n
\n

{lang('NoBlockedGroup2')}

\n\n {removedMembers.map((member) => (\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 { byId: usersById } = global.users;\n\n return { chat, usersById };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatMemberBannedRights']),\n)(ManageGroupRemovedUsers));\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ManagementScreens, ManagementProgress } from '../../../types';\nimport { ApiChat, ApiMediaFormat } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { getChatAvatarHash, getHasAdminRight } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\n\nimport AvatarEditable from '../../ui/AvatarEditable';\nimport InputText from '../../ui/InputText';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './Management.scss';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n progress?: ManagementProgress;\n isSignaturesShown: boolean;\n canChangeInfo?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst CHANNEL_TITLE_EMPTY = 'Channel title can\\'t be empty';\n\nconst ManageChannel: FC = ({\n chatId,\n chat,\n progress,\n isSignaturesShown,\n canChangeInfo,\n onScreenSelect,\n updateChat,\n toggleSignatures,\n closeManagement,\n leaveChannel,\n deleteChannel,\n openChat,\n}) => {\n const currentTitle = chat ? (chat.title || '') : '';\n const currentAbout = chat && chat.fullInfo ? (chat.fullInfo.about || '') : '';\n const hasLinkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId;\n\n const [isDeleteDialogOpen, openDeleteDialog, closeDeleteDialog] = useFlag();\n const [isProfileFieldsTouched, setIsProfileFieldsTouched] = useState(false);\n const [title, setTitle] = useState(currentTitle);\n const [about, setAbout] = useState(currentAbout);\n const [photo, setPhoto] = useState();\n const [error, setError] = useState();\n const imageHash = chat && getChatAvatarHash(chat);\n const currentAvatarBlobUrl = useMedia(imageHash, false, ApiMediaFormat.BlobUrl);\n const lang = useLang();\n\n useEffect(() => {\n if (progress === ManagementProgress.Complete) {\n setIsProfileFieldsTouched(false);\n setError(undefined);\n }\n }, [progress]);\n\n const adminsCount = (chat && chat.fullInfo && chat.fullInfo.adminMembers && chat.fullInfo.adminMembers.length) || 0;\n\n const handleClickEditType = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatPrivacyType);\n }, [onScreenSelect]);\n\n const handleClickDiscussion = useCallback(() => {\n onScreenSelect(ManagementScreens.Discussion);\n }, [onScreenSelect]);\n\n const handleClickAdministrators = useCallback(() => {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }, [onScreenSelect]);\n\n const handleSetPhoto = useCallback((file: File) => {\n setPhoto(file);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleTitleChange = useCallback((e: ChangeEvent) => {\n setTitle(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleAboutChange = useCallback((e: ChangeEvent) => {\n setAbout(e.target.value);\n setIsProfileFieldsTouched(true);\n }, []);\n\n const handleUpdateChannel = useCallback(() => {\n const trimmedTitle = title.trim();\n const trimmedAbout = about.trim();\n\n if (!trimmedTitle.length) {\n setError(CHANNEL_TITLE_EMPTY);\n return;\n }\n\n updateChat({\n chatId,\n title: trimmedTitle,\n about: trimmedAbout,\n photo,\n });\n }, [about, chatId, photo, title, updateChat]);\n\n const handleToggleSignatures = useCallback(() => {\n toggleSignatures({ chatId, isEnabled: !isSignaturesShown });\n }, [chatId, isSignaturesShown, toggleSignatures]);\n\n const handleClickSubscribers = useCallback(() => {\n onScreenSelect(ManagementScreens.ChannelSubscribers);\n }, [onScreenSelect]);\n\n\n const handleDeleteChannel = useCallback(() => {\n if (chat.isCreator) {\n deleteChannel({ chatId: chat.id });\n } else {\n leaveChannel({ chatId: chat.id });\n }\n\n closeDeleteDialog();\n closeManagement();\n openChat({ id: undefined });\n }, [chat.isCreator, chat.id, closeDeleteDialog, closeManagement, leaveChannel, deleteChannel, openChat]);\n\n if (chat.isRestricted) {\n return undefined;\n }\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n \n \n \n {chat.isCreator && (\n \n {lang('ChannelType')}\n {chat.username ? lang('TypePublic') : lang('TypePrivate')}\n \n )}\n \n {lang('Discussion')}\n {hasLinkedChat ? lang('DiscussionUnlink') : lang('Add')}\n \n \n {lang('ChannelAdministrators')}\n {adminsCount}\n \n
\n \n
\n
\n
\n \n {lang('ChannelSubscribers')}\n {lang('Subscribers', chat.membersCount!, 'i')}\n \n
\n
\n \n {chat.isCreator ? lang('ChannelDelete') : lang('LeaveChannel')}\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 { progress } = global.management;\n const isSignaturesShown = Boolean(chat && chat.isSignaturesShown);\n\n return {\n chat,\n progress,\n isSignaturesShown,\n canChangeInfo: getHasAdminRight(chat, 'changeInfo'),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSignatures', 'updateChat', 'closeManagement', 'leaveChannel', 'deleteChannel', 'openChat',\n ]),\n)(ManageChannel));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { selectChat, selectManagement } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport { isChatChannel } from '../../../modules/helpers';\nimport useFlag from '../../../hooks/useFlag';\nimport useLang from '../../../hooks/useLang';\n\nimport SafeLink from '../../common/SafeLink';\nimport ListItem from '../../ui/ListItem';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Loading from '../../ui/Loading';\nimport Spinner from '../../ui/Spinner';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport UsernameInput from '../../common/UsernameInput';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype PrivacyType = 'private' | 'public';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat: ApiChat;\n isChannel: boolean;\n progress?: ManagementProgress;\n isUsernameAvailable?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageChatPrivacyType: FC = ({\n chat,\n isChannel,\n progress,\n isUsernameAvailable,\n checkPublicLink,\n updatePublicLink,\n updatePrivateLink,\n}) => {\n const isPublic = Boolean(chat.username);\n const privateLink = chat.fullInfo && chat.fullInfo.inviteLink;\n\n const [privacyType, setPrivacyType] = useState(isPublic ? 'public' : 'private');\n const [username, setUsername] = useState();\n const [isRevokeConfirmDialogOpen, openRevokeConfirmDialog, closeRevokeConfirmDialog] = useFlag();\n\n const canUpdate = (\n (privacyType === 'public' && username && isUsernameAvailable)\n || (privacyType === 'private' && isPublic)\n );\n\n useEffect(() => {\n if (privacyType && !privateLink) {\n updatePrivateLink();\n }\n }, [privacyType, privateLink, updatePrivateLink]);\n\n const handleOptionChange = useCallback((value: string) => {\n setPrivacyType(value as PrivacyType);\n }, []);\n\n const handleSave = useCallback(() => {\n updatePublicLink({ username: privacyType === 'public' ? username : '' });\n }, [privacyType, updatePublicLink, username]);\n\n const handleRevokePrivateLink = useCallback(() => {\n closeRevokeConfirmDialog();\n updatePrivateLink();\n }, [closeRevokeConfirmDialog, updatePrivateLink]);\n\n const lang = useLang();\n const langPrefix1 = isChannel ? 'Channel' : 'Mega';\n const langPrefix2 = isChannel ? 'Channel' : 'Group';\n\n const options = [\n { value: 'private', label: lang(`${langPrefix1}Private`), subLabel: lang(`${langPrefix1}PrivateInfo`) },\n { value: 'public', label: lang(`${langPrefix1}Public`), subLabel: lang(`${langPrefix1}PublicInfo`) },\n ];\n\n const isLoading = progress === ManagementProgress.InProgress;\n\n return (\n
\n
\n
\n

{lang(`${langPrefix2}Type`)}

\n \n
\n {privacyType === 'private' ? (\n
\n {privateLink ? (\n <>\n \n

\n {lang(`${langPrefix1}PrivateLinkHelp`)}\n

\n\n \n {lang('RevokeLink')}\n \n \n \n ) : (\n \n )}\n
\n ) : (\n
\n \n

\n {lang(`${langPrefix2}.Username.CreatePublicLinkHelp`)}\n

\n
\n )}\n
\n \n {isLoading ? (\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 { isUsernameAvailable } = selectManagement(global, chatId)!;\n\n return {\n chat,\n isChannel: isChatChannel(chat),\n progress: global.management.progress,\n isUsernameAvailable,\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'checkPublicLink', 'updatePublicLink', 'updatePrivateLink',\n ]),\n)(ManageChatPrivacyType));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\n\nimport { STICKER_SIZE_DISCUSSION_GROUPS } from '../../../config';\nimport { selectChat } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport getAnimationData from '../../common/helpers/animatedAssets';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport NothingFound from '../../common/NothingFound';\nimport GroupChatInfo from '../../common/GroupChatInfo';\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport useFlag from '../../../hooks/useFlag';\nimport renderText from '../../common/helpers/renderText';\nimport Avatar from '../../common/Avatar';\nimport { isChatChannel } from '../../../modules/helpers';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n chatsByIds: Record;\n linkedChat?: ApiChat;\n forDiscussionIds?: number[];\n isChannel?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageDiscussion: FC = ({\n chat,\n chatId,\n chatsByIds,\n linkedChat,\n forDiscussionIds,\n isChannel,\n onScreenSelect,\n loadGroupsForDiscussion,\n linkDiscussionGroup,\n unlinkDiscussionGroup,\n}) => {\n const [linkedGroupId, setLinkedGroupId] = useState();\n const [animationData, setAnimationData] = useState>();\n const [isAnimationLoaded, setIsAnimationLoaded] = useState(false);\n const handleAnimationLoad = useCallback(() => setIsAnimationLoaded(true), []);\n const [isConfirmUnlinkGroupDialogOpen, openConfirmUnlinkGroupDialog, closeConfirmUnlinkGroupDialog] = useFlag();\n const [isConfirmLinkGroupDialogOpen, openConfirmLinkGroupDialog, closeConfirmLinkGroupDialog] = useFlag();\n const lang = useLang();\n const linkedChatId = linkedChat && linkedChat.id;\n\n useEffect(() => {\n loadGroupsForDiscussion();\n }, [loadGroupsForDiscussion]);\n\n useEffect(() => {\n if (!animationData) {\n getAnimationData('DiscussionGroups').then(setAnimationData);\n }\n }, [animationData]);\n\n const handleUnlinkGroupSessions = useCallback(() => {\n closeConfirmUnlinkGroupDialog();\n unlinkDiscussionGroup({ channelId: isChannel ? chatId : linkedChatId });\n if (!isChannel) {\n onScreenSelect(ManagementScreens.Initial);\n }\n }, [closeConfirmUnlinkGroupDialog, unlinkDiscussionGroup, isChannel, chatId, linkedChatId, onScreenSelect]);\n\n const handleLinkGroupSessions = useCallback(() => {\n closeConfirmLinkGroupDialog();\n linkDiscussionGroup({ channelId: chatId, chatId: linkedGroupId });\n }, [closeConfirmLinkGroupDialog, linkDiscussionGroup, chatId, linkedGroupId]);\n\n const onDiscussionClick = (groupId: number) => {\n setLinkedGroupId(groupId);\n openConfirmLinkGroupDialog();\n };\n\n function renderUnlinkGroupHeader() {\n return (\n
\n \n
\n {lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n
\n
\n );\n }\n function renderLinkGroupHeader() {\n const linkedGroup = chatsByIds[linkedGroupId];\n\n if (!linkedGroup) {\n return undefined;\n }\n\n return (\n
\n \n
\n {lang('Channel.DiscussionGroup.LinkGroup')}\n
\n
\n );\n }\n\n function renderLinkGroupConfirmText() {\n const linkedGroup = chatsByIds[linkedGroupId];\n\n if (!linkedGroup) {\n return undefined;\n }\n\n if (linkedGroup.hasPrivateLink) {\n return renderText(\n `Do you want to make **${linkedGroup.title}** the discussion board for **${chat!.title}**?`,\n ['br', 'simple_markdown'],\n );\n // return renderText(\n // lang('DiscussionLinkGroupPublicAlert', linkedChat.title, chat!.title),\n // ['br', 'simple_markdown'],\n // );\n }\n\n return renderText(\n // eslint-disable-next-line max-len\n `Do you want to make **${linkedGroup.title}** the discussion board for **${chat!.title}**?\\n\\nAnyone from the channel will be able to see messages in this group.`,\n ['br', 'simple_markdown'],\n );\n // return renderText(\n // lang('DiscussionLinkGroupPrivateAlert', linkedChat.title, chat!.title),\n // ['br', 'simple_markdown'],\n // );\n }\n\n function renderLinkedGroup() {\n return (\n
\n \n \n \n \n {lang(isChannel ? 'DiscussionUnlinkGroup' : 'DiscussionUnlinkChannel')}\n \n \n
\n );\n }\n\n function renderDiscussionGroups() {\n return (\n
\n

{lang('DiscussionChannelHelp')}

\n\n
\n \n {lang('DiscussionCreateGroup')}\n \n {forDiscussionIds ? (\n forDiscussionIds.map((id, i) => (\n { onDiscussionClick(id); }}\n >\n \n \n ))\n ) : (\n \n )}\n
\n

{lang('DiscussionChannelHelp2')}

\n \n
\n );\n }\n\n return (\n
\n
\n
\n
\n {animationData && (\n \n )}\n
\n {linkedChat && renderLinkedGroup()}\n {!linkedChat && renderDiscussionGroups()}\n
\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { forDiscussionIds, byId: chatsByIds } = global.chats;\n const linkedChat = chat && chat.fullInfo && chat.fullInfo.linkedChatId\n ? selectChat(global, chat.fullInfo.linkedChatId)\n : undefined;\n\n return {\n chat,\n chatsByIds,\n forDiscussionIds,\n linkedChat,\n isChannel: chat && isChatChannel(chat),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadGroupsForDiscussion', 'linkDiscussionGroup', 'unlinkDiscussionGroup',\n ]),\n)(ManageDiscussion));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatBannedRights } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\n\ntype OwnProps = {\n chatId: number;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n isFormFullyDisabled?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageGroupUserPermissions: FC = ({\n chat,\n selectedChatMemberId,\n onScreenSelect,\n updateChatMemberBannedRights,\n isFormFullyDisabled,\n}) => {\n const [permissions, setPermissions] = useState({});\n const [havePermissionChanged, setHavePermissionChanged] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [isBanConfirmationDialogOpen, openBanConfirmationDialog, closeBanConfirmationDialog] = useFlag();\n const lang = useLang();\n\n const selectedChatMember = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.members) {\n return undefined;\n }\n\n return chat.fullInfo.members.find(({ userId }) => userId === selectedChatMemberId);\n }, [chat, selectedChatMemberId]);\n\n useEffect(() => {\n if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) {\n onScreenSelect(ManagementScreens.GroupPermissions);\n }\n }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]);\n\n useEffect(() => {\n setPermissions((selectedChatMember && selectedChatMember.bannedRights) || (chat && chat.defaultBannedRights) || {});\n setHavePermissionChanged(false);\n setIsLoading(false);\n }, [chat, selectedChatMember]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatBannedRights]),\n ...(name === 'sendStickers' && {\n sendGifs: getUpdatedPermissionValue(p[name]),\n }),\n }));\n setHavePermissionChanged(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!chat || !selectedChatMemberId) {\n return;\n }\n\n setIsLoading(true);\n updateChatMemberBannedRights({\n chatId: chat.id,\n userId: selectedChatMemberId,\n bannedRights: permissions,\n });\n }, [chat, selectedChatMemberId, permissions, updateChatMemberBannedRights]);\n\n const handleBanFromGroup = useCallback(() => {\n if (!chat || !selectedChatMemberId) {\n return;\n }\n\n updateChatMemberBannedRights({\n chatId: chat.id,\n userId: selectedChatMemberId,\n bannedRights: {\n viewMessages: true,\n },\n });\n }, [chat, selectedChatMemberId, updateChatMemberBannedRights]);\n\n const getControlIsDisabled = useCallback((key: keyof ApiChatBannedRights) => {\n if (isFormFullyDisabled) {\n return true;\n }\n\n if (!chat || !chat.defaultBannedRights) {\n return false;\n }\n\n return chat.defaultBannedRights[key];\n }, [chat, isFormFullyDisabled]);\n\n if (!selectedChatMember) {\n return undefined;\n }\n\n return (\n
\n
\n
\n \n \n \n\n

{lang('UserRestrictionsCanDo')}

\n\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n {!isFormFullyDisabled && (\n
\n \n {lang('UserRestrictionsBlock')}\n \n
\n )}\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n\n \n
\n );\n};\n\n\nexport default memo(withGlobal(\n (global, { chatId, isPromotedByCurrentUser }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const isFormFullyDisabled = !(chat.isCreator || isPromotedByCurrentUser);\n\n return { chat, isFormFullyDisabled };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatMemberBannedRights']),\n)(ManageGroupUserPermissions));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens } from '../../../types';\nimport { ApiChat, ApiChatMember, ApiUser } from '../../../api/types';\nimport { getUserFullName, isChatChannel } from '../../../modules/helpers';\n\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport ListItem from '../../ui/ListItem';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n currentUserId?: number;\n isChannel: boolean;\n usersById: Record;\n};\n\nconst ManageChatAdministrators: FC = ({\n chat,\n isChannel,\n currentUserId,\n usersById,\n onScreenSelect,\n onChatMemberSelect,\n}) => {\n const lang = useLang();\n\n function handleRecentActionsClick() {\n onScreenSelect(ManagementScreens.GroupRecentActions);\n }\n\n const adminMembers = useMemo(() => {\n if (!chat.fullInfo || !chat.fullInfo.adminMembers) {\n return [];\n }\n\n return chat.fullInfo.adminMembers.sort((a, b) => {\n if (a.isOwner) {\n return -1;\n } else if (b.isOwner) {\n return 1;\n }\n\n return 0;\n });\n }, [chat]);\n\n const handleAdminMemberClick = useCallback((member: ApiChatMember) => {\n onChatMemberSelect(member.userId, member.promotedByUserId === currentUserId);\n onScreenSelect(ManagementScreens.ChatAdminRights);\n }, [currentUserId, onChatMemberSelect, onScreenSelect]);\n\n const getMemberStatus = useCallback((member: ApiChatMember) => {\n if (member.isOwner) {\n return lang('ChannelCreator');\n }\n\n const promotedByUser = member.promotedByUserId ? usersById[member.promotedByUserId] : undefined;\n\n if (promotedByUser) {\n return lang('EditAdminPromotedBy', getUserFullName(promotedByUser));\n }\n\n return lang('ChannelAdmin');\n }, [lang, usersById]);\n\n return (\n
\n
\n
\n \n {lang('EventLog')}\n {lang(isChannel ? 'EventLogInfoDetailChannel' : 'EventLogInfoDetail')}\n \n
\n\n
\n

\n {isChannel\n ? 'You can add administrators to help you manage your channel.'\n : 'You can add administrators to help you manage your group.'}\n

\n\n {adminMembers.map((member) => (\n handleAdminMemberClick(member)}\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 { byId: usersById } = global.users;\n\n return {\n chat,\n currentUserId: global.currentUserId,\n isChannel: isChatChannel(chat),\n usersById,\n };\n },\n // (setGlobal, actions): DispatchProps => pick(actions, ['togglePreHistoryHidden', 'updateChat']),\n)(ManageChatAdministrators));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatMember } from '../../../api/types';\nimport useLang from '../../../hooks/useLang';\nimport { selectChat } from '../../../modules/selectors';\n\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n};\n\nconst ManageGroupRecentActions: FC = ({ chat }) => {\n const lang = useLang();\n\n const adminMembers = useMemo(() => {\n if (!chat || !chat.fullInfo || !chat.fullInfo.adminMembers) {\n return [];\n }\n\n return chat.fullInfo.adminMembers.sort((a, b) => {\n if (a.isOwner) {\n return -1;\n } else if (b.isOwner) {\n return 1;\n }\n\n return 0;\n });\n }, [chat]);\n\n const getMemberStatus = useCallback((member: ApiChatMember) => {\n if (member.isOwner) {\n return lang('ChannelCreator');\n }\n\n return lang('ChannelAdmin');\n }, [lang]);\n\n return (\n
\n
\n
\n

Actions

\n\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n\n
\n

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

\n\n
\n \n
\n\n {adminMembers.map((member) => (\n \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\n return { chat };\n },\n)(ManageGroupRecentActions));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatAdminRights, ApiUser } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectChat } from '../../../modules/selectors';\nimport { getUserFullName, isChatBasicGroup, isChatChannel } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport Checkbox from '../../ui/Checkbox';\nimport FloatingActionButton from '../../ui/FloatingActionButton';\nimport Spinner from '../../ui/Spinner';\nimport ConfirmDialog from '../../ui/ConfirmDialog';\nimport InputText from '../../ui/InputText';\n\ntype OwnProps = {\n chatId: number;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n};\n\ntype StateProps = {\n chat: ApiChat;\n usersById: Record;\n currentUserId?: number;\n isChannel: boolean;\n isFormFullyDisabled: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst CUSTOM_TITLE_MAX_LENGTH = 16;\n\nconst ManageGroupAdminRights: FC = ({\n selectedChatMemberId,\n onScreenSelect,\n chat,\n usersById,\n currentUserId,\n isChannel,\n isFormFullyDisabled,\n updateChatAdmin,\n}) => {\n const [permissions, setPermissions] = useState({});\n const [isTouched, setIsTouched] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [isDismissConfirmationDialogOpen, openDismissConfirmationDialog, closeDismissConfirmationDialog] = useFlag();\n const [customTitle, setCustomTitle] = useState('');\n const lang = useLang();\n\n const selectedChatMember = useMemo(() => {\n if (!chat.fullInfo || !chat.fullInfo.adminMembers) {\n return undefined;\n }\n\n return chat.fullInfo.adminMembers.find(({ userId }) => userId === selectedChatMemberId);\n }, [chat, selectedChatMemberId]);\n\n useEffect(() => {\n if (chat && chat.fullInfo && selectedChatMemberId && !selectedChatMember) {\n onScreenSelect(ManagementScreens.ChatAdministrators);\n }\n }, [chat, onScreenSelect, selectedChatMember, selectedChatMemberId]);\n\n useEffect(() => {\n setPermissions((selectedChatMember && selectedChatMember.adminRights) || {});\n setCustomTitle(((selectedChatMember && selectedChatMember.customTitle) || '').substr(0, CUSTOM_TITLE_MAX_LENGTH));\n setIsTouched(false);\n setIsLoading(false);\n }, [selectedChatMember]);\n\n const handlePermissionChange = useCallback((e: React.ChangeEvent) => {\n const { name } = e.target;\n\n function getUpdatedPermissionValue(value: true | undefined) {\n return value ? undefined : true;\n }\n\n setPermissions((p) => ({\n ...p,\n [name]: getUpdatedPermissionValue(p[name as keyof ApiChatAdminRights]),\n }));\n setIsTouched(true);\n }, []);\n\n const handleSavePermissions = useCallback(() => {\n if (!selectedChatMemberId) {\n return;\n }\n\n setIsLoading(true);\n updateChatAdmin({\n chatId: chat.id,\n userId: selectedChatMemberId,\n adminRights: permissions,\n customTitle,\n });\n }, [chat, selectedChatMemberId, permissions, customTitle, updateChatAdmin]);\n\n const handleDismissAdmin = useCallback(() => {\n if (!selectedChatMemberId) {\n return;\n }\n\n updateChatAdmin({\n chatId: chat.id,\n userId: selectedChatMemberId,\n adminRights: {},\n });\n closeDismissConfirmationDialog();\n }, [chat.id, closeDismissConfirmationDialog, selectedChatMemberId, updateChatAdmin]);\n\n const getControlIsDisabled = useCallback((key: keyof ApiChatAdminRights) => {\n if (isChatBasicGroup(chat)) {\n return false;\n }\n\n if (isFormFullyDisabled || !chat.adminRights) {\n return true;\n }\n\n return !chat.adminRights![key];\n }, [chat, isFormFullyDisabled]);\n\n const memberStatus = useMemo(() => {\n if (!selectedChatMember) {\n return undefined;\n }\n\n if (selectedChatMember.isOwner) {\n return lang('ChannelCreator');\n }\n\n const promotedByUser = selectedChatMember.promotedByUserId\n ? usersById[selectedChatMember.promotedByUserId]\n : undefined;\n\n if (promotedByUser) {\n return lang('EditAdminPromotedBy', getUserFullName(promotedByUser));\n }\n\n return lang('ChannelAdmin');\n }, [selectedChatMember, usersById, lang]);\n\n const handleCustomTitleChange = useCallback((e) => {\n const { value } = e.target;\n setCustomTitle(value);\n setIsTouched(true);\n }, []);\n\n if (!selectedChatMember) {\n return undefined;\n }\n\n return (\n
\n
\n
\n \n \n \n\n

{lang('EditAdminWhatCanDo')}

\n\n
\n \n
\n {isChannel && (\n
\n \n
\n )}\n {isChannel && (\n
\n \n
\n )}\n
\n \n
\n {!isChannel && (\n
\n \n
\n )}\n
\n \n
\n {!isChannel && (\n
\n \n
\n )}\n
\n \n
\n {!isChannel && (\n
\n \n
\n )}\n\n {isFormFullyDisabled && (\n

\n {lang('Channel.EditAdmin.CannotEdit')}\n

\n )}\n\n {!isChannel && (\n \n )}\n\n {currentUserId !== selectedChatMemberId && !isFormFullyDisabled && (\n \n {lang('EditAdminRemoveAdmin')}\n \n )}\n
\n
\n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n\n \n
\n );\n};\n\n\nexport default memo(withGlobal(\n (global, { chatId, isPromotedByCurrentUser }): StateProps => {\n const chat = selectChat(global, chatId)!;\n const { byId: usersById } = global.users;\n const { currentUserId } = global;\n const isChannel = isChatChannel(chat);\n const isFormFullyDisabled = !(chat.isCreator || isPromotedByCurrentUser);\n\n return {\n chat,\n usersById,\n currentUserId,\n isChannel,\n isFormFullyDisabled,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['updateChatAdmin']),\n)(ManageGroupAdminRights));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { selectChat } from '../../../modules/selectors';\nimport { sortUserIds, isChatChannel } from '../../../modules/helpers';\nimport { pick } from '../../../util/iteratees';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport NothingFound from '../../common/NothingFound';\nimport ListItem from '../../ui/ListItem';\n\ntype OwnProps = {\n chatId: number;\n};\n\ntype StateProps = {\n usersById: Record;\n members?: ApiChatMember[];\n isChannel?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ManageGroupMembers: FC = ({\n members,\n usersById,\n isChannel,\n openUserInfo,\n}) => {\n const memberIds = useMemo(() => {\n if (!members || !usersById) {\n return undefined;\n }\n\n return sortUserIds(members.map(({ userId }) => userId), usersById);\n }, [members, usersById]);\n\n const handleMemberClick = useCallback((id: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n return (\n
\n
\n
\n {memberIds ? (\n memberIds.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \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 { byId: usersById } = global.users;\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const isChannel = chat && isChatChannel(chat);\n\n return {\n members,\n usersById,\n isChannel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(ManageGroupMembers));\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChatMember, ApiUser } from '../../../api/types';\nimport { ManagementScreens } from '../../../types';\n\nimport { selectChat } from '../../../modules/selectors';\nimport { sortUserIds, isChatChannel } from '../../../modules/helpers';\n\nimport PrivateChatInfo from '../../common/PrivateChatInfo';\nimport ListItem from '../../ui/ListItem';\nimport NothingFound from '../../common/NothingFound';\n\ntype OwnProps = {\n chatId: number;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number) => void;\n};\n\ntype StateProps = {\n usersById: Record;\n members?: ApiChatMember[];\n isChannel?: boolean;\n};\n\nconst ManageGroupUserPermissionsCreate: FC = ({\n usersById,\n members,\n isChannel,\n onScreenSelect,\n onChatMemberSelect,\n}) => {\n const memberIds = useMemo(() => {\n if (!members || !usersById) {\n return undefined;\n }\n\n return sortUserIds(members.filter((member) => !member.isOwner).map(({ userId }) => userId), usersById);\n }, [members, usersById]);\n\n const handleExceptionMemberClick = useCallback((memberId: number) => {\n onChatMemberSelect(memberId);\n onScreenSelect(ManagementScreens.GroupUserPermissions);\n }, [onChatMemberSelect, onScreenSelect]);\n\n return (\n
\n
\n
\n {memberIds ? (\n memberIds.map((id, i) => (\n handleExceptionMemberClick(id)}\n >\n \n \n ))\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 { byId: usersById } = global.users;\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const isChannel = chat && isChatChannel(chat);\n\n return {\n members,\n usersById,\n isChannel,\n };\n },\n)(ManageGroupUserPermissionsCreate));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementScreens, ManagementType } from '../../../types';\n\nimport { selectCurrentManagementType } from '../../../modules/selectors';\n\nimport ManageUser from './ManageUser';\nimport ManageGroup from './ManageGroup';\nimport ManageGroupPermissions from './ManageGroupPermissions';\nimport ManageGroupRemovedUsers from './ManageGroupRemovedUsers';\nimport ManageChannel from './ManageChannel';\nimport ManageChatPrivacyType from './ManageChatPrivacyType';\nimport ManageDiscussion from './ManageDiscussion';\nimport ManageGroupUserPermissions from './ManageGroupUserPermissions';\nimport ManageChatAdministrators from './ManageChatAdministrators';\nimport ManageGroupRecentActions from './ManageGroupRecentActions';\nimport ManageGroupAdminRights from './ManageGroupAdminRights';\nimport ManageGroupMembers from './ManageGroupMembers';\nimport ManageGroupUserPermissionsCreate from './ManageGroupUserPermissionsCreate';\n\nexport type OwnProps = {\n chatId: number;\n currentScreen: ManagementScreens;\n selectedChatMemberId?: number;\n isPromotedByCurrentUser?: boolean;\n onScreenSelect: (screen: ManagementScreens) => void;\n onChatMemberSelect: (memberId: number, isPromotedByCurrentUser?: boolean) => void;\n};\n\ntype StateProps = {\n managementType?: ManagementType;\n};\n\nconst Management: FC = ({\n chatId,\n currentScreen,\n selectedChatMemberId,\n isPromotedByCurrentUser,\n onScreenSelect,\n onChatMemberSelect,\n managementType,\n}) => {\n switch (currentScreen) {\n case ManagementScreens.Initial: {\n switch (managementType) {\n case 'user':\n return ;\n case 'group':\n return ;\n case 'channel':\n return ;\n }\n\n break;\n }\n\n case ManagementScreens.ChatPrivacyType:\n return (\n \n );\n\n case ManagementScreens.Discussion:\n return (\n \n );\n\n case ManagementScreens.GroupPermissions:\n return (\n \n );\n\n case ManagementScreens.GroupRemovedUsers:\n return (\n \n );\n\n case ManagementScreens.GroupUserPermissionsCreate:\n return (\n \n );\n\n case ManagementScreens.GroupUserPermissions:\n return (\n \n );\n\n case ManagementScreens.ChatAdministrators:\n return (\n \n );\n\n case ManagementScreens.GroupRecentActions:\n return (\n \n );\n\n case ManagementScreens.ChatAdminRights:\n return (\n \n );\n\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n return (\n \n );\n }\n\n return undefined; // Never reached\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const managementType = selectCurrentManagementType(global);\n\n return {\n managementType,\n };\n },\n)(Management));\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\n}\n","const VISA = /^4[0-9]{12}(?:[0-9]{1,3})?$/;\nconst MASTERCARD1 = /^5[1-5][0-9]{11,14}$/;\nconst MASTERCARD2 = /^2[2-7][0-9]{11,14}$/;\n\nexport enum CardType {\n Default,\n Visa,\n Mastercard,\n}\n\nconst cards: Record = {\n [CardType.Default]: '',\n [CardType.Visa]: 'visa',\n [CardType.Mastercard]: 'mastercard',\n};\n\nexport function detectCardType(cardNumber: string): number {\n cardNumber = cardNumber.replace(/\\s/g, '');\n if (VISA.test(cardNumber)) {\n return CardType.Visa;\n }\n if (MASTERCARD1.test(cardNumber) || MASTERCARD2.test(cardNumber)) {\n return CardType.Mastercard;\n }\n return CardType.Default;\n}\n\nexport function detectCardTypeText(cardNumber: string): string {\n const cardType = detectCardType(cardNumber);\n return cards[cardType as number] || '';\n}\n","import useReducer, { StateReducer, Dispatch } from '../useReducer';\nimport { countryList } from '../../util/phoneNumber';\n\nexport type FormState = {\n streetLine1: string;\n streetLine2: string;\n city: string;\n state: string;\n countryIso2: string;\n postCode: string;\n fullName: string;\n email: string;\n phone: string;\n shipping: string;\n cardNumber: string;\n cardholder: string;\n expiry: string;\n cvv: string;\n billingCountry: string;\n billingZip: string;\n saveInfo: boolean;\n saveCredentials: boolean;\n formErrors: Record;\n};\n\nexport type FormActions = (\n 'changeAddress1' | 'changeAddress2' | 'changeCity' | 'changeState' | 'changeCountry' |\n 'changePostCode' | 'changeFullName' | 'changeEmail' | 'changePhone' | 'changeShipping' | 'updateUserInfo' |\n 'changeCardNumber' | 'changeCardholder' | 'changeExpiryDate' | 'changeCvvCode' | 'changeBillingCountry' |\n 'changeBillingZip' | 'changeSaveInfo' | 'changeSaveCredentials' | 'setFormErrors'\n);\nexport type FormEditDispatch = Dispatch;\n\nconst INITIAL_STATE: FormState = {\n streetLine1: '',\n streetLine2: '',\n city: '',\n state: '',\n countryIso2: '',\n postCode: '',\n fullName: '',\n email: '',\n phone: '',\n shipping: '',\n cardNumber: '',\n cardholder: '',\n expiry: '',\n cvv: '',\n billingCountry: '',\n billingZip: '',\n saveInfo: true,\n saveCredentials: false,\n formErrors: {},\n};\n\nconst reducer: StateReducer = (state, action) => {\n switch (action.type) {\n case 'changeAddress1':\n return {\n ...state,\n streetLine1: action.payload,\n formErrors: {\n ...state.formErrors,\n streetLine1: undefined,\n },\n };\n case 'changeAddress2':\n return {\n ...state,\n streetLine2: action.payload,\n formErrors: {\n ...state.formErrors,\n streetLine2: undefined,\n },\n };\n case 'changeCity':\n return {\n ...state,\n city: action.payload,\n formErrors: {\n ...state.formErrors,\n city: undefined,\n },\n };\n case 'changeState':\n return {\n ...state,\n state: action.payload,\n formErrors: {\n ...state.formErrors,\n state: undefined,\n },\n };\n case 'changeCountry':\n return {\n ...state,\n countryIso2: action.payload,\n billingCountry: getBillingCountry(action.payload),\n formErrors: {\n ...state.formErrors,\n countryIso2: undefined,\n },\n };\n case 'changePostCode':\n return {\n ...state,\n postCode: action.payload,\n formErrors: {\n ...state.formErrors,\n postCode: undefined,\n },\n };\n case 'changeFullName':\n return {\n ...state,\n fullName: action.payload,\n formErrors: {\n ...state.formErrors,\n fullName: undefined,\n },\n };\n case 'changeEmail':\n return {\n ...state,\n email: action.payload,\n formErrors: {\n ...state.formErrors,\n email: undefined,\n },\n };\n case 'changePhone':\n return {\n ...state,\n phone: action.payload,\n formErrors: {\n ...state.formErrors,\n phone: undefined,\n },\n };\n case 'changeShipping':\n return { ...state, shipping: action.payload };\n case 'changeCardNumber':\n return {\n ...state,\n cardNumber: action.payload,\n formErrors: {\n ...state.formErrors,\n cardNumber: undefined,\n },\n };\n case 'changeCardholder':\n return {\n ...state,\n cardholder: action.payload,\n formErrors: {\n ...state.formErrors,\n cardholder: undefined,\n },\n };\n case 'changeExpiryDate':\n return {\n ...state,\n expiry: action.payload,\n formErrors: {\n ...state.formErrors,\n expiry: undefined,\n },\n };\n case 'changeCvvCode':\n return {\n ...state,\n cvv: action.payload,\n formErrors: {\n ...state.formErrors,\n cvv: undefined,\n },\n };\n case 'changeBillingCountry':\n return {\n ...state,\n billingCountry: action.payload,\n formErrors: {\n ...state.formErrors,\n billingCountry: undefined,\n },\n };\n case 'changeBillingZip':\n return {\n ...state,\n billingZip: action.payload,\n formErrors: {\n ...state.formErrors,\n billingZip: undefined,\n },\n };\n case 'changeSaveInfo':\n return { ...state, saveInfo: action.payload };\n case 'changeSaveCredentials':\n return { ...state, saveCredentials: action.payload };\n case 'updateUserInfo':\n if (action.payload.countryIso2) {\n return {\n ...state,\n ...action.payload,\n billingCountry: getBillingCountry(action.payload.countryIso2),\n };\n }\n return { ...state, ...action.payload };\n case 'setFormErrors':\n return {\n ...state,\n formErrors: {\n ...state.formErrors,\n ...action.payload,\n },\n };\n default:\n return state;\n }\n};\n\nfunction getBillingCountry(countryCode: string) {\n const country = countryList.find(({ id }) => id === countryCode);\n return country ? country.name : '';\n}\n\nexport default () => {\n return useReducer(reducer, INITIAL_STATE);\n};\n","import { RefObject } from 'react';\n\nimport { IS_TOUCH_ENV } from '../util/environment';\nimport { fastRaf } from '../util/schedulers';\nimport { useEffect } from '../lib/teact/teact';\n\nconst DEFAULT_DURATION = 400;\n\nexport default function useFocusAfterAnimation(\n ref: RefObject, animationDuration = DEFAULT_DURATION,\n) {\n useEffect(() => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n setTimeout(() => {\n fastRaf(() => {\n if (ref.current) {\n ref.current.focus();\n }\n });\n }, animationDuration);\n }, [ref, animationDuration]);\n}\n","import { ChangeEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n id?: string;\n value?: string;\n label?: string;\n error?: string;\n ref?: RefObject;\n hasArrow?: boolean;\n placeholder?: string;\n onChange?: (e: ChangeEvent) => void;\n children: any;\n};\n\nconst Select: FC = (props) => {\n const {\n id,\n value,\n label,\n hasArrow,\n error,\n ref,\n placeholder,\n onChange,\n children,\n } = props;\n const labelText = error || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error && 'error',\n labelText && 'with-label',\n hasArrow && 'with-arrow',\n 'input-group',\n );\n\n return (\n
\n \n {children}\n \n {labelText && id && (\n \n )}\n
\n );\n};\n\nexport default memo(Select);\n","import React, {\n FC, useRef, useCallback, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\nimport useFocusAfterAnimation from '../../hooks/useFocusAfterAnimation';\nimport useLang from '../../hooks/useLang';\nimport { countryList } from '../../util/phoneNumber';\n\nimport InputText from '../ui/InputText';\nimport Select from '../ui/Select';\nimport Checkbox from '../ui/Checkbox';\n\nimport './ShippingInfo.scss';\n\nexport type OwnProps = {\n state: FormState;\n needEmail: boolean;\n needPhone: boolean;\n needName: boolean;\n needAddress: boolean;\n dispatch: FormEditDispatch;\n};\n\nconst ShippingInfo: FC = ({\n state,\n needEmail,\n needPhone,\n needName,\n needAddress,\n dispatch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const phoneRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const selectCountryRef = useRef(null);\n\n useEffect(() => {\n if (selectCountryRef.current\n && selectCountryRef.current.value !== state.countryIso2) {\n selectCountryRef.current.value = state.countryIso2;\n }\n }, [state.countryIso2]);\n\n const lang = useLang();\n\n useFocusAfterAnimation(inputRef);\n\n const handleAddress1Change = useCallback((e) => {\n dispatch({ type: 'changeAddress1', payload: e.target.value });\n }, [dispatch]);\n\n const handleAddress2Change = useCallback((e) => {\n dispatch({ type: 'changeAddress2', payload: e.target.value });\n }, [dispatch]);\n\n const handleCityChange = useCallback((e) => {\n dispatch({ type: 'changeCity', payload: e.target.value });\n }, [dispatch]);\n\n const handleStateChange = useCallback((e) => {\n dispatch({ type: 'changeState', payload: e.target.value });\n }, [dispatch]);\n\n const handleCountryChange = useCallback((e) => {\n dispatch({ type: 'changeCountry', payload: e.target.value });\n }, [dispatch]);\n\n const handlePostCodeChange = useCallback((e) => {\n dispatch({ type: 'changePostCode', payload: e.target.value });\n }, [dispatch]);\n\n const handleFullNameChange = useCallback((e) => {\n dispatch({ type: 'changeFullName', payload: e.target.value });\n }, [dispatch]);\n\n const handleEmailChange = useCallback((e) => {\n dispatch({ type: 'changeEmail', payload: e.target.value });\n }, [dispatch]);\n\n const handlePhoneChange = useCallback((e) => {\n let { value } = e.target;\n value = `+${value.replace(/\\D/g, '')}`;\n if (phoneRef.current) {\n phoneRef.current.value = value;\n }\n dispatch({ type: 'changePhone', payload: value });\n }, [dispatch]);\n\n const handleSaveInfoChange = useCallback((e) => {\n dispatch({ type: 'changeSaveInfo', payload: e.target.value });\n }, [dispatch]);\n\n const { formErrors } = state;\n return (\n
\n
\n {needAddress ? (\n
\n
{lang('PaymentShippingAddress')}
\n \n \n \n \n \n {countryList.map(({ name, id }) => (\n \n {name}\n \n ))}\n \n\n \n
\n ) : undefined}\n { needName || needEmail || needPhone ? (\n
{lang('PaymentShippingReceiver')}
\n ) : undefined }\n { needName && (\n \n ) }\n { needEmail && (\n \n ) }\n { needPhone && (\n \n ) }\n \n \n
\n );\n};\n\nexport default memo(ShippingInfo);\n","import React, {\n FC, useCallback, memo, useMemo, useEffect,\n} from '../../lib/teact/teact';\n\nimport { ShippingOption } from '../../types/index';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\n\nimport RadioGroup from '../ui/RadioGroup';\n\nimport './Shipping.scss';\n\nexport type OwnProps = {\n state: FormState;\n shippingOptions: ShippingOption[];\n currency: string;\n dispatch: FormEditDispatch;\n};\n\nconst Shipping: FC = ({\n state,\n shippingOptions,\n currency,\n dispatch,\n}) => {\n useEffect(() => {\n if (!shippingOptions || state.shipping) {\n return;\n }\n dispatch({ type: 'changeShipping', payload: shippingOptions[0].id });\n }, [shippingOptions, state.shipping, dispatch]);\n\n const handleShippingSelect = useCallback((value) => {\n dispatch({ type: 'changeShipping', payload: value });\n }, [dispatch]);\n\n const options = useMemo(() => (shippingOptions.map(({ id: value, title: label, amount }) => ({\n label,\n subLabel: `${currency} ${String(amount / 100)}`,\n value,\n }))), [shippingOptions, currency]);\n\n return (\n
\n
\n

Select shipping method

\n \n \n
\n );\n};\n\nexport default memo(Shipping);\n","import React, {\n FC, memo,\n} from '../../lib/teact/teact';\n\nimport { Price } from '../../types';\n\nimport './Checkout.scss';\n\nexport type OwnProps = {\n invoiceContent?: {\n title?: string;\n description?: string;\n text?: string;\n photoUrl?: string;\n };\n checkoutInfo?: {\n paymentMethod?: string;\n paymentProvider?: string;\n shippingAddress?: string;\n name?: string;\n phone?: string;\n shippingMethod?: string;\n };\n prices?: Price[];\n totalPrice?: number;\n shippingPrices?: Price[];\n currency?: string;\n};\n\nconst Checkout: FC = ({\n invoiceContent,\n prices,\n shippingPrices,\n checkoutInfo,\n currency,\n totalPrice,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const { photoUrl, title, text } = (invoiceContent || {});\n const {\n paymentMethod,\n paymentProvider,\n shippingAddress,\n name,\n phone,\n shippingMethod,\n } = (checkoutInfo || {});\n return (\n
\n
\n { photoUrl && (\n \"\"\n )}\n
\n
{ title }
\n

{ text }

\n
\n
\n
\n { prices && prices.map((item) => (\n renderPaymentItem(item.label, item.amount, currency, false)\n )) }\n { shippingPrices && shippingPrices.map((item) => (\n renderPaymentItem(item.label, item.amount, currency, false)\n )) }\n { totalPrice !== undefined && (\n renderPaymentItem('Total', totalPrice, currency, true)\n ) }\n
\n
\n {paymentMethod && renderCheckoutItem('icon-card', paymentMethod, 'Payment method')}\n {paymentProvider && renderCheckoutItem('stripe-provider', paymentProvider, 'Payment provider')}\n {shippingAddress && renderCheckoutItem('icon-location', shippingAddress, 'Shipping address')}\n {name && renderCheckoutItem('icon-user', name, 'Name')}\n {phone && renderCheckoutItem('icon-phone', phone, 'Phone number')}\n {shippingMethod && renderCheckoutItem('icon-truck', shippingMethod, 'Shipping method')}\n
\n
\n );\n};\n\nfunction renderPaymentItem(title: string, value: number, currency?: string, main = false) {\n return (\n
\n
\n { title }\n
\n
\n { `${currency || ''} ${(value / 100).toFixed(2)}` }\n
\n
\n );\n}\n\nfunction renderCheckoutItem(icon: string, title: string, data: string) {\n return (\n
\n \n
\n
\n { title }\n
\n

\n { data }\n

\n
\n
\n );\n}\n\nexport default memo(Checkout);\n","import React, {\n FC, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { formatCardExpiry } from '../middle/helpers/inputFormatters';\n\nimport InputText from '../ui/InputText';\n\nconst MAX_FIELD_LENGTH = 5;\n\nexport type OwnProps = {\n value: string;\n error?: string;\n onChange: (value: string) => void;\n};\n\nconst ExpiryInput : FC = ({ value, error, onChange }) => {\n // eslint-disable-next-line no-null/no-null\n const expiryInputRef = useRef(null);\n\n const handleKeyDown = useCallback((e) => {\n if (e.key === 'Backspace' && value.charAt(value.length - 1) === '/') {\n const newValue = value.slice(0, value.length - 1);\n if (expiryInputRef.current) {\n expiryInputRef.current.value = newValue;\n }\n }\n }, [value]);\n\n const handleChange = useCallback((e) => {\n onChange(formatCardExpiry(e.target.value));\n }, [onChange]);\n\n return (\n \n );\n};\n\nexport default memo(ExpiryInput);\n","export function formatCardExpiry(input: string) {\n input = input.replace(/[^\\d]/g, '').slice(0, 4);\n const parts = input.match(/.{1,2}/g);\n if (parts && parts[0] && Number(parts[0]) > 12) {\n parts[0] = '12';\n }\n if (parts && parts[0] && parts[0].length === 2 && !parts[1]) {\n parts[1] = '';\n }\n return parts ? parts.join('/') : '';\n}\n\nexport function formatCardNumber(input: string) {\n input = input.replace(/[^\\d]/g, '');\n const parts = input.match(/.{1,4}/g);\n return parts ? parts.join(' ') : '';\n}\n","export default __webpack_public_path__ + \"mastercard.4216118edafe23cc2dec7b8807ba4622.svg\";","export default __webpack_public_path__ + \"visa.e5a7c336e1deb4b92a636e2e053878c4.svg\";","import React, {\n FC, memo, useCallback, useState, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport useFocusAfterAnimation from '../../hooks/useFocusAfterAnimation';\nimport { formatCardNumber } from '../middle/helpers/inputFormatters';\nimport { detectCardType, CardType } from '../common/helpers/detectCardType';\n\nimport InputText from '../ui/InputText';\n\nimport './CardInput.scss';\n\n// @ts-ignore\nimport mastercardIconPath from '../../assets/mastercard.svg';\n// @ts-ignore\nimport visaIconPath from '../../assets/visa.svg';\n\nconst CARD_NUMBER_MAX_LENGTH = 23;\n\nexport type OwnProps = {\n value: string;\n error?: string;\n onChange: (value: string) => void;\n};\n\nconst CardInput : FC = ({ value, error, onChange }) => {\n // eslint-disable-next-line no-null/no-null\n const cardNumberRef = useRef(null);\n\n useFocusAfterAnimation(cardNumberRef);\n\n const [cardType, setCardType] = useState(CardType.Default);\n useEffect(() => {\n const newCardType = detectCardType(value);\n setCardType(newCardType);\n // eslint-disable-next-line\n }, []);\n\n const handleChange = useCallback((e) => {\n const newValue = formatCardNumber(e.target.value);\n const newCardType = detectCardType(e.target.value);\n setCardType(newCardType);\n onChange(newValue);\n if (cardNumberRef.current) {\n cardNumberRef.current.value = newValue;\n }\n }, [onChange, cardNumberRef]);\n\n const cardIcon = getCardIcon(cardType);\n\n return (\n
\n {cardIcon}\n \n
\n );\n};\n\nexport default memo(CardInput);\n\nfunction getCardIcon(cardType: CardType) {\n switch (cardType) {\n case CardType.Mastercard:\n return \"\";\n case CardType.Visa:\n return \"\";\n default:\n return undefined;\n }\n}\n","import React, {\n FC, useCallback, memo, useRef, useEffect,\n} from '../../lib/teact/teact';\n\nimport { FormState, FormEditDispatch } from '../../hooks/reducers/usePaymentReducer';\nimport useLang from '../../hooks/useLang';\nimport { countryList } from '../../util/phoneNumber';\n\nimport InputText from '../ui/InputText';\nimport Checkbox from '../ui/Checkbox';\nimport Select from '../ui/Select';\nimport ExpiryInput from './ExpiryInput';\nimport CardInput from './CardInput';\n\nimport './PaymentInfo.scss';\n\nexport type OwnProps = {\n state: FormState;\n canSaveCredentials: boolean;\n needCardholderName?: boolean;\n needCountry?: boolean;\n needZip?: boolean;\n dispatch: FormEditDispatch;\n};\n\nconst PaymentInfo: FC = ({\n state,\n canSaveCredentials,\n needCardholderName,\n needCountry,\n needZip,\n dispatch,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const selectCountryRef = useRef(null);\n\n useEffect(() => {\n if (selectCountryRef.current\n && selectCountryRef.current.value !== state.billingCountry) {\n selectCountryRef.current.value = state.billingCountry;\n }\n }, [state.billingCountry]);\n\n const handleCardNumberChange = useCallback((value) => {\n dispatch({ type: 'changeCardNumber', payload: value });\n }, [dispatch]);\n\n const handleCardholderChange = useCallback((e) => {\n dispatch({ type: 'changeCardholder', payload: e.target.value.toUpperCase() });\n }, [dispatch]);\n\n const handleExpiryChange = useCallback((value) => {\n dispatch({ type: 'changeExpiryDate', payload: value });\n }, [dispatch]);\n\n const handleCvvChange = useCallback((e) => {\n dispatch({ type: 'changeCvvCode', payload: e.target.value });\n }, [dispatch]);\n\n const handleCountryChange = useCallback((e) => {\n dispatch({ type: 'changeBillingCountry', payload: e.target.value });\n }, [dispatch]);\n\n const handleBillingPostCodeChange = useCallback((e) => {\n dispatch({ type: 'changeBillingZip', payload: e.target.value });\n }, [dispatch]);\n\n const handleChangeSaveCredentials = useCallback((e) => {\n dispatch({ type: 'changeSaveCredentials', payload: e.target.value });\n }, [dispatch]);\n\n const lang = useLang();\n\n const { formErrors = {} } = state;\n\n return (\n
\n
\n
{lang('PaymentCardTitle')}
\n \n { needCardholderName && (\n \n )}\n
\n \n \n
\n { needCountry || needZip ? (\n
{lang('PaymentBillingAddress')}
\n ) : undefined }\n { needCountry && (\n \n {\n countryList.map(({ name }) => (\n \n {name}\n \n ))\n }\n \n ) }\n { needZip && (\n \n )}\n { canSaveCredentials && (\n \n ) }\n \n
\n );\n};\n\nexport default memo(PaymentInfo);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { PaymentStep, ShippingOption, Price } from '../../types';\nimport { ApiError } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport { getCurrencySign } from '../middle/helpers/getCurrencySign';\nimport { detectCardTypeText } from '../common/helpers/detectCardType';\nimport { getShippingError } from '../../modules/helpers/payments';\nimport usePaymentReducer, { FormState } from '../../hooks/reducers/usePaymentReducer';\nimport useLang from '../../hooks/useLang';\n\nimport ShippingInfo from './ShippingInfo';\nimport Shipping from './Shipping';\nimport Checkout from './Checkout';\nimport PaymentInfo from './PaymentInfo';\nimport Button from '../ui/Button';\nimport Modal from '../ui/Modal';\nimport Transition from '../ui/Transition';\nimport Spinner from '../ui/Spinner';\n\nimport './PaymentModal.scss';\n\nconst DEFAULT_PROVIDER = 'stripe';\n\nexport type OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n nameRequested?: boolean;\n shippingAddressRequested?: boolean;\n phoneRequested?: boolean;\n emailRequested?: boolean;\n flexible?: boolean;\n phoneToProvider?: boolean;\n emailToProvider?: boolean;\n currency?: string;\n prices?: Price[];\n isProviderError: boolean;\n needCardholderName?: boolean;\n needCountry?: boolean;\n needZip?: boolean;\n globalErrors?: ApiError[];\n};\n\ntype GlobalStateProps = Pick;\n\ntype DispatchProps = Pick;\n\nconst Invoice: FC = ({\n isOpen,\n onClose,\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n nameRequested,\n shippingAddressRequested,\n phoneRequested,\n emailRequested,\n phoneToProvider,\n emailToProvider,\n currency,\n passwordMissing,\n isProviderError,\n invoiceContent,\n nativeProvider,\n prices,\n needCardholderName,\n needCountry,\n needZip,\n error,\n globalErrors,\n validateRequestedInfo,\n sendPaymentForm,\n setPaymentStep,\n sendCredentialsInfo,\n clearPaymentError,\n}) => {\n const [paymentState, paymentDispatch] = usePaymentReducer();\n const currencySign = getCurrencySign(currency);\n const [isLoading, setIsLoading] = useState(false);\n const lang = useLang();\n\n useEffect(() => {\n if (step || error || globalErrors) {\n setIsLoading(false);\n }\n }, [step, error, globalErrors]);\n\n useEffect(() => {\n if (error && error.field) {\n paymentDispatch({\n type: 'setFormErrors',\n payload: {\n [error.field]: error.fieldError,\n },\n });\n return;\n }\n if (globalErrors && globalErrors.length) {\n const errors = getShippingError(globalErrors);\n paymentDispatch({\n type: 'setFormErrors',\n payload: {\n ...errors,\n },\n });\n }\n }, [error, globalErrors, paymentDispatch]);\n\n useEffect(() => {\n if (savedInfo) {\n const {\n name: fullName, phone, email, shippingAddress,\n } = savedInfo;\n paymentDispatch({\n type: 'updateUserInfo',\n payload: {\n fullName,\n phone: phone && phone.charAt(0) !== '+'\n ? `+${phone}`\n : phone,\n email,\n ...(shippingAddress || {}),\n },\n });\n }\n }, [savedInfo, paymentDispatch]);\n\n const handleErrorModalClose = useCallback(() => {\n clearPaymentError();\n }, [clearPaymentError]);\n\n const totalPrice = useMemo(() => {\n if (step !== PaymentStep.Checkout) {\n return 0;\n }\n\n return getTotalPrice(prices, shippingOptions, paymentState.shipping);\n }, [step, paymentState.shipping, prices, shippingOptions]);\n\n const checkoutInfo = useMemo(() => {\n if (step !== PaymentStep.Checkout) {\n return undefined;\n }\n return getCheckoutInfo(paymentState, shippingOptions, nativeProvider || '');\n }, [step, paymentState, shippingOptions, nativeProvider]);\n\n function renderError() {\n if (!error) {\n return undefined;\n }\n return (\n \n

{error.description || 'Error'}

\n

{error.description || 'Error'}

\n \n {lang('OK')}\n \n
\n );\n }\n\n function renderModalContent(cuurentStep: PaymentStep) {\n switch (cuurentStep) {\n case PaymentStep.ShippingInfo:\n return (\n \n );\n case PaymentStep.Shipping:\n return (\n \n );\n case PaymentStep.PaymentInfo:\n return (\n \n );\n case PaymentStep.Checkout:\n return (\n \n );\n default:\n return undefined;\n }\n }\n\n const validateRequest = useCallback(() => {\n const { saveInfo } = paymentState;\n const requestInfo = getRequestInfo(paymentState);\n validateRequestedInfo({ requestInfo, saveInfo });\n }, [validateRequestedInfo, paymentState]);\n\n const sendCredentials = useCallback(() => {\n const credentials = getCredentials(paymentState);\n sendCredentialsInfo({\n credentials,\n });\n }, [sendCredentialsInfo, paymentState]);\n\n const sendForm = useCallback(() => {\n sendPaymentForm({\n shippingOptionId: paymentState.shipping,\n saveCredentials: paymentState.saveCredentials,\n });\n }, [sendPaymentForm, paymentState]);\n\n const setStep = useCallback((nextStep) => {\n setPaymentStep({ step: nextStep });\n }, [setPaymentStep]);\n\n const handleButtonClick = useCallback(() => {\n setIsLoading(true);\n switch (step) {\n case PaymentStep.ShippingInfo:\n return validateRequest();\n case PaymentStep.Shipping:\n return setStep(PaymentStep.PaymentInfo);\n case PaymentStep.PaymentInfo:\n return sendCredentials();\n case PaymentStep.Checkout:\n return sendForm();\n default:\n return () => {};\n }\n }, [step, validateRequest, setStep, sendCredentials, sendForm]);\n\n const modalHeader = useMemo(() => {\n switch (step) {\n case PaymentStep.ShippingInfo:\n return lang('PaymentShippingInfo');\n case PaymentStep.Shipping:\n return lang('PaymentShippingMethod');\n case PaymentStep.PaymentInfo:\n return lang('PaymentCardInfo');\n case PaymentStep.Checkout:\n return lang('PaymentCheckout');\n default:\n return '';\n }\n }, [step, lang]);\n\n const buttonText = useMemo(() => {\n switch (step) {\n case PaymentStep.Checkout:\n return lang('Checkout.PayPrice', `${currencySign}${(totalPrice / 100).toFixed(2)}`);\n default:\n return lang('Next');\n }\n }, [step, lang, currencySign, totalPrice]);\n\n if (isProviderError) {\n return (\n \n

\n Sorry, Telegram T doesn't support payments with this provider yet.
\n Please use one of our mobile apps to do this.\n

\n \n {lang('OK')}\n \n \n );\n }\n\n return (\n \n
\n \n \n \n

{modalHeader}

\n
\n {step !== undefined ? (\n \n {() => (\n
\n {renderModalContent(step)}\n
\n )}\n
\n ) : (\n
\n \n
\n )}\n
\n \n {buttonText}\n \n
\n {error && !error.field && renderError()}\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps & GlobalStateProps => {\n const {\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n invoice,\n invoiceContent,\n nativeProvider,\n nativeParams,\n passwordMissing,\n error,\n } = global.payment;\n\n const isProviderError = Boolean(invoice && (!nativeProvider || nativeProvider !== DEFAULT_PROVIDER));\n const { needCardholderName, needCountry, needZip } = (nativeParams || {});\n const {\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = (invoice || {});\n\n return {\n step,\n shippingOptions,\n savedInfo,\n canSaveCredentials,\n nativeProvider,\n passwordMissing,\n nameRequested,\n shippingAddressRequested,\n phoneRequested,\n emailRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n isProviderError,\n invoiceContent,\n needCardholderName,\n needCountry,\n needZip,\n error,\n globalErrors: global.errors,\n };\n },\n (setGlobal, actions): DispatchProps => {\n return pick(actions, [\n 'validateRequestedInfo',\n 'sendPaymentForm',\n 'setPaymentStep',\n 'sendCredentialsInfo',\n 'clearPaymentError',\n ]);\n },\n)(Invoice));\n\nfunction findShippingOption(shippingOptions: ShippingOption[], optionId: string) {\n return shippingOptions.find(({ id }) => id === optionId);\n}\n\nfunction getShippingPrices(shippingOptions: ShippingOption[], shippingOption: string) {\n const option = findShippingOption(shippingOptions, shippingOption);\n return option ? option.prices : undefined;\n}\n\nfunction getTotalPrice(prices: Price[] = [], shippingOptions: ShippingOption[] | undefined, shippingOption: string) {\n const shippingPrices = shippingOptions\n ? getShippingPrices(shippingOptions, shippingOption)\n : [];\n let total = 0;\n const totalPrices = prices.concat(shippingPrices || []);\n total = totalPrices.reduce((acc, cur) => {\n return acc + cur.amount;\n }, total);\n return total;\n}\n\nfunction getCheckoutInfo(state: FormState, shippingOptions: ShippingOption[] | undefined, paymentProvider: string) {\n const cardTypeText = detectCardTypeText(state.cardNumber);\n const paymentMethod = `${cardTypeText} *${state.cardNumber.slice(-4)}`;\n const shippingAddress = state.streetLine1\n ? `${state.streetLine1}, ${state.city}, ${state.countryIso2}`\n : undefined;\n const { phone, fullName: name } = state;\n const shippingOption = shippingOptions ? findShippingOption(shippingOptions, state.shipping) : undefined;\n const shippingMethod = shippingOption ? shippingOption.title : undefined;\n return {\n paymentMethod,\n paymentProvider,\n shippingAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n\nfunction getRequestInfo(paymentState: FormState) {\n const {\n streetLine1,\n streetLine2,\n city,\n state,\n countryIso2,\n postCode,\n fullName: name,\n phone,\n email,\n } = paymentState;\n\n const shippingAddress = {\n streetLine1,\n streetLine2,\n city,\n state,\n countryIso2,\n postCode,\n };\n\n return {\n name,\n phone,\n email,\n shippingAddress,\n };\n}\n\nfunction getCredentials(paymentState: FormState) {\n const {\n cardNumber, cardholder, expiry, cvv, billingCountry, billingZip,\n } = paymentState;\n const [expiryMonth, expiryYear] = expiry.split('/');\n const data = {\n cardNumber,\n cardholder,\n expiryMonth,\n expiryYear,\n cvv,\n country: billingCountry,\n zip: billingZip,\n };\n\n return {\n data,\n };\n}\n","import React, {\n FC, memo, useMemo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { Price } from '../../types';\nimport { ApiShippingAddress } from '../../api/types/payments';\n\nimport useLang from '../../hooks/useLang';\nimport { getCurrencySign } from '../middle/helpers/getCurrencySign';\n\nimport Checkout from './Checkout';\nimport Modal from '../ui/Modal';\nimport Button from '../ui/Button';\n\nimport './PaymentModal.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n onClose: () => void;\n};\n\ntype StateProps = {\n prices?: Price[];\n shippingPrices: any;\n totalAmount?: number;\n currency?: string;\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n photoUrl?: string;\n text?: string;\n title?: string;\n credentialsTitle?: string;\n shippingMethod?: string;\n};\n\nconst ReceiptModal: FC = ({\n isOpen,\n onClose,\n prices,\n shippingPrices,\n totalAmount,\n currency,\n info,\n photoUrl,\n text,\n title,\n credentialsTitle,\n shippingMethod,\n}) => {\n const lang = useLang();\n const currencySign = getCurrencySign(currency);\n const checkoutInfo = useMemo(() => {\n return getCheckoutInfo(credentialsTitle, info, shippingMethod);\n }, [info, shippingMethod, credentialsTitle]);\n return (\n \n
\n
\n \n \n \n

{lang('PaymentReceipt')}

\n
\n
\n \n
\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { receipt } = global.payment;\n const {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n } = (receipt || {});\n\n return {\n currency,\n prices: mapedPrices,\n info,\n totalAmount,\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n photoUrl,\n text,\n title,\n };\n },\n)(ReceiptModal));\n\nfunction getCheckoutInfo(paymentMethod?: string,\n info?:\n { phone?: string;\n name?: string;\n shippingAddress?: ApiShippingAddress;\n },\n shippingMethod?: string) {\n if (!info) {\n return { paymentMethod };\n }\n const { shippingAddress } = info;\n const fullAddress = shippingAddress && shippingAddress.streetLine1\n ? `${shippingAddress.streetLine1}, ${shippingAddress.city}, ${shippingAddress.countryIso2}`\n : undefined;\n const { phone, name } = info;\n return {\n paymentMethod,\n paymentProvider: 'Stripe',\n shippingAddress: fullAddress,\n name,\n phone,\n shippingMethod,\n };\n}\n","import { ApiMediaFormat } from '../../../api/types';\n\nimport * as mediaLoader from '../../../util/mediaLoader';\n\n// @ts-ignore\nimport MonkeyIdle from '../../../assets/TwoFactorSetupMonkeyIdle.tgs';\n// @ts-ignore\nimport MonkeyTracking from '../../../assets/TwoFactorSetupMonkeyTracking.tgs';\n// @ts-ignore\nimport MonkeyClose from '../../../assets/TwoFactorSetupMonkeyClose.tgs';\n// @ts-ignore\nimport MonkeyPeek from '../../../assets/TwoFactorSetupMonkeyPeek.tgs';\n// @ts-ignore\nimport FoldersAll from '../../../assets/FoldersAll.tgs';\n// @ts-ignore\nimport FoldersNew from '../../../assets/FoldersNew.tgs';\n// @ts-ignore\nimport DiscussionGroups from '../../../assets/DiscussionGroupsDucks.tgs';\n\nexport const ANIMATED_STICKERS_PATHS = {\n MonkeyIdle,\n MonkeyTracking,\n MonkeyClose,\n MonkeyPeek,\n FoldersAll,\n FoldersNew,\n DiscussionGroups,\n};\n\nexport default function getAnimationData(name: keyof typeof ANIMATED_STICKERS_PATHS) {\n const path = ANIMATED_STICKERS_PATHS[name].replace(window.location.origin, '');\n\n return mediaLoader.fetch(`file${path}`, ApiMediaFormat.Lottie);\n}\n","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyIdle.dea4a492c144df84ddab778dc8a3f0cd.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyTracking.eb5a7a6f166fb7589c12e6248561fb58.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyClose.604c4c833d322b7e6c3ea19bef058241.tgs\";","export default __webpack_public_path__ + \"TwoFactorSetupMonkeyPeek.1905436b042520363d7e59f5d7f903ab.tgs\";","export default __webpack_public_path__ + \"FoldersAll.3f9f9e243d19f0fbf9aaaff11cbd4572.tgs\";","export default __webpack_public_path__ + \"FoldersNew.9a40d71c0c8be70f5bd14ff2d7bc1593.tgs\";","export default __webpack_public_path__ + \"DiscussionGroupsDucks.9ea453d1be9d1b0ee77a992f8e587485.tgs\";","import React, {\n FC, useEffect, useState, memo,\n} from '../../lib/teact/teact';\n\nimport { DEBUG } from '../../config';\nimport { blobToFile, blobToDataUri } from '../../util/files';\nimport useLang from '../../hooks/useLang';\n\nimport Button from './Button';\nimport Modal from './Modal';\nimport Loading from './Loading';\n\nimport './CropModal.scss';\n\n// Change to 'base64' to get base64-encoded string\nconst cropperResultOptions: Croppie.ResultOptions & { type: 'blob' } = {\n type: 'blob',\n quality: 0.8,\n format: 'jpeg',\n circle: false,\n};\n\ntype ICroppie = typeof import('croppie');\nlet Croppie: ICroppie;\nlet croppiePromise: Promise<{ default: ICroppie }>;\n\nasync function ensureCroppie() {\n if (!croppiePromise) {\n croppiePromise = import('../../lib/croppie') as unknown as Promise<{ default: ICroppie }>;\n Croppie = (await croppiePromise).default;\n }\n\n return croppiePromise;\n}\n\nlet cropper: Croppie;\n\nasync function initCropper(imgFile: File) {\n try {\n const cropContainer = document.getElementById('avatar-crop');\n if (!cropContainer) {\n return;\n }\n\n const { offsetWidth, offsetHeight } = cropContainer;\n\n cropper = new Croppie(cropContainer, {\n enableZoom: true,\n boundary: {\n width: offsetWidth,\n height: offsetHeight,\n },\n viewport: {\n width: offsetWidth - 16,\n height: offsetHeight - 16,\n type: 'circle',\n },\n });\n\n const dataUri = await blobToDataUri(imgFile);\n await cropper.bind({ url: dataUri });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n}\n\ntype OwnProps = {\n file?: File;\n onChange: (file: File) => void;\n onClose: () => void;\n};\n\nconst CropModal: FC = ({ file, onChange, onClose }: OwnProps) => {\n const [isCroppieReady, setIsCroppieReady] = useState(false);\n\n useEffect(() => {\n if (!file) {\n return;\n }\n\n if (!isCroppieReady) {\n ensureCroppie().then(() => setIsCroppieReady(true));\n\n return;\n }\n\n initCropper(file);\n }, [file, isCroppieReady]);\n\n const lang = useLang();\n\n async function handleCropClick() {\n if (!cropper) {\n return;\n }\n\n const result: Blob | string = await cropper.result(cropperResultOptions);\n const croppedImg = typeof result === 'string' ? result : blobToFile(result, 'avatar.jpg');\n\n onChange(croppedImg);\n }\n\n return (\n \n {isCroppieReady ? (\n
\n ) : (\n \n )}\n \n \n \n \n );\n};\n\nexport default memo(CropModal);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport CropModal from './CropModal';\n\nimport './AvatarEditable.scss';\n\ninterface OwnProps {\n title?: string;\n disabled?: boolean;\n currentAvatarBlobUrl?: string;\n onChange: (file: File) => void;\n}\n\nconst AvatarEditable: FC = ({\n title = 'Change your profile picture',\n disabled,\n currentAvatarBlobUrl,\n onChange,\n}) => {\n const [selectedFile, setSelectedFile] = useState();\n const [croppedBlobUrl, setCroppedBlobUrl] = useState(currentAvatarBlobUrl);\n\n useEffect(() => {\n setCroppedBlobUrl(currentAvatarBlobUrl);\n }, [currentAvatarBlobUrl]);\n\n function handleSelectFile(event: ChangeEvent) {\n const target = event.target as HTMLInputElement;\n\n if (!target || !target.files || !target.files[0]) {\n return;\n }\n\n setSelectedFile(target.files[0]);\n target.value = '';\n }\n\n function handleAvatarCrop(croppedImg: File) {\n setSelectedFile(undefined);\n onChange(croppedImg);\n\n if (croppedBlobUrl) {\n URL.revokeObjectURL(croppedBlobUrl);\n }\n setCroppedBlobUrl(URL.createObjectURL(croppedImg));\n }\n\n function handleModalClose() {\n setSelectedFile(undefined);\n }\n\n const labelClassName = buildClassName(\n croppedBlobUrl && 'filled',\n disabled && 'disabled',\n );\n\n return (\n
\n \n \n \n {croppedBlobUrl && \"Avatar\"}\n \n \n
\n );\n};\n\nexport default memo(AvatarEditable);\n","import React, {\n FC, useState, useEffect, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { STICKER_SIZE_AUTH, STICKER_SIZE_AUTH_MOBILE, STICKER_SIZE_TWO_FA } from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport getAnimationData from './helpers/animatedAssets';\n\nimport AnimatedSticker from './AnimatedSticker';\n\nimport './PasswordMonkey.scss';\n\ntype OwnProps = {\n isPasswordVisible: boolean;\n isBig?: boolean;\n};\n\nconst PEEK_MONKEY_SHOW_DELAY = 2000;\nconst SEGMENT_COVER_EYES: [number, number] = [0, 50];\nconst SEGMENT_UNCOVER_EYE: [number, number] = [0, 20];\nconst SEGMENT_COVER_EYE: [number, number] = [20, 0];\nconst STICKER_SIZE = IS_MOBILE_SCREEN ? STICKER_SIZE_AUTH_MOBILE : STICKER_SIZE_AUTH;\n\nconst PasswordMonkey: FC = ({ isPasswordVisible, isBig }) => {\n const [closeMonkeyData, setCloseMonkeyData] = useState>();\n const [peekMonkeyData, setPeekMonkeyData] = useState>();\n const [isFirstMonkeyLoaded, setIsFirstMonkeyLoaded] = useState(false);\n const [isPeekShown, setIsPeekShown] = useState(false);\n\n useEffect(() => {\n if (!closeMonkeyData) {\n getAnimationData('MonkeyClose').then(setCloseMonkeyData);\n } else {\n setTimeout(() => setIsPeekShown(true), PEEK_MONKEY_SHOW_DELAY);\n }\n }, [closeMonkeyData]);\n\n useEffect(() => {\n if (!peekMonkeyData) {\n getAnimationData('MonkeyPeek').then(setPeekMonkeyData);\n }\n }, [peekMonkeyData]);\n\n const handleFirstMonkeyLoad = useCallback(() => setIsFirstMonkeyLoaded(true), []);\n\n return (\n
\n {!isFirstMonkeyLoaded && (\n
\n )}\n {closeMonkeyData && (\n \n )}\n {peekMonkeyData && (\n \n )}\n
\n );\n};\n\nexport default memo(PasswordMonkey);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\n\nimport { MIN_PASSWORD_LENGTH } from '../../config';\nimport { IS_TOUCH_ENV, IS_MOBILE_SCREEN } from '../../util/environment';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\ntype OwnProps = {\n submitLabel?: string;\n error?: string;\n hint?: string;\n placeholder?: string;\n isLoading?: boolean;\n isPasswordVisible?: boolean;\n clearError: NoneToVoidFunction;\n onChangePasswordVisibility: (state: boolean) => void;\n onInputChange?: (password: string) => void;\n onSubmit: (password: string) => void;\n};\n\nconst FOCUS_DELAY_TIMEOUT_MS = IS_MOBILE_SCREEN ? 550 : 400;\n\nconst PasswordForm: FC = ({\n isLoading = false,\n isPasswordVisible,\n error,\n hint,\n placeholder = 'Password',\n submitLabel = 'Next',\n clearError,\n onChangePasswordVisibility,\n onInputChange,\n onSubmit,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const lang = useLang();\n\n const [password, setPassword] = useState('');\n const [canSubmit, setCanSubmit] = useState(false);\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n setTimeout(() => {\n inputRef.current!.focus();\n }, FOCUS_DELAY_TIMEOUT_MS);\n }\n }, []);\n\n useEffect(() => {\n if (error) {\n requestAnimationFrame(() => {\n inputRef.current!.focus();\n inputRef.current!.select();\n });\n }\n }, [error]);\n\n function onPasswordChange(e: ChangeEvent) {\n if (error) {\n clearError();\n }\n\n const { target } = e;\n setPassword(target.value);\n setCanSubmit(target.value.length >= MIN_PASSWORD_LENGTH);\n if (onInputChange) {\n onInputChange(target.value);\n }\n }\n\n function togglePasswordVisibility() {\n onChangePasswordVisibility(!isPasswordVisible);\n }\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (isLoading) {\n return;\n }\n\n if (canSubmit) {\n onSubmit(password);\n }\n }\n\n return (\n
\n \n \n \n \n \n
\n
\n {canSubmit && (\n \n )}\n \n );\n};\n\nexport default memo(PasswordForm);\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/4.92917cccdb4999ea7d20.css b/dist/4.75225d931a1e76f26855.css similarity index 67% rename from dist/4.92917cccdb4999ea7d20.css rename to dist/4.75225d931a1e76f26855.css index 3ddaa5e4..96852adc 100644 --- a/dist/4.92917cccdb4999ea7d20.css +++ b/dist/4.75225d931a1e76f26855.css @@ -1 +1 @@ -.Switcher{display:inline-flex;align-items:center;position:relative;margin:0}.Switcher.disabled{opacity:.5}.Switcher.disabled,.Switcher.inactive{pointer-events:none}.Switcher.no-animation .widget,.Switcher.no-animation .widget:after,body.animation-level-0 .Switcher .widget,body.animation-level-0 .Switcher .widget:after{transition:none!important}.Switcher.no-animation .widget:active:after,body.animation-level-0 .Switcher .widget:active:after{width:1.125rem}.Switcher input{height:0;width:0;visibility:hidden;position:absolute;z-index:var(--z-below);opacity:0}.Switcher .widget{cursor:pointer;text-indent:-999px;width:2.125rem;height:.875rem;background:var(--color-gray);display:inline-block;border-radius:.5rem;position:relative;transition:background .2s ease-in}.Switcher .widget:after{content:"";position:absolute;top:-.125rem;left:0;width:1.125rem;height:1.125rem;background:var(--color-background);border-radius:.75rem;transition:.2s ease-out;border:.125rem solid var(--color-gray)}.Switcher input:checked+.widget{background:var(--color-primary)}.Switcher input:checked+.widget:after{left:calc(100% - 1.125rem);transform:translateX(calc(-100% + 1.125rem));border-color:var(--color-primary)}.Switcher .widget:active:after{width:1.25rem}#LeftMainHeader{position:relative}#LeftMainHeader .animated-menu-icon{position:absolute}#LeftMainHeader .animated-menu-icon,#LeftMainHeader .animated-menu-icon:after,#LeftMainHeader .animated-menu-icon:before{width:1.125rem;height:.125rem;border-radius:.125rem;background-color:var(--color-text-secondary);transition:transform .25s;transform:rotate(0)}#LeftMainHeader .animated-menu-icon:after,#LeftMainHeader .animated-menu-icon:before{position:absolute;left:0;content:""}#LeftMainHeader .animated-menu-icon:before{top:-.3125rem}#LeftMainHeader .animated-menu-icon:after{top:.3125rem}#LeftMainHeader .animated-menu-icon.state-back{transform:rotate(180deg)}#LeftMainHeader .animated-menu-icon.state-back:before{transform:rotate(45deg) scaleX(.75) translate(.375rem,-.1875rem)}#LeftMainHeader .animated-menu-icon.state-back:after{transform:rotate(-45deg) scaleX(.75) translate(.375rem,.1875rem)}#LeftMainHeader .archived-badge{min-width:1.5rem;height:1.5rem;margin-left:auto;background:var(--color-gray);border-radius:.75rem;padding:0 .45rem;color:#fff;font-size:.875rem;line-height:1.5rem;font-weight:500;text-align:center;flex-shrink:0}#LeftMainHeader [dir=rtl] .archived-badge{margin-left:0;margin-right:auto}#LeftMainHeader .Menu .bubble{min-width:17rem}.Transition>div:not(.active) #LeftMainHeader .Menu .bubble,body.animating-right-column #LeftMainHeader .Menu .bubble{transition:none!important}#ConnectionState{flex:0 0 auto;display:flex;align-items:center;margin:0 .5rem .5rem;padding:.75rem;background:var(--color-yellow);border-radius:var(--border-radius-default)}#ConnectionState>.Spinner{--spinner-size:1.75rem}#ConnectionState>.state-text{color:var(--color-text-lighter);font-weight:500;line-height:2rem;margin-inline-start:1.875rem;white-space:nowrap}@media (max-width:950px){#ConnectionState>.state-text{margin-inline-start:1.25rem}}.NewChatButton{position:absolute;right:1rem;bottom:1rem;transform:translateY(5rem);transition:transform .25s cubic-bezier(.34,1.56,.64,1)}body.animation-level-0 .NewChatButton{transform:none!important;opacity:0;transition:opacity .15s}body.animation-level-0 .NewChatButton.revealed{opacity:1}.NewChatButton.revealed{transform:translateY(0)}@media (max-width:600px){.NewChatButton.revealed{transform:translateZ(10px);transform-style:preserve-3d}}.NewChatButton.menu-is-open:before{content:"";display:block;position:absolute;top:-13rem;left:-11rem;right:-1rem;bottom:-1rem;z-index:-1}.is-touch-env .NewChatButton .Menu>.backdrop{position:absolute;left:-100vw;right:-100vw;top:-100vh;bottom:-100vh}.NewChatButton>.Button .icon-close,.NewChatButton>.Button .icon-new-chat-filled{position:absolute}.NewChatButton>.Button:not(.active) .icon-new-chat-filled{animation:grow-icon .4s ease-out}.NewChatButton>.Button:not(.active) .icon-close{animation:hide-icon .4s ease-out forwards}.NewChatButton>.Button.active .icon-close{animation:grow-icon .4s ease-out}.NewChatButton>.Button.active .icon-new-chat-filled{animation:hide-icon .4s ease-out forwards}#LeftColumn-main{height:100%;position:relative;display:flex;flex-direction:column;overflow:hidden;z-index:1}#LeftColumn-main>.Transition{flex:1;overflow:hidden}#LeftColumn-main .ChatFolders{height:100%;display:flex;flex-direction:column;overflow:hidden}#LeftColumn-main .ChatFolders .tabs-placeholder{height:2.625rem;transition:height .15s ease}#LeftColumn-main .ChatFolders .tabs-placeholder:not(.open){height:0}#LeftColumn-main .ChatFolders .TabList{justify-content:flex-start;padding-left:.5625rem;padding-bottom:1px;border-bottom:0;z-index:1}#LeftColumn-main .ChatFolders .Tab{flex:0 0 auto;padding-left:.625rem;padding-right:.625rem}#LeftColumn-main .ChatFolders .Tab>span{padding-left:.5rem;padding-right:.5rem}#LeftColumn-main .ChatFolders>.Transition{flex:1;overflow:hidden}#LeftColumn-main .chat-list,#LeftColumn-main .LeftSearch,#LeftColumn-main .RecentContacts,#LeftColumn-main .search-content{height:100%;overflow-y:auto}#LeftColumn{overflow:hidden}#NewChat{height:100%}.left-header{height:var(--header-height);padding:.375rem 1.25rem .5rem .8125rem;display:flex;align-items:center;flex-shrink:0;background-color:var(--color-background)}.left-header h3{margin-bottom:0;font-size:1.25rem;font-weight:500;margin-left:1.375rem}.left-header .SearchInput{margin-left:.875rem;max-width:calc(100% - 3.625rem)}@media (max-width:600px){.left-header .SearchInput{max-width:calc(100% - 3.375rem)}}@media (max-width:600px){.left-header{padding:.5rem}}.AudioPlayer{display:flex;margin-left:auto;margin-top:-.25rem;margin-bottom:-.25rem}body.animation-level-0 .AudioPlayer{transition:none!important}.AudioPlayer>.Button{flex-shrink:0;margin:.125rem}.AudioPlayer>.toggle-play{--color-text-secondary:var(--color-primary);--color-text-secondary-rgb:var(--color-primary-shade-rgb);--color-primary-shade:var(--color-green);--color-white:var(--color-background-own)}.MiddleHeader .AudioPlayer+.HeaderActions{margin-left:1.5rem}.AudioPlayer .toggle-play.smaller{width:3rem;height:3rem}.AudioPlayer .toggle-play.smaller i{font-size:1.625rem;margin-top:-.025rem}.AudioPlayer .toggle-play i{position:absolute;font-size:1.9375rem;margin-top:-.05rem}.AudioPlayer .toggle-play i.icon-play{margin-left:.1rem}.AudioPlayer .toggle-play .icon-pause,.AudioPlayer .toggle-play .icon-play{opacity:1;transform:scale(1);transition:opacity .4s,transform .6s cubic-bezier(.34,1.56,.64,1)}.AudioPlayer .toggle-play.loading .icon-pause,.AudioPlayer .toggle-play.loading .icon-play,.AudioPlayer .toggle-play.pause .icon-play,.AudioPlayer .toggle-play.play .icon-pause{opacity:0;transform:scale(.5)}.AudioPlayer-content{display:flex;justify-content:center;flex-direction:column;flex-shrink:1;padding:.25rem .5rem;position:relative;overflow:hidden;cursor:pointer;max-width:15rem;border-radius:var(--border-radius-messages-small)}.AudioPlayer-content:hover{background-color:var(--color-interactive-element-hover)}@media (min-width:1440px) and (max-width:1500px){.AudioPlayer-content{max-width:14rem}}.AudioPlayer .AudioPlayer-content .title{display:block;font-weight:500;font-size:.875rem!important;line-height:1rem;height:1rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.AudioPlayer-content .subtitle{font-size:.85rem!important;color:var(--color-text-secondary);line-height:1.125rem;height:1.125rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:.125rem 0 0}.MiddleHeader{display:flex;align-items:center;width:100%;box-shadow:0 2px 2px var(--color-light-shadow);background:var(--color-background);padding:.5rem .8125rem .5rem 1.5rem;position:relative;z-index:var(--z-middle-header)}@media (max-width:600px){.MiddleHeader{padding:.5rem;position:relative;transform:translateZ(10px);transform-style:preserve-3d}}.MiddleHeader .Transition{width:100%;min-width:0}.MiddleHeader .Transition>div{display:flex;align-items:center;width:100%}.MiddleHeader .back-button{margin-left:-.5rem;margin-right:.5rem;position:relative}@media (max-width:600px){.MiddleHeader .back-button{margin-left:0}}.MiddleHeader .back-button .unread-count{min-width:1.25rem;height:1.25rem;padding:0 .375rem;border-radius:.625rem;font-size:.75rem;line-height:1.25rem;font-weight:500;text-align:center;position:absolute;top:-.25rem;right:-.5rem;background:var(--color-gray);color:#fff;pointer-events:none}.MiddleHeader .back-button .unread-count.active{background:var(--color-primary)}.MiddleHeader .chat-info-wrapper{flex-grow:1;overflow:hidden}.MiddleHeader .header-tools{display:flex;align-items:center;justify-content:flex-end;margin-left:auto;flex-shrink:0}body.animation-level-0 .MiddleHeader .header-tools,body.animation-level-0 .MiddleHeader .header-tools .AudioPlayer,body.animation-level-0 .MiddleHeader .header-tools .HeaderActions,body.animation-level-0 .MiddleHeader .header-tools .HeaderPinnedMessage-wrapper{transition:none!important}@media (min-width:1276px) and (max-width:1439px){.MiddleHeader .header-tools .HeaderActions{transform:translateZ(0);transition:transform var(--layer-transition)}#Main.right-column-open .MiddleHeader .header-tools .HeaderActions{transform:translate3d(calc(var(--right-column-width)*-1),0,0)}}@media (min-width:1440px){.MiddleHeader .header-tools{transform:translateZ(0);transition:transform var(--layer-transition)}#Main.right-column-open .MiddleHeader .header-tools{transform:translate3d(calc(var(--right-column-width)*-1),0,0)}}.Transition>div:not(.active) .MiddleHeader .header-tools,body.animating-right-column .MiddleHeader .header-tools{pointer-events:none}@media (min-width:1276px) and (max-width:1439px){.MiddleHeader:not(.tools-stacked) .header-tools .AudioPlayer,.MiddleHeader:not(.tools-stacked) .header-tools .HeaderPinnedMessage-wrapper{opacity:1}#Main.right-column-open .MiddleHeader:not(.tools-stacked) .header-tools .AudioPlayer,#Main.right-column-open .MiddleHeader:not(.tools-stacked) .header-tools .HeaderPinnedMessage-wrapper{opacity:0}}.MiddleHeader.tools-stacked .header-tools .AudioPlayer,.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper{position:absolute;top:100%;left:0;right:0;height:2.875rem;overflow:hidden;box-shadow:0 2px 2px var(--color-light-shadow);display:flex;flex-direction:row-reverse;padding:.375rem .5rem .375rem .75rem;background:var(--color-background)}.MiddleHeader.tools-stacked .header-tools .AudioPlayer:before,.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper:before{content:"";display:block;position:absolute;top:-.1875rem;left:0;right:0;height:.125rem;box-shadow:0 .125rem .125rem var(--color-light-shadow)}.MiddleHeader.tools-stacked .header-tools .AudioPlayer .HeaderPinnedMessage,.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper .HeaderPinnedMessage{max-width:unset;margin-top:-.1875rem}.MiddleHeader.tools-stacked .header-tools .AudioPlayer{height:3.25rem;flex-direction:row;padding:.375rem .5rem}.MiddleHeader.tools-stacked .header-tools .AudioPlayer-content{padding:0 .5rem;flex-grow:1}.MiddleHeader.tools-stacked .header-tools .AudioPlayer>.Button{margin:0}.MiddleHeader.tools-stacked .header-tools .AudioPlayer>.player-close{margin-left:auto}.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage{flex-grow:1;padding-top:0;padding-bottom:0}.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage:before{top:.125rem;bottom:.125rem}.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage .message-text{max-width:none}@media (min-width:1150px){#Main.right-column-open .MiddleHeader.tools-stacked .header-tools .AudioPlayer,#Main.right-column-open .MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper{padding-right:calc(.5rem + var(--right-column-width))}}.MiddleHeader.tools-stacked.animated .header-tools .AudioPlayer,.MiddleHeader.tools-stacked.animated .header-tools .HeaderPinnedMessage-wrapper{animation:fade-in var(--layer-transition) forwards}body.animation-level-0 .MiddleHeader.tools-stacked.animated .header-tools .AudioPlayer,body.animation-level-0 .MiddleHeader.tools-stacked.animated .header-tools .HeaderPinnedMessage-wrapper{animation:none}.MiddleHeader h3{font-weight:500;font-size:1.125rem;line-height:1.375rem;white-space:pre;margin:0;overflow:hidden;text-overflow:ellipsis;unicode-bidi:plaintext}@media (max-width:600px){.MiddleHeader h3{display:block;overflow:hidden;text-overflow:ellipsis}}@media (min-width:1275px){#Main.right-column-open .MiddleHeader h3{max-width:calc(100% - var(--right-column-width))}}.MiddleHeader .ChatInfo{cursor:pointer;display:flex;align-items:center}.MiddleHeader .ChatInfo .info{display:flex;flex-direction:column;justify-content:center;flex-grow:1;overflow:hidden}.MiddleHeader .ChatInfo .title{display:flex;align-items:center}.MiddleHeader .ChatInfo .title .VerifiedIcon{width:1.25rem;height:1.25rem;margin-left:.25rem;margin-top:.05rem}.MiddleHeader .ChatInfo .status,.MiddleHeader .ChatInfo .user-status{unicode-bidi:plaintext}.MiddleHeader .Avatar{margin-right:.625rem;width:2.5rem;height:2.5rem;font-size:1.0625rem}.MiddleHeader .status,.MiddleHeader .typing-status{font-size:.875rem;line-height:1.125rem;margin:0;color:var(--color-text-secondary);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;display:inline-block}.MiddleHeader .status .ellipsis,.MiddleHeader .typing-status .ellipsis{display:inline-flex}.MiddleHeader .status.online,.MiddleHeader .typing-status.online{color:var(--color-primary)}.MiddleHeader .status .font-emoji,.MiddleHeader .typing-status .font-emoji{line-height:1rem}.MiddleHeader .Button.smaller{width:2.5rem;height:2.5rem}.MiddleHeader .HeaderPinnedMessage-wrapper{display:flex;align-items:center;margin-left:auto;cursor:default;flex-direction:row-reverse}body.animation-level-1 .MiddleHeader .HeaderPinnedMessage-wrapper .ripple-container{display:none}.MiddleHeader .HeaderPinnedMessage-wrapper .HeaderPinnedMessage{min-width:16rem}.MiddleHeader .HeaderPinnedMessage-wrapper>.Button{flex-shrink:0}.MiddleHeader .HeaderPinnedMessage{display:flex;flex-shrink:1;margin-top:-.25rem;margin-bottom:-.25rem;padding:.25rem .25rem .25rem .375rem;border-radius:var(--border-radius-messages-small);position:relative;overflow:hidden;cursor:pointer}.MiddleHeader .HeaderPinnedMessage:hover{background-color:var(--color-interactive-element-hover)}.MiddleHeader .HeaderPinnedMessage .pinned-message-border{position:relative;height:2.25rem;margin:.125rem 0;width:.125rem;min-width:.125rem;overflow:hidden}.MiddleHeader .HeaderPinnedMessage .pinned-message-border .pinned-message-border-wrapper-1{height:2.25rem;width:.125rem;border-radius:.0625rem;background:var(--color-primary)}.MiddleHeader .HeaderPinnedMessage .pinned-message-border .pinned-message-border-wrapper{background-color:var(--color-primary-opacity);position:relative;will-change:transform;transition:transform .25s ease-in-out}.MiddleHeader .HeaderPinnedMessage .pinned-message-border .pinned-message-border-mark{position:absolute;left:0;top:0;width:.125rem;background:var(--color-primary);border-radius:.0625rem;will-change:transform;transition:transform .25s ease-in-out}.MiddleHeader .HeaderPinnedMessage .message-text{overflow:hidden;margin-inline-start:.375rem;margin-top:.125rem;max-width:15rem}@media (min-width:1440px) and (max-width:1500px){.MiddleHeader .HeaderPinnedMessage .message-text{max-width:14rem}}.MiddleHeader .HeaderPinnedMessage .message-text .title{font-weight:500;font-size:.875rem;line-height:1rem;height:1rem;color:var(--color-primary);margin-bottom:.125rem;white-space:pre;text-align:initial}.MiddleHeader .HeaderPinnedMessage .message-text p{font-size:.875rem;line-height:1.125rem;height:1.125rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:0}.MiddleHeader .HeaderPinnedMessage .emoji-small{width:1rem;height:1rem}.MiddleHeader .HeaderPinnedMessage>img{width:2.25rem;height:2.25rem;object-fit:cover;border-radius:.25rem;margin-inline-start:.375rem;margin-top:.125rem;flex-shrink:0}.MiddleHeader .HeaderPinnedMessage>img+.message-text{max-width:12rem}.MiddleHeader .HeaderActions{flex-shrink:0;margin-left:auto;display:flex;align-items:center;justify-content:flex-end}.MiddleHeader .HeaderActions .toggle-right-pane-button.active{color:var(--color-primary);opacity:1}.MiddleHeader .HeaderActions .Button,.MiddleHeader .HeaderPinnedMessage-wrapper .Button{margin-left:.25rem}.MiddleHeader .HeaderActions .Button.tiny,.MiddleHeader .HeaderPinnedMessage-wrapper .Button.tiny{margin-right:.625rem}@media (max-width:600px){.MiddleHeader .AudioPlayer,.MiddleHeader .HeaderPinnedMessage-wrapper{position:absolute;top:100%;left:0;right:0;height:2.875rem;overflow:hidden;box-shadow:0 2px 2px var(--color-light-shadow);display:flex;flex-direction:row-reverse;padding:.375rem .5rem .375rem .75rem;background:var(--color-background)}.MiddleHeader .AudioPlayer:before,.MiddleHeader .HeaderPinnedMessage-wrapper:before{content:"";display:block;position:absolute;top:-.1875rem;left:0;right:0;height:.125rem;box-shadow:0 .125rem .125rem var(--color-light-shadow)}.MiddleHeader .AudioPlayer .HeaderPinnedMessage,.MiddleHeader .HeaderPinnedMessage-wrapper .HeaderPinnedMessage{max-width:unset;margin-top:-.1875rem}.MiddleHeader .AudioPlayer{height:3.25rem;flex-direction:row;padding:.375rem .5rem}.MiddleHeader .AudioPlayer-content{padding:0 .5rem;flex-grow:1}.MiddleHeader .AudioPlayer>.Button{margin:0}.MiddleHeader .AudioPlayer>.player-close{margin-left:auto}.MiddleHeader .HeaderPinnedMessage{flex-grow:1;padding-top:0;padding-bottom:0}.MiddleHeader .HeaderPinnedMessage:before{top:.125rem;bottom:.125rem}.MiddleHeader .HeaderPinnedMessage .message-text{max-width:none}.MiddleHeader .AudioPlayer,.MiddleHeader .HeaderPinnedMessage-wrapper{transform:translateZ(0)}}@media (min-width:925px) and (max-width:1149.9px){.MiddleHeader .AudioPlayer,.MiddleHeader .HeaderPinnedMessage-wrapper{position:absolute}}@keyframes fade-in{0%{opacity:0}to{opacity:1}}.EmbeddedMessage{display:flex;align-items:center;font-size:.875rem;line-height:1.125rem;margin:0 -.25rem .0625rem;padding:.1875rem .25rem .1875rem .4375rem;border-radius:var(--border-radius-messages-small);position:relative;overflow:hidden;cursor:pointer;direction:ltr}body.animation-level-1 .EmbeddedMessage .ripple-container{display:none}.custom-shape .EmbeddedMessage{max-width:15rem;padding:.5rem;margin:0;background-color:var(--background-color);box-shadow:0 1px 2px var(--color-default-shadow)}.custom-shape .EmbeddedMessage:before{left:.625rem;top:.625rem;bottom:.625rem}.custom-shape .EmbeddedMessage img:not(.emoji){margin-inline-start:.5rem}.custom-shape .EmbeddedMessage:dir(rtl){padding:.5rem}.EmbeddedMessage:before{content:"";display:block;position:absolute;top:.3125rem;bottom:.3125rem;left:.3125rem;width:2px;background:var(--accent-color);border-radius:2px}.EmbeddedMessage:hover{background-color:var(--hover-color)}.EmbeddedMessage:active{background-color:var(--active-color)}.EmbeddedMessage .message-text{overflow:hidden;margin-inline-start:.5rem;display:flex;flex-direction:column-reverse}.EmbeddedMessage .message-text .message-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:.125rem;flex:1;display:block}.EmbeddedMessage .message-text p{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;height:1.125rem;margin-bottom:0;flex:1}.EmbeddedMessage .message-text p:after{content:none;display:none}.EmbeddedMessage .message-text .emoji{width:1.125rem!important;height:1.125rem!important;vertical-align:-4px!important}.EmbeddedMessage .embedded-action-message{color:var(--accent-color);opacity:.75}.EmbeddedMessage img:not(.emoji){width:2rem;height:2rem;object-fit:cover;border-radius:.25rem;margin-left:.25rem;flex-shrink:0}.EmbeddedMessage img:not(.emoji).round{border-radius:1rem}.EmbeddedMessage.inside-input{padding-inline-start:.5625rem;margin:0 0 -.125rem -.1875rem;display:grid;grid-template-columns:auto 1fr;grid-template-rows:1fr;width:100%;--accent-color:var(--color-primary);--hover-color:var(--color-interactive-element-hover)}.EmbeddedMessage.inside-input:before{bottom:.3125rem}.EmbeddedMessage.inside-input img:not(.emoji){margin-left:.125rem}.EmbeddedMessage.inside-input .message-text{margin-inline-start:.375rem}.EmbeddedMessage.inside-input .message-title{font-weight:500;color:var(--accent-color)}.MessageMeta{position:absolute;height:1.25rem;bottom:0;right:0;display:flex;align-items:center;background:hsla(0,0%,60%,.6);border-radius:.625rem;padding:0 .25rem;color:#fff;cursor:pointer;max-width:100%}.MessageMeta .message-signature,.MessageMeta .message-time,.MessageMeta .message-views{font-size:.75rem;white-space:nowrap}.MessageMeta .message-time{margin-right:.1875rem}.MessageMeta .message-views{margin-left:.1875rem}.MessageMeta .message-signature{overflow:hidden;text-overflow:ellipsis;margin-right:.375rem}.MessageMeta .icon-channelviews{margin-left:.125rem;margin-right:.375rem;font-size:1.125rem;position:relative;top:-.0625rem}.has-solid-background .MessageMeta{color:rgba(var(--color-text-meta-rgb),.75);background:none}.media:not(.text) .MessageMeta,.Message .custom-shape .MessageMeta{background:rgba(0,0,0,.2);--color-accent-own:#fff;--color-accent:#fff;color:#fff!important;opacity:1;bottom:.25rem;right:.25rem;left:auto;height:1.125rem;padding:0 .3125rem 0 .375rem}.media:not(.text) .MessageMeta .MessageOutgoingStatus i,.Message .custom-shape .MessageMeta .MessageOutgoingStatus i{background:transparent}.media:not(.text):dir(rtl) .MessageMeta,.Message .custom-shape:dir(rtl) .MessageMeta{right:auto!important;left:.25rem;padding:0 .375rem 0 .3125rem}.is-forwarded.media:not(.text):dir(rtl) .MessageMeta,.Message .is-forwarded.custom-shape:dir(rtl) .MessageMeta{left:.8125rem}.is-forwarded.media:not(.text) .MessageMeta{bottom:.935rem;right:.8125rem}.emoji-only .MessageMeta{right:0}.Message.own .has-solid-background .MessageMeta{color:var(--color-message-meta-own)}.MessageMeta .MessageOutgoingStatus{margin-left:-.1875rem;font-size:1.1875rem;border-radius:.625rem}.Message.own .MessageMeta .MessageOutgoingStatus{color:var(--color-accent-own)}.message-content.has-replies:not(.custom-shape) .MessageMeta{bottom:3.375rem}.message-content.has-replies.text:not(.custom-shape) .MessageMeta{bottom:3.4375rem}.Message:not(.own) .custom-shape .reply-message+.MessageMeta{right:auto;left:13.2rem;bottom:.25rem}.Message:not(.own) .emoji-only-1 .reply-message+.MessageMeta{left:2.5rem}.Message:not(.own) .emoji-only-2 .reply-message+.MessageMeta{left:5.5rem}.Message:not(.own) .emoji-only-3 .reply-message+.MessageMeta{left:6.5rem}.Sticker:not(.inactive){cursor:pointer}.Sticker.inactive{pointer-events:none}.Contact{display:flex;align-items:center;padding:.25rem}.Contact.interactive{cursor:pointer}.Contact .Avatar{margin-right:.8rem}.Contact .contact-info{padding:.5rem .5rem .5rem 0;white-space:nowrap;overflow:hidden}.Contact .contact-info .contact-name{font-size:1rem;line-height:1rem;margin-bottom:.25rem;font-weight:500}.Contact .contact-info .contact-phone{line-height:1rem;color:var(--secondary-color)}.PollOption{display:flex;flex-flow:row nowrap;margin-bottom:.75rem}.PollOption:last-child{margin-bottom:0}.PollOption .poll-option-text{word-break:break-word}.PollOption .poll-option-share{position:relative;margin-top:.125rem;width:1.75rem;margin-inline-end:.5rem;flex-shrink:0;font-weight:500;font-size:.875rem;text-align:right}.PollOption .poll-option-share.limit-width{display:inline-flex;justify-content:center;font-size:.75rem}.PollOption .poll-option-chosen{position:absolute;right:0;bottom:-5px;width:1rem;height:1rem;background:var(--accent-color);color:var(--background-color);border-radius:.5rem;font-size:.75rem;text-align:center}.PollOption .poll-option-chosen.wrong{background:var(--color-error)}.is-forwarded .PollOption .poll-option-chosen>i{margin-left:1px}.PollOption .poll-option-chosen.animate{opacity:0;animation-name:PollOptionIconAnimate;animation-delay:.09s;animation-duration:.3s;animation-fill-mode:forwards}.PollOption .poll-option-right{flex-grow:1}.PollOption .poll-option-answer{position:relative}.PollOption .poll-option-line{position:relative;width:0;height:.25rem;min-width:.5rem;border-radius:.125rem;margin-top:.5rem;background:var(--accent-color);transform-origin:0 0;transition:transform .3s;transition-delay:.09s}.PollOption .poll-line{width:30px;height:35px;position:absolute;left:-27px;bottom:-5px;transition:stroke-dashoffset .3s,stroke-dasharray .3s;stroke-dashoffset:0;stroke-dasharray:0,200%}.PollOption .poll-line path{stroke-width:4px;stroke-linecap:round;stroke:var(--accent-color);fill:none}.PollOption .wrong .poll-option-line{background:var(--color-error)}.PollOption .wrong .poll-line path{stroke:var(--color-error)}@keyframes PollOptionIconAnimate{0%{opacity:0}to{opacity:1}}.Poll{min-width:15rem;text-align:initial}@media (max-width:600px){.Poll{min-width:50vw}}.Poll .poll-question{font-weight:500;line-height:1.25rem;margin:.125rem 0;word-break:break-word}.Poll .poll-type,.Poll .poll-voters-count{color:var(--secondary-color);font-size:.875rem}.Poll .poll-type{margin-bottom:.5rem;display:flex;align-items:center;min-height:1.375rem}.Poll .poll-voters-count{margin:.4375rem 0 .3125rem;text-align:center}.Poll .poll-answers{padding-top:.25rem;padding-bottom:1rem}.Poll .Checkbox,.Poll .Radio{padding-left:2.25rem}.Poll .Checkbox:last-child,.Poll .Radio:last-child{margin-bottom:.75rem}.Poll .Checkbox.disabled,.Poll .Radio.disabled{opacity:1!important;cursor:not-allowed}.Poll .Checkbox .Checkbox-main:before,.Poll .Checkbox .Radio-main:before,.Poll .Radio .Checkbox-main:before,.Poll .Radio .Radio-main:before{left:.125rem;background-color:var(--background-color)}.theme-dark .Poll .Checkbox .Checkbox-main:before,.theme-dark .Poll .Checkbox .Radio-main:before,.theme-dark .Poll .Radio .Checkbox-main:before,.theme-dark .Poll .Radio .Radio-main:before{--color-borders:var(--color-borders-input)}.Message.own .Poll .Checkbox .Checkbox-main:before,.Message.own .Poll .Checkbox .Radio-main:before,.Message.own .Poll .Radio .Checkbox-main:before,.Message.own .Poll .Radio .Radio-main:before{--color-borders:var(--accent-color)}.Poll .Checkbox .Checkbox-main:after,.Poll .Checkbox .Radio-main:after,.Poll .Radio .Checkbox-main:after,.Poll .Radio .Radio-main:after{left:.4375rem;background-color:var(--accent-color)}.Poll .Checkbox input:checked~.Checkbox-main:before,.Poll .Checkbox input:checked~.Radio-main:before,.Poll .Radio input:checked~.Checkbox-main:before,.Poll .Radio input:checked~.Radio-main:before{border-color:var(--accent-color)}.Poll .Checkbox .Spinner,.Poll .Radio .Spinner{left:.125rem}.Poll .Checkbox .Checkbox-main:after{left:.125rem;background-color:var(--color-primary)}.Message.own .Poll .Checkbox .Checkbox-main:after{background-color:var(--accent-color)}.Poll .Spinner>div{background-image:var(--spinner-gray-data)}.theme-dark .Poll .Spinner>div{background-image:var(--spinner-white-data)}.Message.own .Poll .Spinner>div{background-image:var(--spinner-green-data)}.theme-dark .Message.own .Poll .Spinner>div{background-image:var(--spinner-white-data)}.Poll .poll-recent-voters{display:inline-flex;align-items:center;vertical-align:text-bottom;margin-left:.875rem;margin-right:.5rem;margin-top:-2px}.Poll .poll-recent-voters .Avatar{border:1px solid var(--color-white);margin-right:0;box-sizing:initial}.Poll .poll-recent-voters .Avatar:not(:first-child){margin-left:-3px}.Poll .poll-countdown{margin-left:auto;font-size:.75rem;transition:color .2s}.Poll .poll-countdown.hurry-up{color:var(--color-error)}.Poll .poll-countdown.hurry-up .poll-countdown-progress{stroke:var(--color-error)}.Poll .poll-countdown svg{vertical-align:-3px}.Poll .poll-countdown-progress{stroke:var(--color-primary);fill:transparent;stroke-width:2;stroke-linecap:round;transition:stroke-dashoffset 2s,stroke .2s}.Poll .poll-quiz-help{margin:-.625rem 0 -.625rem auto}.Message:not(.own) .Poll .poll-quiz-help{color:var(--color-primary)}.Poll .poll-answers,.Poll .poll-results{padding-top:.25rem;padding-bottom:.5rem}.Poll .Button{text-transform:none;font-size:1rem}.Message.own .Poll .Button{color:var(--accent-color);--color-primary-shade-rgb:var(--color-accent-own)}.Poll>.Button{margin-top:-.125rem;margin-bottom:-.0625rem}.WebPage{margin-top:.25rem;margin-bottom:.125rem;padding-left:.625rem;font-size:.875rem;line-height:1.125rem;max-width:29rem;position:relative}.WebPage:before{content:"";display:block;position:absolute;top:0;bottom:0;left:0;width:2px;background:var(--accent-color);border-radius:2px}.WebPage-text{display:flex;flex-direction:column;align-items:flex-start}.WebPage .media-inner{margin:0 0 .375rem!important}.WebPage .media-inner,.WebPage .media-inner.small-image img,.WebPage .media-inner img{border-radius:var(--border-radius-messages-small)!important}.WebPage .media-inner.square-image{width:5rem;height:5rem;min-height:0;margin-bottom:0!important}.WebPage .media-inner.square-image img{width:100%;height:100%}.WebPage.with-square-photo{display:flex;margin-bottom:1rem}.WebPage.with-square-photo .WebPage-text{order:1;padding-right:1rem}.WebPage.with-square-photo .media-inner{order:2;flex-shrink:0}.WebPage.with-square-photo:dir(rtl) .WebPage-text{padding-inline-end:1rem}.WebPage:not(.with-square-photo) .site-description:last-child:after,.WebPage:not(.with-square-photo) .site-name:last-child:after,.WebPage:not(.with-square-photo) .site-title:last-child:after{content:"";display:inline-block;width:var(--meta-safe-area-size);height:.5rem}.WebPage .site-description,.WebPage .site-name,.WebPage .site-title{word-break:break-word}.WebPage .site-name{color:var(--accent-color)}.WebPage .site-name,.WebPage .site-title{font-weight:500;margin-bottom:.125rem}.WebPage .site-description{line-height:1rem;margin-bottom:0}.WebPage:dir(rtl){padding-inline-start:.625rem}.WebPage:dir(rtl):before{left:auto;right:0}.Invoice .title{color:var(--accent-color);font-weight:500}.Invoice .description{position:relative}.Invoice .description.has-image .invoice-image{max-width:100%;height:20rem}@media (max-width:600px){.Invoice .description.has-image .invoice-image{height:10rem}}.Invoice .description.has-image .description-text{position:absolute;top:0;padding:.25rem .5rem;margin:.25rem;background-color:rgba(90,110,70,.6);border-radius:var(--border-radius-messages-small);color:var(--color-text);font-weight:500}.Album{position:relative;overflow:hidden}.message-content.media.text .Album{margin:-.3125rem -.5rem .3125rem}.forwarded-message .Album{margin-bottom:.125rem}.message-content.media.text .forwarded-message .Album{margin:0 0 .3125rem;--border-bottom-left-radius:inherit;--border-bottom-right-radius:inherit}.Album>.album-item-select-wrapper .media-inner,.message-content.media.text .Album>.album-item-select-wrapper .media-inner{margin:0!important}.Album>.album-item-select-wrapper .media-inner,.Album>.album-item-select-wrapper .media-inner img,.Album>.album-item-select-wrapper .media-inner video{border-radius:0!important;object-fit:cover}.RoundVideo{position:relative;width:200px;height:200px;cursor:pointer}.RoundVideo .thumbnail-wrapper{width:200px;height:200px;border-radius:50%;overflow:hidden}.RoundVideo .video-wrapper{position:absolute;left:0;top:0;border-radius:50%;overflow:hidden}.RoundVideo .progress{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none}.RoundVideo .progress-circle{stroke:#fff;fill:transparent;stroke-width:4;stroke-opacity:.35;stroke-linecap:round}.RoundVideo video::-internal-media-controls-cast-button,.RoundVideo video::-webkit-media-controls,.RoundVideo video::-webkit-media-controls-start-playback-button{display:none}.InlineButtons{display:flex;flex-direction:column}.InlineButtons .row{display:flex;flex-direction:row}.InlineButtons .Button{flex:1;width:auto;margin:.125rem;background:var(--pattern-color);border-radius:var(--border-radius-messages-small);font-weight:500;text-transform:none}.InlineButtons .Button:before{content:"";background-color:var(--color-white);opacity:0;position:absolute;top:0;left:0;right:0;bottom:0;border-radius:var(--border-radius-messages-small);z-index:var(--z-below);transition:opacity .2s}.InlineButtons .Button:hover{background:var(--pattern-color)!important}.InlineButtons .Button:hover:before{opacity:.4}.InlineButtons .Button:first-of-type{margin-left:0}.InlineButtons .Button:last-of-type{margin-right:0}.InlineButtons .Button i{font-size:.75rem;position:absolute;right:.125rem;top:.125rem;display:block;transform:rotate(-45deg)}.InlineButtons .row:first-of-type .Button{margin-top:.25rem!important}.InlineButtons .row:last-of-type .Button{margin-bottom:0}.InlineButtons .row:last-of-type .Button:first-of-type{border-bottom-left-radius:var(--border-radius-messages)}.InlineButtons .row:last-of-type .Button:last-of-type{border-bottom-right-radius:var(--border-radius-messages)}.CommentButton{--background-color:var(--color-background);--hover-color:var(--color-chat-hover);display:flex;width:100%;align-items:center;padding:.5625rem .25rem .5625rem .625rem;padding-inline-start:.625rem;padding-inline-end:.25rem;background:var(--background-color);border-bottom-right-radius:var(--border-bottom-right-radius);border-bottom-left-radius:var(--border-bottom-left-radius);font-size:.9375rem;font-weight:500;line-height:2rem;color:var(--accent-color);white-space:nowrap;cursor:pointer;transition:background-color .15s,color .15s}body.animation-level-0 .CommentButton{transition:none!important}.Message .has-appendix .CommentButton:before{content:"";display:block;position:absolute;bottom:-.1875rem;left:-.5625rem;width:.5625rem;height:1.25rem;background-position:0 100%;background-image:url("data:image/svg+xml;charset=utf-8,%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");opacity:0;transition:opacity .15s,filter .15s}.theme-dark #root .Message .has-appendix .CommentButton:before{filter:invert(.83)}body.animation-level-0 .Message .has-appendix .CommentButton:before{transition:none!important}.custom-shape .CommentButton{position:absolute;right:-3rem;width:2.25rem;bottom:3rem;height:3.375rem;border-radius:1.375rem;padding:.375rem .3125rem .25rem;align-items:flex-start;color:#fff;background-color:rgba(0,0,0,.2);opacity:0;transition:opacity .2s ease}@media (pointer:coarse){.custom-shape .CommentButton{opacity:1!important}}.custom-shape .CommentButton:hover{background-color:rgba(0,0,0,.28)}.Message:hover .custom-shape .CommentButton{opacity:1}.custom-shape .CommentButton:after{content:attr(data-cnt);position:absolute;bottom:-.0625rem;left:0;width:100%;text-align:center;font-size:12px;display:block}.custom-shape .CommentButton[data-cnt="0"]{height:2.25rem}.custom-shape .CommentButton[data-cnt="0"]:after{display:none}.custom-shape .CommentButton .icon-comments-sticker{display:block;font-size:1.5rem;margin:0 auto}.custom-shape .CommentButton .icon-comments,.custom-shape .CommentButton .icon-next,.custom-shape .CommentButton .label,.custom-shape .CommentButton .recent-repliers{display:none}.CommentButton:hover{background:var(--hover-color)}.Message .has-appendix .CommentButton:hover:before{opacity:1}.CommentButton:hover .Avatar{border-color:var(--hover-color)!important}.audio .CommentButton,.is-forwarded .CommentButton,.poll .CommentButton,.text .CommentButton,.voice .CommentButton{border-top:1px solid var(--color-borders)}.message-content.has-solid-background .CommentButton{margin:.375rem -.5rem -.375rem}.message-content.voice .CommentButton{margin-bottom:-.5rem}.message-content.audio .CommentButton{margin-bottom:-.8125rem}.message-content.audio .CommentButton,.message-content.has-solid-background.is-forwarded .CommentButton,.message-content.has-solid-background.text .CommentButton,.message-content.poll .CommentButton,.message-content.voice .CommentButton{width:calc(100% + 1rem)}.CommentButton .icon-comments-sticker{display:none}.CommentButton .icon-comments{font-size:1.5625rem;line-height:2rem;margin-inline-end:.875rem}.CommentButton .icon-next{margin-inline-start:auto;font-size:1.5rem}.CommentButton .recent-repliers{display:inline-flex;align-items:center;margin-inline-end:.5rem;margin-inline-start:-.125rem}.CommentButton .recent-repliers .Avatar{transition:border .15s;border:2px solid var(--color-background);margin-inline-end:0;z-index:3;overflow:hidden}.CommentButton .recent-repliers .Avatar .emoji{width:1rem;background-size:1rem}.CommentButton .recent-repliers .Avatar+.Avatar{z-index:2}.CommentButton .recent-repliers .Avatar+.Avatar+.Avatar{z-index:1}.CommentButton .recent-repliers .Avatar:not(:first-child){margin-inline-start:-.75rem}.CommentButton.has-unread .label{position:relative}.CommentButton.has-unread .label:after{content:"";display:inline-block;width:.5rem;height:.5rem;border-radius:50%;background:var(--accent-color);margin-inline-start:.75rem}.CommentButton.disabled{cursor:default;pointer-events:none}.Message{display:flex;align-items:flex-end;margin-bottom:.375rem;position:relative;--background-color:var(--color-background);--hover-color:var(--color-reply-hover);--active-color:var(--color-reply-active);--max-width:29rem;--accent-color:var(--color-primary);--accent-shade-color:var(--color-primary-shade);--secondary-color:var(--color-text-secondary);--meta-safe-area-base:2.25rem;--meta-safe-author-width:0px;--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width));--deleting-translate-x:-50%;--select-message-scale:0.9;--select-background-color:#fff}.Message>.Avatar,.Message>.message-content-wrapper{opacity:1;transform:scale(1) translateX(0);transition:transform var(--select-transition)}body.animation-level-0 .Message>.Avatar,body.animation-level-0 .Message>.message-content-wrapper{transition:none!important}.Message>.Avatar{position:absolute;bottom:0;left:0}@media (max-width:600px){.Message>.Avatar{width:2.5rem;height:2.5rem}}.Message.last-in-group{margin-bottom:.625rem}.Message.last-in-list{margin-bottom:.4375rem}.Message.is-in-selection-mode .Album{border:1px solid var(--select-background-color);background-color:var(--select-background-color)}.Message.has-inline-buttons .message-content{border-bottom-right-radius:var(--border-radius-messages-small)}.Message:not(.own){padding-left:2.5rem}.Message:not(.own).is-thread-top,.no-avatars .Message:not(.own){padding-left:0}@media (max-width:600px){.Message:not(.own){padding-left:2.875rem}.Message:not(.own).is-thread-top,.no-avatars .Message:not(.own){padding-left:.25rem}}.Message.own{flex-direction:row-reverse;--background-color:var(--color-background-own);--hover-color:var(--color-reply-own-hover);--active-color:var(--color-reply-own-active);--max-width:30rem;--accent-color:var(--color-accent-own);--accent-shade-color:var(--color-green);--secondary-color:var(--color-accent-own);--color-code:var(--color-code-own);--color-code-bg:var(--color-code-own-bg);--color-links:var(--color-own-links);--color-links-hover:var(--color-own-links);--meta-safe-area-base:3.5rem;--deleting-translate-x:50%;--color-text-green:var(--color-accent-own)}@media (max-width:600px){.Message.own{padding-right:.25rem}}.Message.is-deleting>.Avatar,.Message.is-deleting>.message-content-wrapper{transition:opacity .2s ease,transform .2s ease-in;opacity:0;transform:scale(.3) translateX(var(--deleting-translate-x));transform-origin:bottom}.Message.has-views{--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + 4rem)}.Message.was-edited{--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + 2.5rem)}.Message.was-edited.has-views{--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + 7.5rem)}.select-mode-active .Message{cursor:pointer;-webkit-user-select:none;user-select:none}.select-mode-active .Message:not(.own)>.Avatar,.select-mode-active .Message:not(.own)>.message-content-wrapper{transform:translateX(2.5rem)}.select-mode-active .Message:not(.is-album):after{content:"";position:absolute;top:-.25rem;bottom:-.25rem;left:-4rem;right:-4rem;z-index:var(--z-message-select-area)}.select-mode-active .Message.is-album .message-select-control,.select-mode-active .Message.is-in-document-group .message-select-control{pointer-events:unset}.select-mode-active .Message .message-select-control{opacity:1}.Message.is-selected .message-select-control{background:var(--color-green)}.Message.is-selected .message-select-control.group-select{background:transparent}.Message .File.file-is-selected .message-select-control,.Message.is-selected .message-select-control.group-select.is-selected{background:var(--color-green)}.Message.has-menu-open.is-in-document-group .File .file-icon,.Message.is-in-document-group .File.file-is-selected .file-icon{--background-color:var(--color-background-selected)}.Message.own.has-menu-open.is-in-document-group .File .file-icon,.Message.own.is-in-document-group .File.file-is-selected .file-icon{--background-color:var(--color-background-own-selected)}.Message .Audio .message-select-control{left:1.0625rem;top:1.375rem}html.theme-dark .Message.own .Audio .ProgressSpinner{background-image:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUiIGhlaWdodD0iMTUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTguMjE4IDcuNWw1LjYzMy01LjYzM2EuNTA4LjUwOCAwIDEwLS43MTgtLjcxOEw3LjUgNi43ODIgMS44NjcgMS4xNDlhLjUwOC41MDggMCAxMC0uNzE4LjcxOEw2Ljc4MiA3LjVsLTUuNjMzIDUuNjMzYS41MDguNTA4IDAgMTAuNzE4LjcxOEw3LjUgOC4yMThsNS42MzMgNS42MzNhLjUwNi41MDYgMCAwMC43MTggMCAuNTA4LjUwOCAwIDAwMC0uNzE4TDguMjE4IDcuNXoiIGZpbGw9IiNGRkYiIHN0cm9rZT0iI0E0NUQzNyIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjwvc3ZnPg==)}html.theme-dark .Message.own .Audio .ProgressSpinner circle{stroke:var(--background-color)}.Message .File{position:relative}.Message .File .message-select-control{position:absolute;top:2rem;left:2rem;z-index:2}.Message.own .Message .album-item-select-wrapper{background:var(--color-background-own)}.Message .album-item-select-wrapper .message-select-control{top:.438rem;right:.438rem;left:unset}.Message .album-item-select-wrapper .media-inner{border:0 solid var(--select-background-color);transition:border-width var(--select-transition)}.Message .album-item-select-wrapper img,.Message .album-item-select-wrapper video{transition:transform var(--select-transition)}.Message .album-item-select-wrapper.is-selected .message-select-control{background:var(--color-green)}.Message .album-item-select-wrapper.is-selected img,.Message .album-item-select-wrapper.is-selected video{transform:scale(var(--select-message-scale))}.Message.is-forwarding .message-select-control,.Message.is-selected .message-select-control{background:var(--color-green)}.Message.is-forwarding .Menu .bubble,.Message.is-selected .Menu .bubble{transition:none!important}.Message.is-in-document-group:not(.first-in-document-group):before{top:0!important}.Message.is-in-document-group:not(.first-in-document-group) .message-content{box-shadow:none;border-top-left-radius:0!important;border-top-right-radius:0!important}.Message.is-in-document-group:not(.first-in-document-group) .forwarded-message:before{top:-1.5rem}.Message.is-in-document-group:not(.last-in-document-group){margin-bottom:0}.Message.is-in-document-group:not(.last-in-document-group):before{bottom:0!important}.Message.is-in-document-group:not(.last-in-document-group) .message-content{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.Message.is-in-document-group.is-in-selection-mode .Audio:not(.audio-is-selected) .message-select-control:not(.group-select),.Message.is-in-document-group.is-in-selection-mode .File:not(.file-is-selected) .message-select-control:not(.group-select){background:#fff}.Message.is-in-document-group.is-in-selection-mode .Audio:not(.audio-is-selected) .message-select-control:not(.group-select):after,.Message.is-in-document-group.is-in-selection-mode .File:not(.file-is-selected) .message-select-control:not(.group-select):after{content:"";width:1.25rem;height:1.25rem;border-radius:.688rem;background:#fff;border:.125rem solid rgba(0,0,0,.2);position:absolute}.Message.is-in-document-group.is-in-selection-mode.own .message-content .Audio:not(.audio-is-selected) .message-select-control:not(.group-select),.Message.is-in-document-group.is-in-selection-mode.own .message-content .File:not(.file-is-selected) .message-select-control:not(.group-select){background:var(--background-color);border-color:var(--background-color)}.Message.is-in-document-group.is-in-selection-mode.own .message-content .Audio:not(.audio-is-selected) .message-select-control:not(.group-select):after,.Message.is-in-document-group.is-in-selection-mode.own .message-content .File:not(.file-is-selected) .message-select-control:not(.group-select):after{background:var(--background-color);border-color:var(--color-message-meta-own)}.Message.is-in-document-group.focused .message-content,.Message.is-in-document-group.has-menu-open .message-content,.Message.is-in-document-group.is-forwarding .message-content,.Message.is-in-document-group.is-selected .message-content{background:var(--color-background-selected)}.Message.is-in-document-group.focused.own .message-content,.Message.is-in-document-group.has-menu-open.own .message-content,.Message.is-in-document-group.is-forwarding.own .message-content,.Message.is-in-document-group.is-selected.own .message-content{--background-color:var(--color-background-own-selected);background:var(--color-background-own-selected)}.Message.is-in-document-group .message-content-wrapper{width:17.1875rem}.Message.is-in-document-group .message-content{transition:background-color var(--select-transition)}.Message.is-in-document-group.own .message-content-wrapper{display:flex;justify-content:flex-end}.Message.is-in-document-group.own .message-content-wrapper .message-content{width:100%}.Message .album-item-select-wrapper{position:absolute}.Message .album-item-select-wrapper .message-select-control{position:absolute;z-index:2}.Message .message-select-control{position:absolute;left:0;bottom:.25rem;width:1.5rem;height:1.5rem;border:2px solid #fff;border-radius:50%;z-index:var(--z-message-select-control);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;opacity:0;pointer-events:none;transition:opacity var(--select-transition)}.Message .message-select-control .icon-select{position:absolute;left:-3px;top:-3px;font-size:1.625rem}.theme-dark .Message .message-select-control{border-color:hsla(0,0%,100%,.5)}.Message .Avatar{margin-right:.3rem}.Message.is-in-document-group .message-content.document{padding:.25rem .5rem!important}.Message.is-in-document-group.last-in-document-group .message-content.document{padding-bottom:.5rem!important}.Message.is-in-document-group.first-in-document-group .message-content.document{padding-top:.5rem!important}.Album,.media-inner,.message-content,.message-content.custom-shape .media-inner img,.message-content.media .media-inner img,.message-content.media .media-inner video{border-top-left-radius:var(--border-top-left-radius);border-top-right-radius:var(--border-top-right-radius);border-bottom-left-radius:var(--border-bottom-left-radius);border-bottom-right-radius:var(--border-bottom-right-radius)}.media-inner video.full-media{background:transparent!important}.media-inner{overflow:hidden}.media-inner.small-image img{border-radius:0!important}.Message{--border-top-left-radius:var(--border-radius-messages);--border-top-right-radius:var(--border-radius-messages);--border-bottom-left-radius:var(--border-radius-messages);--border-bottom-right-radius:var(--border-radius-messages)}.Message:not(.own).first-in-group:not(.last-in-group),.Message:not(.own):not(.first-in-group):not(.last-in-group){--border-bottom-left-radius:var(--border-radius-messages-small)}.Message:not(.own).last-in-group:not(.first-in-group),.Message:not(.own):not(.first-in-group):not(.last-in-group){--border-top-left-radius:var(--border-radius-messages-small)}.Message:not(.own).last-in-group{--border-bottom-left-radius:var(--border-radius-messages-small)}.Message:not(.own).last-in-group .message-content.has-appendix{--border-bottom-left-radius:0}.Message.own.first-in-group:not(.last-in-group),.Message.own:not(.first-in-group):not(.last-in-group){--border-bottom-right-radius:var(--border-radius-messages-small)}.Message.own.last-in-group:not(.first-in-group),.Message.own:not(.first-in-group):not(.last-in-group){--border-top-right-radius:var(--border-radius-messages-small)}.Message.own.last-in-group{--border-bottom-right-radius:var(--border-radius-messages-small)}.Message.own.last-in-group .message-content.has-appendix{--border-bottom-right-radius:0}.Message .message-content.has-replies:not(.custom-shape) .Album,.Message .message-content.has-replies:not(.custom-shape) .media-inner,.Message .message-content.text .Album,.Message .message-content.text .media-inner{--border-bottom-left-radius:0;--border-bottom-right-radius:0}.Message .message-content.is-reply .EmbeddedMessage+.Album,.Message .message-content.is-reply .EmbeddedMessage+.Audio,.Message .message-content.is-reply .EmbeddedMessage+.File{margin-top:.375rem}.Message .message-content:not(.custom-shape).force-sender-name .Album,.Message .message-content:not(.custom-shape).is-reply .Album,.Message .message-content:not(.custom-shape).is-reply .media-inner,.Message .message-content:not(.is-forwarded) .message-title~.media-inner{--border-top-left-radius:0;--border-top-right-radius:0}.Message .message-content.is-forwarded .content-inner .message-title{margin-bottom:.25rem}.Message .message-action-button{position:absolute;bottom:0;color:#fff;background-color:rgba(0,0,0,.2);opacity:0;transition:opacity .2s ease}@media (pointer:coarse){.Message .message-action-button{opacity:1!important}}.Message .message-action-button:active,.Message .message-action-button:focus,.Message .message-action-button:hover{background-color:rgba(0,0,0,.28)!important}.Message:hover .message-action-button,.Message[data-is-document-group-hover] .message-action-button{opacity:1}.Message.own .message-action-button{left:-3rem}.Message:not(.own) .message-action-button{right:-3rem}.Message .bottom-marker{height:1px;width:1px;visibility:hidden}.Message .custom-shape .message-action-button{bottom:.25rem}.message-content{position:relative;max-width:var(--max-width)}@media (max-width:600px){.message-content{max-width:69vw}}.message-content .text-content{margin:0;word-break:break-word;line-height:1.3125;text-align:initial;display:flow-root;unicode-bidi:plaintext}.message-content .text-entity-link{unicode-bidi:plaintext}.message-content.document>.MessageMeta,.message-content .text-content>.MessageMeta{position:relative;top:.4375rem;bottom:auto!important;float:right;line-height:1;margin-left:.4375rem;margin-right:-.5rem}.message-content.document:dir(rtl)>.MessageMeta,.message-content .text-content:dir(rtl)>.MessageMeta{float:left;margin-left:-.25rem;margin-right:.4375rem}.message-content.document:not(.text):after{content:"";display:block;clear:both}.message-content.document:not(.text)>.MessageMeta{position:relative;top:auto;bottom:-.5rem!important}.theme-dark .Message.own .message-content .text-entity-link{text-decoration:underline}.theme-dark .Message.own .message-content .text-entity-link:hover{text-decoration:none}.message-content:not(.custom-shape){font-size:var(--message-text-size,1rem)}.message-content:not(.custom-shape)>.content-inner{min-width:0}.message-content .matching-text-highlight{background:#cae3f7;border-radius:.25rem;padding:0 .125rem}.message-content .message-title{white-space:nowrap;font-size:.875rem;font-weight:500;line-height:1.25rem;color:var(--accent-color);unicode-bidi:plaintext;display:flex}.message-content .message-title,.message-content .message-title>.interactive{overflow:hidden;text-overflow:ellipsis}.message-content .message-title.interactive,.message-content .message-title>.interactive{cursor:pointer}.message-content .message-title.interactive:hover,.message-content .message-title>.interactive:hover{opacity:.85}.message-content .message-title>.color-1{color:var(--color-user-1)}.message-content .message-title>.color-2{color:var(--color-user-2)}.message-content .message-title>.color-4{color:var(--color-user-4)}.message-content .message-title>.color-5{color:var(--color-user-5)}.message-content .message-title>.color-6{color:var(--color-user-6)}.message-content .message-title>.color-7{color:var(--color-user-7)}.message-content .message-title>.color-8{color:var(--color-user-8)}.message-content .message-title+.File{margin-top:.25rem}.message-content .message-title .via{padding:0 .2rem;font-weight:400}.message-content .message-title .admin-title{flex:1;margin-left:1rem;text-align:right;font-weight:400;font-size:.75rem;margin-top:-.1rem;color:rgba(var(--color-text-meta-rgb),.75)}.Message.own .message-content .message-title .admin-title{color:var(--accent-color)}.message-content.has-shadow{box-shadow:0 1px 2px var(--color-default-shadow)}.is-album .message-content,.message-content.has-solid-background{background:var(--background-color)}.message-content.has-solid-background{padding:.3125rem .5rem .375rem}.message-content.has-solid-background .forwarded-message>.text-content:not(.with-meta):last-child:after{content:"";display:inline-block;width:var(--meta-safe-area-size);height:1rem}.message-content:not(.has-appendix) .svg-appendix{display:none}.message-content .svg-appendix{position:absolute;bottom:-.1875rem;width:.5625rem;height:1.25rem}.message-content .svg-appendix .corner{fill:var(--background-color)}.Message.own .message-content .svg-appendix{right:-.551rem}.Message:not(.own) .message-content .svg-appendix{left:-.562rem}.message-content[data-has-custom-appendix] .svg-appendix .corner{fill:var(--appendix-bg)}.Message .message-content.has-appendix-thumb .svg-appendix{--background-color:#ccc;opacity:1;transition:opacity .5s ease}.message-content.document{padding:.5rem!important}.theme-dark .message-content.document .File{--color-primary:var(--color-selection-highlight)}.message-content.document .File+.text-content{margin-top:.313rem}.message-content.audio .Embedded,.message-content.audio .message-title,.message-content.voice .Embedded,.message-content.voice .message-title{margin-top:-.1875rem;margin-bottom:.1875rem}.message-content.voice{padding:.5rem!important}.message-content.voice .Voice+.text-content{margin-top:.5rem}.message-content.audio{min-width:17.1875rem;padding:.5rem .5rem .8125rem!important}.message-content.audio .Audio+.text-content{margin-top:.25rem;margin-bottom:-.4375rem}.message-content:not(.custom-shape) .emoji{display:inline-block;width:1.25rem;background-size:1.25rem;color:transparent;margin-inline-end:1px;vertical-align:text-bottom}.message-content:not(.custom-shape) .emoji::selection{background-color:var(--color-selection-highlight-emoji);color:transparent}.message-content:not(.custom-shape) .text-content .emoji{width:calc(1.25*var(--message-text-size, 1rem));background-size:calc(1.25*var(--message-text-size, 1rem))}.message-content .no-media-corners{--border-top-left-radius:0;--border-top-right-radius:0}.message-content.media .media-inner{display:flex;justify-content:center;align-items:center}.message-content.media .media-inner.interactive{cursor:pointer}.message-content.media .media-inner.interactive.dark video{background-color:#232323}.message-content.media.round.is-reply{width:auto!important}.message-content.media.force-sender-name .Album,.message-content.media.force-sender-name .media-inner,.message-content.media.is-reply .Album,.message-content.media.is-reply .media-inner,.message-content.media.is-via-bot .media-inner,.message-content.media.text .media-inner{margin-left:-.5rem;margin-right:-.5rem}.message-content.media.text .media-inner{margin-top:-.3125rem}.message-content.media.force-sender-name .Album,.message-content.media.is-reply .Album,.message-content.media.is-reply .media-inner,.message-content.media .message-title~.media-inner{margin-top:.375rem;margin-bottom:-.375rem}.message-content.media.text .Album,.message-content.media.text .media-inner{margin-bottom:.375rem}.message-content.media .media-loading{display:flex;align-items:center;justify-content:center}.message-content.media .media-loading:not(.open){opacity:.5;transform:scale(0);transition:opacity .3s ease,transform .3s ease}.message-content.media .icon-download,.message-content.media .icon-large-play{position:absolute;display:flex;align-items:center;justify-content:center;color:#fff;opacity:.7;transition:opacity .15s}.message-content.media .icon-download:hover,.message-content.media .icon-large-play:hover{opacity:1}.message-content.media .icon-download:before,.message-content.media .icon-large-play:before{display:flex;align-items:center;justify-content:center;width:3.375rem;height:3.375rem;border-radius:50%;background:rgba(0,0,0,.25)}.message-content.media .icon-download{font-size:1.5rem}.message-content.media .icon-large-play{font-size:2.5rem}.message-content.media .message-media-duration,.message-content.media .message-upload-progress{background:rgba(0,0,0,.25);color:#fff;font-size:.75rem;position:absolute;left:.1875rem;top:.1875rem;z-index:1;padding:0 .375rem;border-radius:.75rem;line-height:1.125rem}.message-content.media .message-media-duration .icon-muted-chat{vertical-align:-.1875rem;margin-left:.375rem;font-size:1.0625rem}.message-content.custom-shape{line-height:1.2;font-size:10rem;display:flex;flex-wrap:wrap;align-items:flex-end}.message-content.custom-shape.has-comments{min-height:5.25rem;margin-top:0!important}.message-content.custom-shape.has-comments.has-replies{min-height:6.5rem}.message-content.custom-shape.is-reply{max-width:100%}.message-content.custom-shape .reply-message{display:flex;align-items:flex-start;flex-direction:row-reverse;direction:ltr}.message-content.custom-shape .reply-message>p{margin-bottom:0}.message-content.custom-shape .reply-message .EmbeddedMessage{margin-left:.5rem;border-radius:var(--border-radius-messages)}@media (max-width:600px){.message-content.custom-shape .reply-message .EmbeddedMessage{max-width:calc(90vw - 13rem)}}.message-content.custom-shape .text-content{margin-bottom:1rem}.message-content.custom-shape .media-inner{line-height:1;font-size:1rem;flex-shrink:0}.message-content.custom-shape .media-inner .full-media{top:0;left:0;bottom:0;right:0}.message-content.custom-shape .emoji{display:inline-block;color:transparent}.message-content.custom-shape .emoji::selection{background-color:var(--color-selection-highlight-emoji);color:transparent}.message-content.custom-shape.emoji-only .text-content{margin-bottom:0}.message-content.custom-shape.emoji-only-1{min-width:8rem;font-size:4.5rem}.message-content.custom-shape.emoji-only-1 .content-inner{height:7rem}.message-content.custom-shape.emoji-only-1 .text-content{line-height:1.5;text-align:center}.Message.was-edited .message-content.custom-shape.emoji-only-1{min-width:10rem}.message-content.custom-shape.emoji-only-1 .emoji{width:5rem;height:5rem}.message-content.custom-shape.emoji-only-2{font-size:4rem;margin-top:.5rem;min-width:10rem}.message-content.custom-shape.emoji-only-2.has-comments{margin-top:1.25rem}.Message.was-edited .message-content.custom-shape.emoji-only-2{min-width:12rem}.message-content.custom-shape.emoji-only-2 .emoji{width:4rem;height:4rem}.message-content.custom-shape.emoji-only-3{font-size:3rem;margin-top:1.75rem;min-width:12rem}.message-content.custom-shape.emoji-only-3.has-comments{margin-top:2.5rem}.Message.was-edited .message-content.custom-shape.emoji-only-3{min-width:14rem}.message-content.custom-shape.emoji-only-3 .emoji{width:3rem;height:3rem}.Message:not(.own) .message-content.custom-shape{--hover-color:var(--color-reply-hover);--active-color:var(--color-reply-active)}.Message.own .message-content.custom-shape{--hover-color:var(--color-reply-own-hover);--active-color:var(--color-reply-own-active)}.Message.own .message-content.custom-shape .reply-message{flex-direction:row}.Message.own .message-content.custom-shape .reply-message .EmbeddedMessage{margin-right:.5rem}.forwarded-message{--border-top-left-radius:var(--border-radius-messages-small);--border-top-right-radius:var(--border-radius-messages-small);--border-bottom-left-radius:var(--border-radius-messages-small);--border-bottom-right-radius:var(--border-radius-messages-small)}.message-content:not(.custom-shape) .forwarded-message{position:relative;margin-top:.25rem;padding-left:.625rem}.message-content:not(.custom-shape) .forwarded-message:before{content:"";display:block;position:absolute;top:0;bottom:0;left:.05rem;width:2px;background:var(--accent-color);border-radius:2px}.message-content:not(.custom-shape) .forwarded-message:dir(rtl){padding-inline-start:.625rem}.message-content:not(.custom-shape) .forwarded-message:dir(rtl):before{left:auto;right:.05rem}.forwarded-message>.media-inner{margin:0 0 .25rem!important}.long-word-break-all{word-break:break-all}.text-entity-link{color:var(--color-links)!important;text-decoration:none;word-break:break-word;cursor:pointer;unicode-bidi:normal}.text-entity-link:active,.text-entity-link:hover,.text-entity-link:visited{color:var(--color-links-hover)!important;text-decoration:underline}.text-entity-code,.text-entity-pre{color:var(--color-code);background:var(--color-code-bg);white-space:pre-wrap;margin:0;padding:1px 2px;border-radius:4px}.MessageList{flex:1;width:100%;overflow-anchor:none;overflow:scroll;overflow-x:hidden;overflow-y:overlay;margin-bottom:.5rem}.mask-image-enabled .MessageList{-webkit-mask-image:linear-gradient(0deg,transparent 0,#000 .5rem);mask-image:linear-gradient(0deg,transparent 0,#000 .5rem)}@media (pointer:coarse){.MessageList{-webkit-user-select:none;-webkit-touch-callout:none;user-select:none;touch-callout:none}}.MessageList.no-avatars .Message>.Avatar{display:none}.MessageList .messages-container{width:100%;max-width:var(--messages-container-width);min-height:100%;margin:0 auto;display:flex;justify-content:flex-end;flex-direction:column;padding:1rem 1rem 0 1.125rem}.force-messages-scroll .MessageList .messages-container{margin-top:100vh!important}@media (max-width:600px){.MessageList .messages-container{width:100vw;padding:2.75rem .5rem 0;margin:0}}.MessageList.no-composer{margin-bottom:0}.MessageList.no-composer .last-in-list{margin-bottom:1rem}.MessageList.select-mode-active,.MessageList.type-pinned{margin-bottom:0}.MessageList.select-mode-active .last-in-list,.MessageList.type-pinned .last-in-list{margin-bottom:5.6875rem}.MessageList.select-mode-active .last-in-list.ActionMessage,.MessageList.type-pinned .last-in-list.ActionMessage{padding-bottom:.0625rem}@media (max-width:600px){.MessageList.select-mode-active .last-in-list,.MessageList.type-pinned .last-in-list{margin-bottom:4.3125rem}}.MessageList .ActionMessage,.MessageList .Message{position:relative;opacity:1;transform:scale(1);transition:opacity .2s ease,transform .2s ease}.MessageList .ActionMessage:not(.open),.MessageList .Message:not(.open){transform:scale(.8);opacity:0}.MessageList .ActionMessage.open.shown,.MessageList .Message.open.shown{transform:none}.MessageList .ActionMessage:before,.MessageList .Message:before{content:"";position:absolute;top:-.3125rem;bottom:-.3125rem;left:-50vw;right:-50vw;background:#000;z-index:-1;opacity:0;transition:opacity var(--select-transition)}body.animation-level-0 .MessageList .ActionMessage:before,body.animation-level-0 .MessageList .Message:before{transition:none!important}.MessageList .ActionMessage:not(.last-in-group):before,.MessageList .Message:not(.last-in-group):before{bottom:-.1875rem}.MessageList .ActionMessage:not(.first-in-group):before,.MessageList .Message:not(.first-in-group):before{top:-.1875rem}.MessageList .ActionMessage.focused:before,.MessageList .Message.focused:before{transition:none!important}.MessageList .ActionMessage.focused:before,.MessageList .ActionMessage.has-menu-open:before,.MessageList .ActionMessage.is-forwarding:before,.MessageList .ActionMessage.is-selected:before,.MessageList .Message.focused:before,.MessageList .Message.has-menu-open:before,.MessageList .Message.is-forwarding:before,.MessageList .Message.is-selected:before{opacity:.1}.MessageList>.empty{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.MessageList .ActionMessage,.MessageList .empty,.MessageList .local-action-message,.MessageList .sticky-date{text-align:center}.MessageList .ActionMessage>span,.MessageList .empty>span,.MessageList .local-action-message>span,.MessageList .sticky-date>span{display:inline-block;background:var(--pattern-color);color:#fff;font-size:.9375rem;font-weight:500;line-height:1.5rem;padding:0 .5rem;border-radius:.75rem;word-break:break-word}.MessageList .ActionMessage.rich>span,.MessageList .empty.rich>span,.MessageList .local-action-message.rich>span,.MessageList .sticky-date.rich>span{max-width:80%;text-align:left}.MessageList .ActionMessage.rich a,.MessageList .ActionMessage.rich a:visited,.MessageList .empty.rich a,.MessageList .empty.rich a:visited,.MessageList .local-action-message.rich a,.MessageList .local-action-message.rich a:visited,.MessageList .sticky-date.rich a,.MessageList .sticky-date.rich a:visited{color:var(--color-links-darker)!important}.MessageList .ActionMessage.rich a:active,.MessageList .ActionMessage.rich a:hover,.MessageList .empty.rich a:active,.MessageList .empty.rich a:hover,.MessageList .local-action-message.rich a:active,.MessageList .local-action-message.rich a:hover,.MessageList .sticky-date.rich a:active,.MessageList .sticky-date.rich a:hover{color:var(--color-links-darker-hover)!important}.MessageList .sticky-date{margin-top:1rem;margin-bottom:1rem;z-index:var(--z-sticky-date);pointer-events:none;opacity:1;transition:opacity .3s ease}body:not(.is-scrolling-messages) .MessageList .sticky-date.stuck{opacity:0}body.animation-level-0 .MessageList .sticky-date{transition:none}.MessageList.scrolled .sticky-date{position:sticky;top:.625rem}.has-header-tools .MessageList .sticky-date{top:3.75rem}.MessageList .ActionMessage,.MessageList .local-action-message{margin-top:.5rem;margin-bottom:.5rem}.MessageList .ActionMessage .action-link{cursor:pointer}.MessageList .ActionMessage .action-link:hover{text-decoration:underline}.MessageList .sticky-date+.ActionMessage{margin-top:-.5rem}@media (min-width:1276px){.MessageList{width:100%;transform:translateZ(0);transition:transform var(--layer-transition)}.MessageList .messages-container{width:calc(100% - var(--right-column-width))}body.animation-level-0 .MessageList{transition:none}#Main.right-column-open .MessageList{transform:translate3d(calc(var(--right-column-width)/-2),0,0)}#Main.right-column-open .MessageList:not(.select-mode-active),body.animating-right-column .MessageList:not(.select-mode-active),body:not(.animating-right-column) #Main.right-column-open .MessageList.select-mode-active{width:calc(100% - var(--right-column-width))}#Main.right-column-open .MessageList:not(.select-mode-active) .messages-container,body.animating-right-column .MessageList:not(.select-mode-active) .messages-container,body:not(.animating-right-column) #Main.right-column-open .MessageList.select-mode-active .messages-container{width:100%}}@media (max-width:600px){.MessageList{transition:transform var(--layer-transition)}body.enable-symbol-menu-transforms .MessageList{transform:translateZ(0)}body.is-symbol-menu-open .MessageList{transform:translate3d(0,calc(-1*(var(--symbol-menu-height) + var(--symbol-menu-footer-height))),0)}}.animating>div>.MessageList,.MessageList.has-focusing,.MessageList.select-mode-active,body.has-context-menu .MessageList{padding-right:0}.animating>div>.MessageList::-webkit-scrollbar,.MessageList.has-focusing::-webkit-scrollbar,.MessageList.select-mode-active::-webkit-scrollbar,body.has-context-menu .MessageList::-webkit-scrollbar{width:0}@supports (scrollbar-width:none){.animating>div>.MessageList,.MessageList.has-focusing,.MessageList.select-mode-active,body.has-context-menu .MessageList{padding-right:.6875rem;scrollbar-width:none}}.is-safari.has-context-menu .messages-layout .MessageList,.is-safari .MessageList.has-focusing,.is-safari .MessageList.select-mode-active{padding-right:.375rem}.ScrollDownButton{--base-bottom-pos:6rem;position:absolute;bottom:var(--base-bottom-pos);right:1rem;opacity:0;transform:translateY(4.5rem);transition:transform .25s cubic-bezier(.34,1.56,.64,1),opacity .2s ease;z-index:10;pointer-events:none}body.animation-level-0 .ScrollDownButton{transform:none!important;transition:opacity .15s}@media (max-width:600px){.ScrollDownButton{right:.5rem;bottom:4.5rem}}.ScrollDownButton-inner{display:flex;flex-direction:column;align-items:center}.ScrollDownButton-inner>.Button{box-shadow:0 1px 2px var(--color-default-shadow)}.ScrollDownButton-inner>.Button i{font-size:1.75rem}@media (min-width:1276px){.ScrollDownButton-inner{transform:translateX(0);transition:transform var(--layer-transition)}body.animation-level-0 .ScrollDownButton-inner{transition:none!important}#Main.right-column-open .ScrollDownButton-inner{transform:translateX(calc(-1*var(--right-column-width)))}}@media (max-width:600px){.ScrollDownButton-inner>.Button{width:2.875rem;height:2.875rem}}.ScrollDownButton.revealed{transform:translateY(0);opacity:1;pointer-events:all}.ScrollDownButton.revealed.no-composer{transform:translateY(2.5rem)}.ScrollDownButton .unread-count{min-width:1.5rem;height:1.5rem;padding:0 .45rem;border-radius:.75rem;font-size:.875rem;line-height:1.5rem;font-weight:500;text-align:center;position:absolute;top:-.3rem;right:-.3rem;background:var(--color-green);color:#fff;pointer-events:none}@media (max-width:600px){.ScrollDownButton .unread-count{top:-.7rem;right:auto}}@media (max-width:600px){body.is-symbol-menu-open .ScrollDownButton{bottom:calc(var(--base-bottom-pos) + var(--symbol-menu-height) + var(--symbol-menu-footer-height))}}.ComposerEmbeddedMessage{height:2.625rem;transition:height .15s ease-out,opacity .15s ease-out}.ComposerEmbeddedMessage:not(.open){height:0!important}.ComposerEmbeddedMessage body.animation-level-0{transition:none!important}.ComposerEmbeddedMessage>div{display:flex;align-items:center;padding-right:.625rem;padding-top:.45rem}.ComposerEmbeddedMessage>div>.Button{flex-shrink:0;background:none!important;width:2.125rem;height:2.125rem;margin:0 .625rem;padding:0;align-self:center}.WebPagePreview{height:2.625rem;transition:height .15s ease-out,opacity .15s ease-out;--accent-color:var(--color-primary)}.WebPagePreview:not(.open){height:0!important}.WebPagePreview>div{display:flex;align-items:center;padding-right:.625rem;padding-top:.45rem}.ComposerEmbeddedMessage+.WebPagePreview{margin-top:.75rem}.WebPagePreview>div>.Button{flex-shrink:0;background:none!important;width:2.125rem;height:2.125rem;margin:0 .625rem;padding:0;align-self:center}.WebPagePreview .WebPage{flex-grow:1;margin:.1875rem 0 .1875rem .125rem;max-width:calc(100% - 3.375rem)}.WebPagePreview .WebPage:before{top:.1rem;bottom:.05rem}.WebPagePreview .WebPage .site-description,.WebPagePreview .WebPage .site-title{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:0}@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>.Button{flex-shrink:0;margin-left:.5rem}@media (max-width:600px){.Composer>.Button{width:2.875rem;height:2.875rem}}.Composer>.Button .icon-check,.Composer>.Button .icon-microphone-alt,.Composer>.Button .icon-send{position:absolute}.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-check,.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-send{color:var(--color-primary)}.Composer>.Button.cancel{position:relative;z-index:1}.Composer>.Button.cancel.active,.Composer>.Button.cancel:hover{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-check,.Composer>.Button.send .icon-microphone-alt{animation:hide-icon .4s ease-out forwards}.Composer>.Button.record .icon-microphone-alt{animation:grow-icon .4s ease-out}.Composer>.Button.edit .icon-microphone-alt,.Composer>.Button.edit .icon-send,.Composer>.Button.record .icon-check,.Composer>.Button.record .icon-send{animation:hide-icon .4s ease-out forwards}.Composer>.Button.edit .icon-check{animation:grow-icon .4s ease-out}body.animation-level-0 .Composer>.Button .icon-check,body.animation-level-0 .Composer>.Button .icon-microphone-alt,body.animation-level-0 .Composer>.Button .icon-send,body.animation-level-1 .Composer>.Button .icon-check,body.animation-level-1 .Composer>.Button .icon-microphone-alt,body.animation-level-1 .Composer>.Button .icon-send{animation-duration:0ms!important}.Composer .mobile-symbol-menu-button{width:2.875rem;height:2.875rem;position:relative}.Composer .mobile-symbol-menu-button .icon-keyboard,.Composer .mobile-symbol-menu-button .icon-smile,.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 ease-out forwards}.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 ease-out forwards}.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 ease-out forwards}#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:-.1875rem;right:-.551rem;width:.5625rem;height:1.25rem;transition:opacity .2s}#message-compose .svg-appendix .corner{fill:var(--color-background)}@media (max-width:600px){#message-compose{max-width:calc(100% - 3rem)}}.message-input-wrapper{display:flex}.message-input-wrapper>.Button{flex-shrink:0;background:none!important;width:3.375rem;height:3.375rem;margin:0;padding:.625rem;align-self:flex-end}@media (max-width:600px){.message-input-wrapper>.Button{width:2.875rem;height:2.875rem;margin:0 .25rem}}.message-input-wrapper>.Button+.Button{margin-left:-.25rem}.message-input-wrapper>.Button.scheduled-button i:after{content:"";position:absolute;top:.75rem;right:.75rem;border:.1875rem solid var(--color-background);box-sizing:initial;width:.5rem;height:.5rem;border-radius:50%;background:var(--color-green-darker);box-shadow:-.375rem -.25rem 0 -.1875rem var(--color-background)}@media (max-width:600px){.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}.message-input-wrapper .recording-state:after{content:"";width:10px;height:10px;background:var(--color-error);border-radius:5px;position:absolute;top:50%;margin-top:-5px;right:1.375rem}@media (max-width:600px){.message-input-wrapper .recording-state{height:2.875rem;line-height:2.875rem}}#caption-input-text,#message-input-text{position:relative}#caption-input-text .form-control,#message-input-text .form-control{padding-top:calc(1rem - var(--border-width));padding-bottom:calc(1rem - var(--border-width));overflow:hidden;line-height:1.375rem;font-family:Roboto,-apple-system,Apple Color Emoji,Helvetica Neue,sans-serif;unicode-bidi:plaintext;text-align:initial}#caption-input-text .form-control.overflown,#message-input-text .form-control.overflown{overflow-y:auto;overflow-x:hidden}#caption-input-text .form-control.touched+.placeholder-text,#caption-input-text .form-control:focus+.placeholder-text,#message-input-text .form-control.touched+.placeholder-text,#message-input-text .form-control:focus+.placeholder-text{display:none}#caption-input-text .form-control.focus-disabled,#message-input-text .form-control.focus-disabled{pointer-events:none}#caption-input-text .placeholder-text,#message-input-text .placeholder-text{position:absolute;bottom:.9375rem;color:var(--color-placeholders);pointer-events:none;unicode-bidi:plaintext;text-align:initial}@media (max-width:600px){#caption-input-text .placeholder-text,#message-input-text .placeholder-text{bottom:.6875rem}}#caption-input-text[dir=rtl] .placeholder-text,#message-input-text[dir=rtl] .placeholder-text{right:0}#caption-input-text .text-entity-link,#message-input-text .text-entity-link{color:var(--color-links)!important;cursor:default;text-decoration:none}#caption-input-text .text-entity-link:active,#caption-input-text .text-entity-link:hover,#caption-input-text .text-entity-link:visited,#message-input-text .text-entity-link:active,#message-input-text .text-entity-link:hover,#message-input-text .text-entity-link:visited{color:var(--color-links-hover)!important}#caption-input-text .clone,#message-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-top:calc(1.15625rem - var(--border-width));padding-bottom:calc(1.15625rem - var(--border-width));transition:height .1s ease}@media (max-width:600px){#message-input-text .form-control{height:2.875rem;min-height:2.875rem;max-height:16rem;padding-top:calc(.84375rem - var(--border-width));padding-bottom:calc(.84375rem - var(--border-width))}}body.animation-level-0 #message-input-text .form-control{transition:none!important}#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:.90625rem}.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;overflow-y:overlay;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)}.composer-tooltip:not(.shown){display:none}.composer-tooltip.open{opacity:1;transform:translateY(0)}.composer-tooltip .Loading{margin:1rem 0}#middle-column-bg{position:absolute;top:0;left:0;bottom:0;right:0;overflow:hidden;z-index:-1}#middle-column-bg:after,#middle-column-bg:before{content:"";display:block;position:absolute;top:0;left:0;bottom:0;right:0;background-color:var(--theme-background-color)}#middle-column-bg:after{background-position:50%;background-repeat:no-repeat;background-size:cover}.theme-light #middle-column-bg:after{background-image:url(chat-bg.f607e788298d8a7de37a3b39b76c1efa.jpg)}@media (max-width:600px){.theme-light #middle-column-bg:after{background-image:url(chat-bg-mobile.3ebe59c803c10092f2233e6e00ab2492.jpg)}}body:not(.animation-level-0) #root #middle-column-bg:after{transition:transform var(--layer-transition),opacity .2s!important}body.animation-level-0 #middle-column-bg:after{transition:none}.custom-bg-color>#middle-column-bg:before{filter:blur(0);transform:scale(1.1)}.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:blur(0);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,body.animation-level-2 #middle-column-bg:before{margin:-16rem -5rem -20rem 0;overflow:hidden;transform:scale(1);transform-origin:left center;transition:transform var(--layer-transition)}body.animation-level-2 .custom-bg-image>#middle-column-bg:after{margin:-16rem -5rem -20rem -1rem;transition:transform var(--layer-transition)}body.animation-level-2 #Main.right-column-open :not(.custom-bg-image)>#middle-column-bg:after{transform:scale(.67)}}#MiddleColumn{display:flex;justify-content:center;height:100%;position:relative;z-index:1}@media (max-width:600px){#MiddleColumn{overflow:hidden}}#MiddleColumn .messages-layout{display:flex;flex-direction:column;align-items:center;position:relative}#MiddleColumn .messages-layout,#MiddleColumn .messages-layout>.Transition{width:100%;height:100%;overflow:hidden}#MiddleColumn .messages-layout>.Transition>div{display:flex;flex-direction:column;align-items:center}#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 .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)}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(.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,body.animation-level-0 #MiddleColumn .messaging-disabled .messaging-disabled-inner span{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 .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:translateZ(0);transition: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:before{content:"";position:absolute;top:-.5rem;left:0;right:0;height:1px;background:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.4) 2%,hsla(0,0%,100%,.4) 98%,hsla(0,0%,100%,0));opacity:0;transition:opacity .35s 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,hsla(0,0%,49.8%,0),hsla(0,0%,49.8%,.4) 2%,hsla(0,0%,49.8%,.4) 98%,hsla(0,0%,49.8%,0))}.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:1.25rem}@media (max-width:600px){.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:.5rem}}.Composer,.MessageSelectToolbar,.messaging-disabled,.unpin-all-button{width:100%;display:flex;justify-content:center;position:relative}.mask-image-disabled .MessageSelectToolbar-inner,.mask-image-disabled .messaging-disabled,.mask-image-disabled .unpin-all-button{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow)}.unpin-button-container{width:100%;display:flex;justify-content:center;position:absolute;padding-bottom:1.25rem}.unpin-button-container .unpin-all-button{text-transform:capitalize;color:var(--color-black);height:3.5rem;overflow:visible;transform:scaleX(1);transition:transform var(--select-transition),background-color .15s,color .15s}.unpin-button-container .unpin-all-button:hover .icon-unpin{color:var(--color-white)}.select-mode-active+.middle-column-footer .unpin-button-container .unpin-all-button{box-shadow:none;transform:scaleX(var(--unpin-hidden-scale))}@media (max-width:600px){.unpin-button-container .unpin-all-button{height:2.5rem}}.unpin-button-container .unpin-all-button .icon-unpin{margin-inline-start:-.4375rem;margin-inline-end:.75rem;color:var(--color-text-secondary);font-size:1.5rem;transition:color .15s}@media (max-width:600px){.unpin-button-container{padding-bottom:.75rem}}.mask-image-disabled .unpin-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}.ProfilePhoto{width:100%;height:100%;cursor:pointer;position:relative}.ProfilePhoto img{width:100%;object-fit:cover}.ProfilePhoto .prev-avatar-media{position:absolute;left:0;top:0;z-index:-1}.ProfilePhoto .spinner-wrapper{width:100%;height:100%}.ProfilePhoto.deleted-account,.ProfilePhoto.no-photo,.ProfilePhoto.saved-messages,.ProfilePhoto .spinner-wrapper{display:flex;align-items:center;justify-content:center;color:var(--color-white);background:linear-gradient(var(--color-white) -125%,var(--color-user));cursor:default}.ProfilePhoto.no-photo{font-size:14rem}.ProfilePhoto.deleted-account,.ProfilePhoto.saved-messages{font-size:20rem}.ProfileInfo{aspect-ratio:1/1;position:relative}@supports not (aspect-ratio:1/1){.ProfileInfo:before{float:left;padding-top:100%;content:""}.ProfileInfo:after{display:block;content:"";clear:both}}.ProfileInfo .photo-wrapper{width:100%;position:absolute;left:0;top:0;bottom:0}.ProfileInfo .photo-wrapper>.Transition{width:100%;height:100%}.ProfileInfo .photo-dashes{position:absolute;width:100%;height:.125rem;padding:0 .375rem;z-index:1;display:flex;top:.5rem;left:0}.ProfileInfo .photo-dash{flex:1 1 auto;background-color:var(--color-white);opacity:.5;border-radius:.125rem;margin:0 .125rem}.ProfileInfo .photo-dash.current{opacity:1}.ProfileInfo .navigation{position:absolute;top:0;bottom:0;width:25%;border:none;padding:0;margin:0;-webkit-appearance:none;appearance:none;background:transparent no-repeat;background-size:1.25rem;opacity:.25;transition:opacity .15s;outline:none;cursor:pointer;z-index:1}.is-touch-env .ProfileInfo .navigation,.ProfileInfo .navigation:hover{opacity:1}.ProfileInfo .navigation.prev{left:0;background-image:url(media_navigation_previous.11f3cfece8fead5a78e6349db2545210.svg);background-position:1.25rem 50%}.ProfileInfo .navigation.next{right:0;background-image:url(media_navigation_next.3d6e264d21e73ad725738beb8e9dbbb8.svg);background-position:calc(100% - 1.25rem) 50%}.ProfileInfo .info{position:absolute;bottom:0;left:0;width:100%;min-height:100px;padding:0 1.5rem .5rem;background:linear-gradient(0deg,rgba(0,0,0,.5),transparent);color:var(--color-white);display:flex;flex-direction:column;justify-content:flex-end}.ProfileInfo .info:dir(rtl) .status{text-align:initial;unicode-bidi:plaintext}.ProfileInfo .info[dir=rtl] .status{text-align:initial;unicode-bidi:plaintext}.ProfileInfo .title{display:flex;align-items:center}.ProfileInfo .title h3{font-weight:500;font-size:1.25rem;line-height:1.375rem;white-space:pre-wrap;word-break:break-word;margin-bottom:.25rem}.ProfileInfo .title .VerifiedIcon{margin-left:.25rem;margin-top:-.125rem}.ProfileInfo .title .emoji{width:1.5rem;height:1.5rem;background-size:1.5rem}.ProfileInfo .status{font-size:.875rem;opacity:.5}.ProfileInfo[dir=rtl] .navigation.prev{left:auto;right:0;transform:scaleX(-1)}.ProfileInfo[dir=rtl] .navigation.next{left:0;right:auto;transform:scaleX(-1)}.Profile{height:100%;overflow-y:scroll;overflow-x:hidden}@supports (overflow-y:overlay){.Profile{overflow-y:overlay!important}}.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 -.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}.shared-media{display:flex;flex-direction:column-reverse}.shared-media .TabList{background:var(--color-background);top:-1px}.shared-media .TabList .Tab{padding:1rem .25rem}.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 .message-upload-progress,.shared-media .content.links-list .ProgressSpinner{display:none}.shared-media .content.audio-list{padding:1.25rem}.shared-media .content.audio-list .Audio .media-loading{top:0;left:0;display:flex;align-items:center;justify-content:center}.shared-media .content.audio-list .Audio+.Audio{margin-top:1.6875rem}.shared-media .content.members-list{padding:.5rem 1rem}@media (max-width:600px){.shared-media .content.members-list{padding:.5rem 0}}#RightColumn{position:absolute;top:0;right:0;width:var(--right-column-width);height:100%;transform:translate3d(var(--right-column-width),0,0);background:var(--color-background);border-left:1px solid var(--color-borders);z-index:var(--z-right-column);transition:transform var(--layer-transition)}body.animation-level-0 #RightColumn{transition:none}#RightColumn:not(:hover) .chat-item-clickable:nth-child(n+18){display:none!important}@media (max-width:1275px){#RightColumn{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow);border-left:none}}@media (max-width:600px){#RightColumn{width:100vw;transform:translate3d(110vw,0,0)}}#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:translateZ(0)}#Main{display:flex;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)}}#LeftColumn{flex:1;min-width:18rem;max-width:26.5rem;height:100%}@media (max-width:600px){#LeftColumn{height:calc(var(--vh, 1vh)*100)}}@media (min-width:1680px){#LeftColumn{border-left:1px solid var(--color-borders)}}@media (max-width:1275px){#LeftColumn{flex:2}}@media (max-width:925px){#LeftColumn{position:fixed;left:0;top:0;height:calc(var(--vh, 1vh)*100);width:26.5rem;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:translateZ(0)}#Main:not(.middle-column-open) #LeftColumn:after{opacity:0;pointer-events:none}#Main.middle-column-open #LeftColumn .custom-scroll{overflow:hidden}}@media (max-width:600px){#LeftColumn{max-width:none;width:100vw;transform:translate3d(-20vw,0,0)}}@media (min-width:1680px){#RightColumn{border-right:1px solid var(--color-borders)}}@media (max-width:600px){#RightColumn{height:calc(var(--vh, 1vh)*100 + 1px)}}#MiddleColumn{flex:3;border-left:1px solid var(--color-borders);max-width:75vw}@media (max-width:1275px){#MiddleColumn{max-width:calc(100vw - 26.5rem)}}@media (max-width:66.25rem){#MiddleColumn{max-width:60vw}}@media (min-width:1680px){#MiddleColumn{border-right:1px solid var(--color-borders);max-width:calc(1680px - 26.5rem)}}@media (max-width:925px){#MiddleColumn{max-width:none;position:fixed;left:0;top:0;bottom:0;right:0;transform:translateZ(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)}}@media (max-width:600px){.SymbolMenu{transition:transform var(--layer-transition)}body.animation-level-0 .SymbolMenu{transition:none}body:not(.is-middle-column-open) .SymbolMenu{transform:translate3d(100vw,0,0)!important}} \ No newline at end of file +.Switcher{display:inline-flex;align-items:center;position:relative;margin:0}.Switcher.disabled{opacity:.5}.Switcher.disabled,.Switcher.inactive{pointer-events:none}.Switcher.no-animation .widget,.Switcher.no-animation .widget:after,body.animation-level-0 .Switcher .widget,body.animation-level-0 .Switcher .widget:after{transition:none!important}.Switcher.no-animation .widget:active:after,body.animation-level-0 .Switcher .widget:active:after{width:1.125rem}.Switcher input{height:0;width:0;visibility:hidden;position:absolute;z-index:var(--z-below);opacity:0}.Switcher .widget{cursor:pointer;text-indent:-999px;width:2.125rem;height:.875rem;background:var(--color-gray);display:inline-block;border-radius:.5rem;position:relative;transition:background .2s ease-in}.Switcher .widget:after{content:"";position:absolute;top:-.125rem;left:0;width:1.125rem;height:1.125rem;background:var(--color-background);border-radius:.75rem;transition:.2s ease-out;border:.125rem solid var(--color-gray)}.Switcher input:checked+.widget{background:var(--color-primary)}.Switcher input:checked+.widget:after{left:calc(100% - 1.125rem);transform:translateX(calc(-100% + 1.125rem));border-color:var(--color-primary)}.Switcher .widget:active:after{width:1.25rem}#LeftMainHeader{position:relative}#LeftMainHeader .animated-menu-icon{position:absolute}#LeftMainHeader .animated-menu-icon,#LeftMainHeader .animated-menu-icon:after,#LeftMainHeader .animated-menu-icon:before{width:1.125rem;height:.125rem;border-radius:.125rem;background-color:var(--color-text-secondary);transition:transform .25s;transform:rotate(0)}#LeftMainHeader .animated-menu-icon:after,#LeftMainHeader .animated-menu-icon:before{position:absolute;left:0;content:""}#LeftMainHeader .animated-menu-icon:before{top:-.3125rem}#LeftMainHeader .animated-menu-icon:after{top:.3125rem}#LeftMainHeader .animated-menu-icon.state-back{transform:rotate(180deg)}#LeftMainHeader .animated-menu-icon.state-back:before{transform:rotate(45deg) scaleX(.75) translate(.375rem,-.1875rem)}#LeftMainHeader .animated-menu-icon.state-back:after{transform:rotate(-45deg) scaleX(.75) translate(.375rem,.1875rem)}#LeftMainHeader .archived-badge{min-width:1.5rem;height:1.5rem;margin-left:auto;background:var(--color-gray);border-radius:.75rem;padding:0 .45rem;color:#fff;font-size:.875rem;line-height:1.5rem;font-weight:500;text-align:center;flex-shrink:0}#LeftMainHeader [dir=rtl] .archived-badge{margin-left:0;margin-right:auto}#LeftMainHeader .Menu .bubble{min-width:17rem}.Transition>div:not(.active) #LeftMainHeader .Menu .bubble,body.animating-right-column #LeftMainHeader .Menu .bubble{transition:none!important}#ConnectionState{flex:0 0 auto;display:flex;align-items:center;margin:0 .5rem .5rem;padding:.75rem;background:var(--color-yellow);border-radius:var(--border-radius-default)}#ConnectionState>.Spinner{--spinner-size:1.75rem}#ConnectionState>.state-text{color:var(--color-text-lighter);font-weight:500;line-height:2rem;margin-inline-start:1.875rem;white-space:nowrap}@media (max-width:950px){#ConnectionState>.state-text{margin-inline-start:1.25rem}}.NewChatButton{position:absolute;right:1rem;bottom:1rem;transform:translateY(5rem);transition:transform .25s cubic-bezier(.34,1.56,.64,1)}body.animation-level-0 .NewChatButton{transform:none!important;opacity:0;transition:opacity .15s}body.animation-level-0 .NewChatButton.revealed{opacity:1}.NewChatButton.revealed{transform:translateY(0)}@media (max-width:600px){.NewChatButton.revealed{transform:translateZ(10px);transform-style:preserve-3d}}.NewChatButton.menu-is-open:before{content:"";display:block;position:absolute;top:-13rem;left:-11rem;right:-1rem;bottom:-1rem;z-index:-1}.is-touch-env .NewChatButton .Menu>.backdrop{position:absolute;left:-100vw;right:-100vw;top:-100vh;bottom:-100vh}.NewChatButton>.Button .icon-close,.NewChatButton>.Button .icon-new-chat-filled{position:absolute}.NewChatButton>.Button:not(.active) .icon-new-chat-filled{animation:grow-icon .4s ease-out}.NewChatButton>.Button:not(.active) .icon-close{animation:hide-icon .4s ease-out forwards}.NewChatButton>.Button.active .icon-close{animation:grow-icon .4s ease-out}.NewChatButton>.Button.active .icon-new-chat-filled{animation:hide-icon .4s ease-out forwards}#LeftColumn-main{height:100%;position:relative;display:flex;flex-direction:column;overflow:hidden;z-index:1}#LeftColumn-main>.Transition{flex:1;overflow:hidden}#LeftColumn-main .ChatFolders{height:100%;display:flex;flex-direction:column;overflow:hidden}#LeftColumn-main .ChatFolders .tabs-placeholder{height:2.625rem;transition:height .15s ease}#LeftColumn-main .ChatFolders .tabs-placeholder:not(.open){height:0}#LeftColumn-main .ChatFolders .TabList{justify-content:flex-start;padding-left:.5625rem;padding-bottom:1px;border-bottom:0;z-index:1}#LeftColumn-main .ChatFolders .Tab{flex:0 0 auto;padding-left:.625rem;padding-right:.625rem}#LeftColumn-main .ChatFolders .Tab>span{padding-left:.5rem;padding-right:.5rem}#LeftColumn-main .ChatFolders>.Transition{flex:1;overflow:hidden}#LeftColumn-main .chat-list,#LeftColumn-main .LeftSearch,#LeftColumn-main .RecentContacts,#LeftColumn-main .search-content{height:100%;overflow-y:auto}#LeftColumn{overflow:hidden}#NewChat{height:100%}.left-header{height:var(--header-height);padding:.375rem 1.25rem .5rem .8125rem;display:flex;align-items:center;flex-shrink:0;background-color:var(--color-background)}.left-header h3{margin-bottom:0;font-size:1.25rem;font-weight:500;margin-left:1.375rem}.left-header .SearchInput{margin-left:.875rem;max-width:calc(100% - 3.625rem)}@media (max-width:600px){.left-header .SearchInput{max-width:calc(100% - 3.375rem)}}@media (max-width:600px){.left-header{padding:.5rem}}.AudioPlayer{display:flex;margin-left:auto;margin-top:-.25rem;margin-bottom:-.25rem}body.animation-level-0 .AudioPlayer{transition:none!important}.AudioPlayer>.Button{flex-shrink:0;margin:.125rem}.AudioPlayer>.toggle-play{--color-text-secondary:var(--color-primary);--color-text-secondary-rgb:var(--color-primary-shade-rgb);--color-primary-shade:var(--color-green);--color-white:var(--color-background-own)}.MiddleHeader .AudioPlayer+.HeaderActions{margin-left:1.5rem}.AudioPlayer .toggle-play.smaller{width:3rem;height:3rem}.AudioPlayer .toggle-play.smaller i{font-size:1.625rem;margin-top:-.025rem}.AudioPlayer .toggle-play i{position:absolute;font-size:1.9375rem;margin-top:-.05rem}.AudioPlayer .toggle-play i.icon-play{margin-left:.1rem}.AudioPlayer .toggle-play .icon-pause,.AudioPlayer .toggle-play .icon-play{opacity:1;transform:scale(1);transition:opacity .4s,transform .6s cubic-bezier(.34,1.56,.64,1)}.AudioPlayer .toggle-play.loading .icon-pause,.AudioPlayer .toggle-play.loading .icon-play,.AudioPlayer .toggle-play.pause .icon-play,.AudioPlayer .toggle-play.play .icon-pause{opacity:0;transform:scale(.5)}.AudioPlayer-content{display:flex;justify-content:center;flex-direction:column;flex-shrink:1;padding:.25rem .5rem;position:relative;overflow:hidden;cursor:pointer;max-width:15rem;border-radius:var(--border-radius-messages-small)}.AudioPlayer-content:hover{background-color:var(--color-interactive-element-hover)}@media (min-width:1440px) and (max-width:1500px){.AudioPlayer-content{max-width:14rem}}.AudioPlayer .AudioPlayer-content .title{display:block;font-weight:500;font-size:.875rem!important;line-height:1rem;height:1rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.AudioPlayer-content .subtitle{font-size:.85rem!important;color:var(--color-text-secondary);line-height:1.125rem;height:1.125rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:.125rem 0 0}.MiddleHeader{display:flex;align-items:center;width:100%;box-shadow:0 2px 2px var(--color-light-shadow);background:var(--color-background);padding:.5rem .8125rem .5rem 1.5rem;position:relative;z-index:var(--z-middle-header)}@media (max-width:600px){.MiddleHeader{padding:.5rem;position:relative;transform:translateZ(10px);transform-style:preserve-3d}}.MiddleHeader .Transition{width:100%;min-width:0}.MiddleHeader .Transition>div{display:flex;align-items:center;width:100%}.MiddleHeader .back-button{margin-left:-.5rem;margin-right:.5rem;position:relative}@media (max-width:600px){.MiddleHeader .back-button{margin-left:0}}.MiddleHeader .back-button .unread-count{min-width:1.25rem;height:1.25rem;padding:0 .375rem;border-radius:.625rem;font-size:.75rem;line-height:1.25rem;font-weight:500;text-align:center;position:absolute;top:-.25rem;right:-.5rem;background:var(--color-gray);color:#fff;pointer-events:none}.MiddleHeader .back-button .unread-count.active{background:var(--color-primary)}.MiddleHeader .chat-info-wrapper{flex-grow:1;overflow:hidden}.MiddleHeader .header-tools{display:flex;align-items:center;justify-content:flex-end;margin-left:auto;flex-shrink:0}body.animation-level-0 .MiddleHeader .header-tools,body.animation-level-0 .MiddleHeader .header-tools .AudioPlayer,body.animation-level-0 .MiddleHeader .header-tools .HeaderActions,body.animation-level-0 .MiddleHeader .header-tools .HeaderPinnedMessage-wrapper{transition:none!important}@media (min-width:1276px) and (max-width:1439px){.MiddleHeader .header-tools .HeaderActions{transform:translateZ(0);transition:transform var(--layer-transition)}#Main.right-column-open .MiddleHeader .header-tools .HeaderActions{transform:translate3d(calc(var(--right-column-width)*-1),0,0)}}@media (min-width:1440px){.MiddleHeader .header-tools{transform:translateZ(0);transition:transform var(--layer-transition)}#Main.right-column-open .MiddleHeader .header-tools{transform:translate3d(calc(var(--right-column-width)*-1),0,0)}}.Transition>div:not(.active) .MiddleHeader .header-tools,body.animating-right-column .MiddleHeader .header-tools{pointer-events:none}@media (min-width:1276px) and (max-width:1439px){.MiddleHeader:not(.tools-stacked) .header-tools .AudioPlayer,.MiddleHeader:not(.tools-stacked) .header-tools .HeaderPinnedMessage-wrapper{opacity:1}#Main.right-column-open .MiddleHeader:not(.tools-stacked) .header-tools .AudioPlayer,#Main.right-column-open .MiddleHeader:not(.tools-stacked) .header-tools .HeaderPinnedMessage-wrapper{opacity:0}}.MiddleHeader.tools-stacked .header-tools .AudioPlayer,.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper{position:absolute;top:100%;left:0;right:0;height:2.875rem;overflow:hidden;box-shadow:0 2px 2px var(--color-light-shadow);display:flex;flex-direction:row-reverse;padding:.375rem .5rem .375rem .75rem;background:var(--color-background)}.MiddleHeader.tools-stacked .header-tools .AudioPlayer:before,.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper:before{content:"";display:block;position:absolute;top:-.1875rem;left:0;right:0;height:.125rem;box-shadow:0 .125rem .125rem var(--color-light-shadow)}.MiddleHeader.tools-stacked .header-tools .AudioPlayer .HeaderPinnedMessage,.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper .HeaderPinnedMessage{max-width:unset;margin-top:-.1875rem}.MiddleHeader.tools-stacked .header-tools .AudioPlayer{height:3.25rem;flex-direction:row;padding:.375rem .5rem}.MiddleHeader.tools-stacked .header-tools .AudioPlayer-content{padding:0 .5rem;flex-grow:1}.MiddleHeader.tools-stacked .header-tools .AudioPlayer>.Button{margin:0}.MiddleHeader.tools-stacked .header-tools .AudioPlayer>.player-close{margin-left:auto}.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage{flex-grow:1;padding-top:0;padding-bottom:0}.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage:before{top:.125rem;bottom:.125rem}.MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage .message-text{max-width:none}@media (min-width:1150px){#Main.right-column-open .MiddleHeader.tools-stacked .header-tools .AudioPlayer,#Main.right-column-open .MiddleHeader.tools-stacked .header-tools .HeaderPinnedMessage-wrapper{padding-right:calc(.5rem + var(--right-column-width))}}.MiddleHeader.tools-stacked.animated .header-tools .AudioPlayer,.MiddleHeader.tools-stacked.animated .header-tools .HeaderPinnedMessage-wrapper{animation:fade-in var(--layer-transition) forwards}body.animation-level-0 .MiddleHeader.tools-stacked.animated .header-tools .AudioPlayer,body.animation-level-0 .MiddleHeader.tools-stacked.animated .header-tools .HeaderPinnedMessage-wrapper{animation:none}.MiddleHeader h3{font-weight:500;font-size:1.125rem;line-height:1.375rem;white-space:pre;margin:0;overflow:hidden;text-overflow:ellipsis;unicode-bidi:plaintext}@media (max-width:600px){.MiddleHeader h3{display:block;overflow:hidden;text-overflow:ellipsis}}@media (min-width:1275px){#Main.right-column-open .MiddleHeader h3{max-width:calc(100% - var(--right-column-width))}}.MiddleHeader .ChatInfo{cursor:pointer;display:flex;align-items:center}.MiddleHeader .ChatInfo .info{display:flex;flex-direction:column;justify-content:center;flex-grow:1;overflow:hidden}.MiddleHeader .ChatInfo .title{display:flex;align-items:center}.MiddleHeader .ChatInfo .title .VerifiedIcon{width:1.25rem;height:1.25rem;margin-left:.25rem;margin-top:.05rem}.MiddleHeader .ChatInfo .status,.MiddleHeader .ChatInfo .user-status{unicode-bidi:plaintext}.MiddleHeader .Avatar{margin-right:.625rem;width:2.5rem;height:2.5rem;font-size:1.0625rem}.MiddleHeader .status,.MiddleHeader .typing-status{font-size:.875rem;line-height:1.125rem;margin:0;color:var(--color-text-secondary);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;display:inline-block}.MiddleHeader .status .ellipsis,.MiddleHeader .typing-status .ellipsis{display:inline-flex}.MiddleHeader .status.online,.MiddleHeader .typing-status.online{color:var(--color-primary)}.MiddleHeader .status .font-emoji,.MiddleHeader .typing-status .font-emoji{line-height:1rem}.MiddleHeader .Button.smaller{width:2.5rem;height:2.5rem}.MiddleHeader .HeaderPinnedMessage-wrapper{display:flex;align-items:center;margin-left:auto;cursor:default;flex-direction:row-reverse}body.animation-level-1 .MiddleHeader .HeaderPinnedMessage-wrapper .ripple-container{display:none}.MiddleHeader .HeaderPinnedMessage-wrapper .HeaderPinnedMessage{min-width:16rem}.MiddleHeader .HeaderPinnedMessage-wrapper>.Button{flex-shrink:0}.MiddleHeader .HeaderPinnedMessage{display:flex;flex-shrink:1;margin-top:-.25rem;margin-bottom:-.25rem;padding:.25rem .25rem .25rem .375rem;border-radius:var(--border-radius-messages-small);position:relative;overflow:hidden;cursor:pointer}.MiddleHeader .HeaderPinnedMessage:hover{background-color:var(--color-interactive-element-hover)}.MiddleHeader .HeaderPinnedMessage .pinned-message-border{position:relative;height:2.25rem;margin:.125rem 0;width:.125rem;min-width:.125rem;overflow:hidden}.MiddleHeader .HeaderPinnedMessage .pinned-message-border .pinned-message-border-wrapper-1{height:2.25rem;width:.125rem;border-radius:.0625rem;background:var(--color-primary)}.MiddleHeader .HeaderPinnedMessage .pinned-message-border .pinned-message-border-wrapper{background-color:var(--color-primary-opacity);position:relative;will-change:transform;transition:transform .25s ease-in-out}.MiddleHeader .HeaderPinnedMessage .pinned-message-border .pinned-message-border-mark{position:absolute;left:0;top:0;width:.125rem;background:var(--color-primary);border-radius:.0625rem;will-change:transform;transition:transform .25s ease-in-out}.MiddleHeader .HeaderPinnedMessage .message-text{overflow:hidden;margin-inline-start:.375rem;margin-top:.125rem;max-width:15rem}@media (min-width:1440px) and (max-width:1500px){.MiddleHeader .HeaderPinnedMessage .message-text{max-width:14rem}}.MiddleHeader .HeaderPinnedMessage .message-text .title{font-weight:500;font-size:.875rem;line-height:1rem;height:1rem;color:var(--color-primary);margin-bottom:.125rem;white-space:pre;text-align:initial}.MiddleHeader .HeaderPinnedMessage .message-text p{font-size:.875rem;line-height:1.125rem;height:1.125rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:0}.MiddleHeader .HeaderPinnedMessage .emoji-small{width:1rem;height:1rem}.MiddleHeader .HeaderPinnedMessage>img{width:2.25rem;height:2.25rem;object-fit:cover;border-radius:.25rem;margin-inline-start:.375rem;margin-top:.125rem;flex-shrink:0}.MiddleHeader .HeaderPinnedMessage>img+.message-text{max-width:12rem}.MiddleHeader .HeaderActions{flex-shrink:0;margin-left:auto;display:flex;align-items:center;justify-content:flex-end}.MiddleHeader .HeaderActions .toggle-right-pane-button.active{color:var(--color-primary);opacity:1}.MiddleHeader .HeaderActions .Button,.MiddleHeader .HeaderPinnedMessage-wrapper .Button{margin-left:.25rem}.MiddleHeader .HeaderActions .Button.tiny,.MiddleHeader .HeaderPinnedMessage-wrapper .Button.tiny{margin-right:.625rem}@media (max-width:600px){.MiddleHeader .AudioPlayer,.MiddleHeader .HeaderPinnedMessage-wrapper{position:absolute;top:100%;left:0;right:0;height:2.875rem;overflow:hidden;box-shadow:0 2px 2px var(--color-light-shadow);display:flex;flex-direction:row-reverse;padding:.375rem .5rem .375rem .75rem;background:var(--color-background)}.MiddleHeader .AudioPlayer:before,.MiddleHeader .HeaderPinnedMessage-wrapper:before{content:"";display:block;position:absolute;top:-.1875rem;left:0;right:0;height:.125rem;box-shadow:0 .125rem .125rem var(--color-light-shadow)}.MiddleHeader .AudioPlayer .HeaderPinnedMessage,.MiddleHeader .HeaderPinnedMessage-wrapper .HeaderPinnedMessage{max-width:unset;margin-top:-.1875rem}.MiddleHeader .AudioPlayer{height:3.25rem;flex-direction:row;padding:.375rem .5rem}.MiddleHeader .AudioPlayer-content{padding:0 .5rem;flex-grow:1}.MiddleHeader .AudioPlayer>.Button{margin:0}.MiddleHeader .AudioPlayer>.player-close{margin-left:auto}.MiddleHeader .HeaderPinnedMessage{flex-grow:1;padding-top:0;padding-bottom:0}.MiddleHeader .HeaderPinnedMessage:before{top:.125rem;bottom:.125rem}.MiddleHeader .HeaderPinnedMessage .message-text{max-width:none}.MiddleHeader .AudioPlayer,.MiddleHeader .HeaderPinnedMessage-wrapper{transform:translateZ(0)}}@media (min-width:925px) and (max-width:1149.9px){.MiddleHeader .AudioPlayer,.MiddleHeader .HeaderPinnedMessage-wrapper{position:absolute}}@keyframes fade-in{0%{opacity:0}to{opacity:1}}.EmbeddedMessage{display:flex;align-items:center;font-size:.875rem;line-height:1.125rem;margin:0 -.25rem .0625rem;padding:.1875rem .25rem .1875rem .4375rem;border-radius:var(--border-radius-messages-small);position:relative;overflow:hidden;cursor:pointer;direction:ltr}body.animation-level-1 .EmbeddedMessage .ripple-container{display:none}.custom-shape .EmbeddedMessage{max-width:15rem;padding:.5rem;margin:0;background-color:var(--background-color);box-shadow:0 1px 2px var(--color-default-shadow)}.custom-shape .EmbeddedMessage:before{left:.625rem;top:.625rem;bottom:.625rem}.custom-shape .EmbeddedMessage img:not(.emoji){margin-inline-start:.5rem}.custom-shape .EmbeddedMessage:dir(rtl){padding:.5rem}.EmbeddedMessage:before{content:"";display:block;position:absolute;top:.3125rem;bottom:.3125rem;left:.3125rem;width:2px;background:var(--accent-color);border-radius:2px}.EmbeddedMessage:hover{background-color:var(--hover-color)}.EmbeddedMessage:active{background-color:var(--active-color)}.EmbeddedMessage .message-text{overflow:hidden;margin-inline-start:.5rem;display:flex;flex-direction:column-reverse}.EmbeddedMessage .message-text .message-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:.125rem;flex:1;display:block}.EmbeddedMessage .message-text p{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;height:1.125rem;margin-bottom:0;flex:1}.EmbeddedMessage .message-text p:after{content:none;display:none}.EmbeddedMessage .message-text .emoji{width:1.125rem!important;height:1.125rem!important;vertical-align:-4px!important}.EmbeddedMessage .embedded-action-message{color:var(--accent-color);opacity:.75}.EmbeddedMessage img:not(.emoji){width:2rem;height:2rem;object-fit:cover;border-radius:.25rem;margin-left:.25rem;flex-shrink:0}.EmbeddedMessage img:not(.emoji).round{border-radius:1rem}.EmbeddedMessage.inside-input{padding-inline-start:.5625rem;margin:0 0 -.125rem -.1875rem;display:grid;grid-template-columns:auto 1fr;grid-template-rows:1fr;width:100%;--accent-color:var(--color-primary);--hover-color:var(--color-interactive-element-hover)}.EmbeddedMessage.inside-input:before{bottom:.3125rem}.EmbeddedMessage.inside-input img:not(.emoji){margin-left:.125rem}.EmbeddedMessage.inside-input .message-text{margin-inline-start:.375rem}.EmbeddedMessage.inside-input .message-title{font-weight:500;color:var(--accent-color)}.MessageMeta{position:absolute;height:1.25rem;bottom:0;right:0;display:flex;align-items:center;background:hsla(0,0%,60%,.6);border-radius:.625rem;padding:0 .25rem;color:#fff;cursor:pointer;max-width:100%}.MessageMeta .message-signature,.MessageMeta .message-time,.MessageMeta .message-views{font-size:.75rem;white-space:nowrap}.MessageMeta .message-time{margin-right:.1875rem}.MessageMeta .message-views{margin-left:.1875rem}.MessageMeta .message-signature{overflow:hidden;text-overflow:ellipsis;margin-right:.375rem}.MessageMeta .icon-channelviews{margin-left:.125rem;margin-right:.375rem;font-size:1.125rem;position:relative;top:-.0625rem}.has-solid-background .MessageMeta{color:rgba(var(--color-text-meta-rgb),.75);background:none}.media:not(.text) .MessageMeta,.Message .custom-shape .MessageMeta{background:rgba(0,0,0,.2);--color-accent-own:#fff;--color-accent:#fff;color:#fff!important;opacity:1;bottom:.25rem;right:.25rem;left:auto;height:1.125rem;padding:0 .3125rem 0 .375rem}.media:not(.text) .MessageMeta .MessageOutgoingStatus i,.Message .custom-shape .MessageMeta .MessageOutgoingStatus i{background:transparent}.media:not(.text):dir(rtl) .MessageMeta,.Message .custom-shape:dir(rtl) .MessageMeta{right:auto!important;left:.25rem;padding:0 .375rem 0 .3125rem}.is-forwarded.media:not(.text):dir(rtl) .MessageMeta,.Message .is-forwarded.custom-shape:dir(rtl) .MessageMeta{left:.8125rem}.is-forwarded.media:not(.text) .MessageMeta{bottom:.935rem;right:.8125rem}.emoji-only .MessageMeta{right:0}.Message.own .has-solid-background .MessageMeta{color:var(--color-message-meta-own)}.MessageMeta .MessageOutgoingStatus{margin-left:-.1875rem;font-size:1.1875rem;border-radius:.625rem}.Message.own .MessageMeta .MessageOutgoingStatus{color:var(--color-accent-own)}.message-content.has-replies:not(.custom-shape) .MessageMeta{bottom:3.375rem}.message-content.has-replies.text:not(.custom-shape) .MessageMeta{bottom:3.4375rem}.Message:not(.own) .custom-shape .reply-message+.MessageMeta{right:auto;left:13.2rem;bottom:.25rem}.Message:not(.own) .emoji-only-1 .reply-message+.MessageMeta{left:2.5rem}.Message:not(.own) .emoji-only-2 .reply-message+.MessageMeta{left:5.5rem}.Message:not(.own) .emoji-only-3 .reply-message+.MessageMeta{left:6.5rem}.Sticker:not(.inactive){cursor:pointer}.Sticker.inactive{pointer-events:none}.Contact{display:flex;align-items:center;padding:.25rem}.Contact.interactive{cursor:pointer}.Contact .Avatar{margin-right:.8rem}.Contact .contact-info{padding:.5rem .5rem .5rem 0;white-space:nowrap;overflow:hidden}.Contact .contact-info .contact-name{font-size:1rem;line-height:1rem;margin-bottom:.25rem;font-weight:500}.Contact .contact-info .contact-phone{line-height:1rem;color:var(--secondary-color)}.PollOption{display:flex;flex-flow:row nowrap;margin-bottom:.75rem}.PollOption:last-child{margin-bottom:0}.PollOption .poll-option-text{word-break:break-word}.PollOption .poll-option-share{position:relative;margin-top:.125rem;width:1.75rem;margin-inline-end:.5rem;flex-shrink:0;font-weight:500;font-size:.875rem;text-align:right}.PollOption .poll-option-share.limit-width{display:inline-flex;justify-content:center;font-size:.75rem}.PollOption .poll-option-chosen{position:absolute;right:0;bottom:-5px;width:1rem;height:1rem;background:var(--accent-color);color:var(--background-color);border-radius:.5rem;font-size:.75rem;text-align:center}.PollOption .poll-option-chosen.wrong{background:var(--color-error)}.is-forwarded .PollOption .poll-option-chosen>i{margin-left:1px}.PollOption .poll-option-chosen.animate{opacity:0;animation-name:PollOptionIconAnimate;animation-delay:.09s;animation-duration:.3s;animation-fill-mode:forwards}.PollOption .poll-option-right{flex-grow:1}.PollOption .poll-option-answer{position:relative}.PollOption .poll-option-line{position:relative;width:0;height:.25rem;min-width:.5rem;border-radius:.125rem;margin-top:.5rem;background:var(--accent-color);transform-origin:0 0;transition:transform .3s;transition-delay:.09s}.PollOption .poll-line{width:30px;height:35px;position:absolute;left:-27px;bottom:-5px;transition:stroke-dashoffset .3s,stroke-dasharray .3s;stroke-dashoffset:0;stroke-dasharray:0,200%}.PollOption .poll-line path{stroke-width:4px;stroke-linecap:round;stroke:var(--accent-color);fill:none}.PollOption .wrong .poll-option-line{background:var(--color-error)}.PollOption .wrong .poll-line path{stroke:var(--color-error)}@keyframes PollOptionIconAnimate{0%{opacity:0}to{opacity:1}}.Poll{min-width:15rem;text-align:initial}@media (max-width:600px){.Poll{min-width:50vw}}.Poll .poll-question{font-weight:500;line-height:1.25rem;margin:.125rem 0;word-break:break-word}.Poll .poll-type,.Poll .poll-voters-count{color:var(--secondary-color);font-size:.875rem}.Poll .poll-type{margin-bottom:.5rem;display:flex;align-items:center;min-height:1.375rem}.Poll .poll-voters-count{margin:.4375rem 0 .3125rem;text-align:center}.Poll .poll-answers{padding-top:.25rem;padding-bottom:1rem}.Poll .Checkbox,.Poll .Radio{padding-left:2.25rem}.Poll .Checkbox:last-child,.Poll .Radio:last-child{margin-bottom:.75rem}.Poll .Checkbox.disabled,.Poll .Radio.disabled{opacity:1!important;cursor:not-allowed}.Poll .Checkbox .Checkbox-main:before,.Poll .Checkbox .Radio-main:before,.Poll .Radio .Checkbox-main:before,.Poll .Radio .Radio-main:before{left:.125rem;background-color:var(--background-color)}.theme-dark .Poll .Checkbox .Checkbox-main:before,.theme-dark .Poll .Checkbox .Radio-main:before,.theme-dark .Poll .Radio .Checkbox-main:before,.theme-dark .Poll .Radio .Radio-main:before{--color-borders:var(--color-borders-input)}.Message.own .Poll .Checkbox .Checkbox-main:before,.Message.own .Poll .Checkbox .Radio-main:before,.Message.own .Poll .Radio .Checkbox-main:before,.Message.own .Poll .Radio .Radio-main:before{--color-borders:var(--accent-color)}.Poll .Checkbox .Checkbox-main:after,.Poll .Checkbox .Radio-main:after,.Poll .Radio .Checkbox-main:after,.Poll .Radio .Radio-main:after{left:.4375rem;background-color:var(--accent-color)}.Poll .Checkbox input:checked~.Checkbox-main:before,.Poll .Checkbox input:checked~.Radio-main:before,.Poll .Radio input:checked~.Checkbox-main:before,.Poll .Radio input:checked~.Radio-main:before{border-color:var(--accent-color)}.Poll .Checkbox .Spinner,.Poll .Radio .Spinner{left:.125rem}.Poll .Checkbox .Checkbox-main:after{left:.125rem;background-color:var(--color-primary)}.Message.own .Poll .Checkbox .Checkbox-main:after{background-color:var(--accent-color)}.Poll .Spinner>div{background-image:var(--spinner-gray-data)}.theme-dark .Poll .Spinner>div{background-image:var(--spinner-white-data)}.Message.own .Poll .Spinner>div{background-image:var(--spinner-green-data)}.theme-dark .Message.own .Poll .Spinner>div{background-image:var(--spinner-white-data)}.Poll .poll-recent-voters{display:inline-flex;align-items:center;vertical-align:text-bottom;margin-left:.875rem;margin-right:.5rem;margin-top:-2px}.Poll .poll-recent-voters .Avatar{border:1px solid var(--color-white);margin-right:0;box-sizing:initial}.Poll .poll-recent-voters .Avatar:not(:first-child){margin-left:-3px}.Poll .poll-countdown{margin-left:auto;font-size:.75rem;transition:color .2s}.Poll .poll-countdown.hurry-up{color:var(--color-error)}.Poll .poll-countdown.hurry-up .poll-countdown-progress{stroke:var(--color-error)}.Poll .poll-countdown svg{vertical-align:-3px}.Poll .poll-countdown-progress{stroke:var(--color-primary);fill:transparent;stroke-width:2;stroke-linecap:round;transition:stroke-dashoffset 2s,stroke .2s}.Poll .poll-quiz-help{margin:-.625rem 0 -.625rem auto}.Message:not(.own) .Poll .poll-quiz-help{color:var(--color-primary)}.Poll .poll-answers,.Poll .poll-results{padding-top:.25rem;padding-bottom:.5rem}.Poll .Button{text-transform:none;font-size:1rem}.Message.own .Poll .Button{color:var(--accent-color);--color-primary-shade-rgb:var(--color-accent-own)}.Poll>.Button{margin-top:-.125rem;margin-bottom:-.0625rem}.WebPage{margin-top:.25rem;margin-bottom:.125rem;padding-left:.625rem;font-size:.875rem;line-height:1.125rem;max-width:29rem;position:relative}.WebPage:before{content:"";display:block;position:absolute;top:0;bottom:0;left:0;width:2px;background:var(--accent-color);border-radius:2px}.WebPage-text{display:flex;flex-direction:column;align-items:flex-start}.WebPage .media-inner{margin:0 0 .375rem!important}.WebPage .media-inner,.WebPage .media-inner.small-image img,.WebPage .media-inner img{border-radius:var(--border-radius-messages-small)!important}.WebPage .media-inner.square-image{width:5rem;height:5rem;min-height:0;margin-bottom:0!important}.WebPage .media-inner.square-image img{width:100%;height:100%}.WebPage.with-square-photo{display:flex;margin-bottom:1rem}.WebPage.with-square-photo .WebPage-text{order:1;padding-right:1rem}.WebPage.with-square-photo .media-inner{order:2;flex-shrink:0}.WebPage.with-square-photo:dir(rtl) .WebPage-text{padding-inline-end:1rem}.WebPage:not(.with-square-photo) .site-description:last-child:after,.WebPage:not(.with-square-photo) .site-name:last-child:after,.WebPage:not(.with-square-photo) .site-title:last-child:after{content:"";display:inline-block;width:var(--meta-safe-area-size);height:.5rem}.WebPage .site-description,.WebPage .site-name,.WebPage .site-title{word-break:break-word}.WebPage .site-name{color:var(--accent-color)}.WebPage .site-name,.WebPage .site-title{font-weight:500;margin-bottom:.125rem}.WebPage .site-description{line-height:1rem;margin-bottom:0}.WebPage:dir(rtl){padding-inline-start:.625rem}.WebPage:dir(rtl):before{left:auto;right:0}.Invoice .title{color:var(--accent-color);font-weight:500}.Invoice .description{position:relative}.Invoice .description.has-image .invoice-image{max-width:100%;height:20rem}@media (max-width:600px){.Invoice .description.has-image .invoice-image{height:10rem}}.Invoice .description.has-image .description-text{position:absolute;top:0;padding:.25rem .5rem;margin:.25rem;background-color:rgba(90,110,70,.6);border-radius:var(--border-radius-messages-small);color:var(--color-text);font-weight:500}.Album{position:relative;overflow:hidden}.message-content.media.text .Album{margin:-.3125rem -.5rem .3125rem}.forwarded-message .Album{margin-bottom:.125rem}.message-content.media.text .forwarded-message .Album{margin:0 0 .3125rem;--border-bottom-left-radius:inherit;--border-bottom-right-radius:inherit}.Album>.album-item-select-wrapper .media-inner,.message-content.media.text .Album>.album-item-select-wrapper .media-inner{margin:0!important}.Album>.album-item-select-wrapper .media-inner,.Album>.album-item-select-wrapper .media-inner img,.Album>.album-item-select-wrapper .media-inner video{border-radius:0!important;object-fit:cover}.RoundVideo{position:relative;width:200px;height:200px;cursor:pointer}.RoundVideo .thumbnail-wrapper{width:200px;height:200px;border-radius:50%;overflow:hidden}.RoundVideo .video-wrapper{position:absolute;left:0;top:0;border-radius:50%;overflow:hidden}.RoundVideo .progress{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none}.RoundVideo .progress-circle{stroke:#fff;fill:transparent;stroke-width:4;stroke-opacity:.35;stroke-linecap:round}.RoundVideo video::-internal-media-controls-cast-button,.RoundVideo video::-webkit-media-controls,.RoundVideo video::-webkit-media-controls-start-playback-button{display:none}.InlineButtons{display:flex;flex-direction:column}.InlineButtons .row{display:flex;flex-direction:row}.InlineButtons .Button{flex:1;width:auto;margin:.125rem;background:var(--pattern-color);border-radius:var(--border-radius-messages-small);font-weight:500;text-transform:none}.InlineButtons .Button:before{content:"";background-color:var(--color-white);opacity:0;position:absolute;top:0;left:0;right:0;bottom:0;border-radius:var(--border-radius-messages-small);z-index:var(--z-below);transition:opacity .2s}.InlineButtons .Button:hover{background:var(--pattern-color)!important}.InlineButtons .Button:hover:before{opacity:.4}.InlineButtons .Button:first-of-type{margin-left:0}.InlineButtons .Button:last-of-type{margin-right:0}.InlineButtons .Button i{font-size:.75rem;position:absolute;right:.125rem;top:.125rem;display:block;transform:rotate(-45deg)}.InlineButtons .row:first-of-type .Button{margin-top:.25rem!important}.InlineButtons .row:last-of-type .Button{margin-bottom:0}.InlineButtons .row:last-of-type .Button:first-of-type{border-bottom-left-radius:var(--border-radius-messages)}.InlineButtons .row:last-of-type .Button:last-of-type{border-bottom-right-radius:var(--border-radius-messages)}.CommentButton{--background-color:var(--color-background);--hover-color:var(--color-chat-hover);display:flex;width:100%;align-items:center;padding:.5625rem .25rem .5625rem .625rem;padding-inline-start:.625rem;padding-inline-end:.25rem;background:var(--background-color);border-bottom-right-radius:var(--border-bottom-right-radius);border-bottom-left-radius:var(--border-bottom-left-radius);font-size:.9375rem;font-weight:500;line-height:2rem;color:var(--accent-color);white-space:nowrap;cursor:pointer;transition:background-color .15s,color .15s}body.animation-level-0 .CommentButton{transition:none!important}.Message .has-appendix .CommentButton:before{content:"";display:block;position:absolute;bottom:-.1875rem;left:-.5625rem;width:.5625rem;height:1.25rem;background-position:0 100%;background-image:url("data:image/svg+xml;charset=utf-8,%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");opacity:0;transition:opacity .15s,filter .15s}.theme-dark #root .Message .has-appendix .CommentButton:before{filter:invert(.83)}body.animation-level-0 .Message .has-appendix .CommentButton:before{transition:none!important}.custom-shape .CommentButton{position:absolute;right:-3rem;width:2.25rem;bottom:3rem;height:3.375rem;border-radius:1.375rem;padding:.375rem .3125rem .25rem;align-items:flex-start;color:#fff;background-color:rgba(0,0,0,.2);opacity:0;transition:opacity .2s ease}@media (pointer:coarse){.custom-shape .CommentButton{opacity:1!important}}.custom-shape .CommentButton:hover{background-color:rgba(0,0,0,.28)}.Message:hover .custom-shape .CommentButton{opacity:1}.custom-shape .CommentButton:after{content:attr(data-cnt);position:absolute;bottom:-.0625rem;left:0;width:100%;text-align:center;font-size:12px;display:block}.custom-shape .CommentButton[data-cnt="0"]{height:2.25rem}.custom-shape .CommentButton[data-cnt="0"]:after{display:none}.custom-shape .CommentButton .icon-comments-sticker{display:block;font-size:1.5rem;margin:0 auto}.custom-shape .CommentButton .icon-comments,.custom-shape .CommentButton .icon-next,.custom-shape .CommentButton .label,.custom-shape .CommentButton .recent-repliers{display:none}.CommentButton:hover{background:var(--hover-color)}.Message .has-appendix .CommentButton:hover:before{opacity:1}.CommentButton:hover .Avatar{border-color:var(--hover-color)!important}.audio .CommentButton,.is-forwarded .CommentButton,.poll .CommentButton,.text .CommentButton,.voice .CommentButton{border-top:1px solid var(--color-borders)}.message-content.has-solid-background .CommentButton{margin:.375rem -.5rem -.375rem}.message-content.voice .CommentButton{margin-bottom:-.5rem}.message-content.audio .CommentButton{margin-bottom:-.8125rem}.message-content.audio .CommentButton,.message-content.has-solid-background.is-forwarded .CommentButton,.message-content.has-solid-background.text .CommentButton,.message-content.poll .CommentButton,.message-content.voice .CommentButton{width:calc(100% + 1rem)}.CommentButton .icon-comments-sticker{display:none}.CommentButton .icon-comments{font-size:1.5625rem;line-height:2rem;margin-inline-end:.875rem}.CommentButton .icon-next{margin-inline-start:auto;font-size:1.5rem}.CommentButton .recent-repliers{display:inline-flex;align-items:center;margin-inline-end:.5rem;margin-inline-start:-.125rem}.CommentButton .recent-repliers .Avatar{transition:border .15s;border:2px solid var(--color-background);margin-inline-end:0;z-index:3;overflow:hidden}.CommentButton .recent-repliers .Avatar .emoji{width:1rem;background-size:1rem}.CommentButton .recent-repliers .Avatar+.Avatar{z-index:2}.CommentButton .recent-repliers .Avatar+.Avatar+.Avatar{z-index:1}.CommentButton .recent-repliers .Avatar:not(:first-child){margin-inline-start:-.75rem}.CommentButton.has-unread .label{position:relative}.CommentButton.has-unread .label:after{content:"";display:inline-block;width:.5rem;height:.5rem;border-radius:50%;background:var(--accent-color);margin-inline-start:.75rem}.CommentButton.disabled{cursor:default;pointer-events:none}.Message{display:flex;align-items:flex-end;margin-bottom:.375rem;position:relative;--background-color:var(--color-background);--hover-color:var(--color-reply-hover);--active-color:var(--color-reply-active);--max-width:29rem;--accent-color:var(--color-primary);--accent-shade-color:var(--color-primary-shade);--secondary-color:var(--color-text-secondary);--meta-safe-area-base:2.25rem;--meta-safe-author-width:0px;--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width));--deleting-translate-x:-50%;--select-message-scale:0.9;--select-background-color:#fff}.Message>.Avatar,.Message>.message-content-wrapper{opacity:1;transform:scale(1) translateX(0);transition:transform var(--select-transition)}body.animation-level-0 .Message>.Avatar,body.animation-level-0 .Message>.message-content-wrapper{transition:none!important}.Message>.Avatar{position:absolute;bottom:0;left:0}@media (max-width:600px){.Message>.Avatar{width:2.5rem;height:2.5rem}}.Message.last-in-group{margin-bottom:.625rem}.Message.last-in-list{margin-bottom:.4375rem}.Message.is-in-selection-mode .Album{border:1px solid var(--select-background-color);background-color:var(--select-background-color)}.Message.has-inline-buttons .message-content{border-bottom-right-radius:var(--border-radius-messages-small)}.Message:not(.own){padding-left:2.5rem}.Message:not(.own).is-thread-top,.no-avatars .Message:not(.own){padding-left:0}@media (max-width:600px){.Message:not(.own){padding-left:2.875rem}.Message:not(.own).is-thread-top,.no-avatars .Message:not(.own){padding-left:.25rem}}.Message.own{flex-direction:row-reverse;--background-color:var(--color-background-own);--hover-color:var(--color-reply-own-hover);--active-color:var(--color-reply-own-active);--max-width:30rem;--accent-color:var(--color-accent-own);--accent-shade-color:var(--color-green);--secondary-color:var(--color-accent-own);--color-code:var(--color-code-own);--color-code-bg:var(--color-code-own-bg);--color-links:var(--color-own-links);--color-links-hover:var(--color-own-links);--meta-safe-area-base:3.5rem;--deleting-translate-x:50%;--color-text-green:var(--color-accent-own)}@media (max-width:600px){.Message.own{padding-right:.25rem}}.Message.is-deleting>.Avatar,.Message.is-deleting>.message-content-wrapper{transition:opacity .2s ease,transform .2s ease-in;opacity:0;transform:scale(.3) translateX(var(--deleting-translate-x));transform-origin:bottom}.Message.has-views{--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + 4rem)}.Message.was-edited{--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + 2.5rem)}.Message.was-edited.has-views{--meta-safe-area-size:calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + 7.5rem)}.select-mode-active .Message{cursor:pointer;-webkit-user-select:none;user-select:none}.select-mode-active .Message:not(.own)>.Avatar,.select-mode-active .Message:not(.own)>.message-content-wrapper{transform:translateX(2.5rem)}.select-mode-active .Message:not(.is-album):after{content:"";position:absolute;top:-.25rem;bottom:-.25rem;left:-4rem;right:-4rem;z-index:var(--z-message-select-area)}.select-mode-active .Message.is-album .message-select-control,.select-mode-active .Message.is-in-document-group .message-select-control{pointer-events:unset}.select-mode-active .Message .message-select-control{opacity:1}.Message.is-selected .message-select-control{background:var(--color-green)}.Message.is-selected .message-select-control.group-select{background:transparent}.Message .File.file-is-selected .message-select-control,.Message.is-selected .message-select-control.group-select.is-selected{background:var(--color-green)}.Message.has-menu-open.is-in-document-group .File .file-icon,.Message.is-in-document-group .File.file-is-selected .file-icon{--background-color:var(--color-background-selected)}.Message.own.has-menu-open.is-in-document-group .File .file-icon,.Message.own.is-in-document-group .File.file-is-selected .file-icon{--background-color:var(--color-background-own-selected)}.Message .Audio .message-select-control{left:1.0625rem;top:1.375rem}html.theme-dark .Message.own .Audio .ProgressSpinner{background-image:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUiIGhlaWdodD0iMTUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTguMjE4IDcuNWw1LjYzMy01LjYzM2EuNTA4LjUwOCAwIDEwLS43MTgtLjcxOEw3LjUgNi43ODIgMS44NjcgMS4xNDlhLjUwOC41MDggMCAxMC0uNzE4LjcxOEw2Ljc4MiA3LjVsLTUuNjMzIDUuNjMzYS41MDguNTA4IDAgMTAuNzE4LjcxOEw3LjUgOC4yMThsNS42MzMgNS42MzNhLjUwNi41MDYgMCAwMC43MTggMCAuNTA4LjUwOCAwIDAwMC0uNzE4TDguMjE4IDcuNXoiIGZpbGw9IiNGRkYiIHN0cm9rZT0iI0E0NUQzNyIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjwvc3ZnPg==)}html.theme-dark .Message.own .Audio .ProgressSpinner circle{stroke:var(--background-color)}.Message .File{position:relative}.Message .File .message-select-control{position:absolute;top:2rem;left:2rem;z-index:2}.Message.own .Message .album-item-select-wrapper{background:var(--color-background-own)}.Message .album-item-select-wrapper .message-select-control{top:.438rem;right:.438rem;left:unset}.Message .album-item-select-wrapper .media-inner{border:0 solid var(--select-background-color);transition:border-width var(--select-transition)}.Message .album-item-select-wrapper img,.Message .album-item-select-wrapper video{transition:transform var(--select-transition)}.Message .album-item-select-wrapper.is-selected .message-select-control{background:var(--color-green)}.Message .album-item-select-wrapper.is-selected img,.Message .album-item-select-wrapper.is-selected video{transform:scale(var(--select-message-scale))}.Message.is-forwarding .message-select-control,.Message.is-selected .message-select-control{background:var(--color-green)}.Message.is-forwarding .Menu .bubble,.Message.is-selected .Menu .bubble{transition:none!important}.Message.is-in-document-group:not(.first-in-document-group):before{top:0!important}.Message.is-in-document-group:not(.first-in-document-group) .message-content{box-shadow:none;border-top-left-radius:0!important;border-top-right-radius:0!important}.Message.is-in-document-group:not(.first-in-document-group) .forwarded-message:before{top:-1.5rem}.Message.is-in-document-group:not(.last-in-document-group){margin-bottom:0}.Message.is-in-document-group:not(.last-in-document-group):before{bottom:0!important}.Message.is-in-document-group:not(.last-in-document-group) .message-content{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important}.Message.is-in-document-group.is-in-selection-mode .Audio:not(.audio-is-selected) .message-select-control:not(.group-select),.Message.is-in-document-group.is-in-selection-mode .File:not(.file-is-selected) .message-select-control:not(.group-select){background:#fff}.Message.is-in-document-group.is-in-selection-mode .Audio:not(.audio-is-selected) .message-select-control:not(.group-select):after,.Message.is-in-document-group.is-in-selection-mode .File:not(.file-is-selected) .message-select-control:not(.group-select):after{content:"";width:1.25rem;height:1.25rem;border-radius:.688rem;background:#fff;border:.125rem solid rgba(0,0,0,.2);position:absolute}.Message.is-in-document-group.is-in-selection-mode.own .message-content .Audio:not(.audio-is-selected) .message-select-control:not(.group-select),.Message.is-in-document-group.is-in-selection-mode.own .message-content .File:not(.file-is-selected) .message-select-control:not(.group-select){background:var(--background-color);border-color:var(--background-color)}.Message.is-in-document-group.is-in-selection-mode.own .message-content .Audio:not(.audio-is-selected) .message-select-control:not(.group-select):after,.Message.is-in-document-group.is-in-selection-mode.own .message-content .File:not(.file-is-selected) .message-select-control:not(.group-select):after{background:var(--background-color);border-color:var(--color-message-meta-own)}.Message.is-in-document-group.focused .message-content,.Message.is-in-document-group.has-menu-open .message-content,.Message.is-in-document-group.is-forwarding .message-content,.Message.is-in-document-group.is-selected .message-content{background:var(--color-background-selected)}.Message.is-in-document-group.focused.own .message-content,.Message.is-in-document-group.has-menu-open.own .message-content,.Message.is-in-document-group.is-forwarding.own .message-content,.Message.is-in-document-group.is-selected.own .message-content{--background-color:var(--color-background-own-selected);background:var(--color-background-own-selected)}.Message.is-in-document-group .message-content-wrapper{width:17.1875rem}.Message.is-in-document-group .message-content{transition:background-color var(--select-transition)}.Message.is-in-document-group.own .message-content-wrapper{display:flex;justify-content:flex-end}.Message.is-in-document-group.own .message-content-wrapper .message-content{width:100%}.Message .album-item-select-wrapper{position:absolute}.Message .album-item-select-wrapper .message-select-control{position:absolute;z-index:2}.Message .message-select-control{position:absolute;left:0;bottom:.25rem;width:1.5rem;height:1.5rem;border:2px solid #fff;border-radius:50%;z-index:var(--z-message-select-control);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1rem;opacity:0;pointer-events:none;transition:opacity var(--select-transition)}.Message .message-select-control .icon-select{position:absolute;left:-3px;top:-3px;font-size:1.625rem}.theme-dark .Message .message-select-control{border-color:hsla(0,0%,100%,.5)}.Message .Avatar{margin-right:.3rem}.Message.is-in-document-group .message-content.document{padding:.25rem .5rem!important}.Message.is-in-document-group.last-in-document-group .message-content.document{padding-bottom:.5rem!important}.Message.is-in-document-group.first-in-document-group .message-content.document{padding-top:.5rem!important}.Album,.media-inner,.message-content,.message-content.custom-shape .media-inner img,.message-content.media .media-inner img,.message-content.media .media-inner video{border-top-left-radius:var(--border-top-left-radius);border-top-right-radius:var(--border-top-right-radius);border-bottom-left-radius:var(--border-bottom-left-radius);border-bottom-right-radius:var(--border-bottom-right-radius)}.media-inner video.full-media{background:transparent!important}.media-inner{overflow:hidden}.media-inner.small-image img{border-radius:0!important}.Message{--border-top-left-radius:var(--border-radius-messages);--border-top-right-radius:var(--border-radius-messages);--border-bottom-left-radius:var(--border-radius-messages);--border-bottom-right-radius:var(--border-radius-messages)}.Message:not(.own).first-in-group:not(.last-in-group),.Message:not(.own):not(.first-in-group):not(.last-in-group){--border-bottom-left-radius:var(--border-radius-messages-small)}.Message:not(.own).last-in-group:not(.first-in-group),.Message:not(.own):not(.first-in-group):not(.last-in-group){--border-top-left-radius:var(--border-radius-messages-small)}.Message:not(.own).last-in-group{--border-bottom-left-radius:var(--border-radius-messages-small)}.Message:not(.own).last-in-group .message-content.has-appendix{--border-bottom-left-radius:0}.Message.own.first-in-group:not(.last-in-group),.Message.own:not(.first-in-group):not(.last-in-group){--border-bottom-right-radius:var(--border-radius-messages-small)}.Message.own.last-in-group:not(.first-in-group),.Message.own:not(.first-in-group):not(.last-in-group){--border-top-right-radius:var(--border-radius-messages-small)}.Message.own.last-in-group{--border-bottom-right-radius:var(--border-radius-messages-small)}.Message.own.last-in-group .message-content.has-appendix{--border-bottom-right-radius:0}.Message .message-content.has-replies:not(.custom-shape) .Album,.Message .message-content.has-replies:not(.custom-shape) .media-inner,.Message .message-content.text .Album,.Message .message-content.text .media-inner{--border-bottom-left-radius:0;--border-bottom-right-radius:0}.Message .message-content.is-reply .EmbeddedMessage+.Album,.Message .message-content.is-reply .EmbeddedMessage+.Audio,.Message .message-content.is-reply .EmbeddedMessage+.File{margin-top:.375rem}.Message .message-content:not(.custom-shape).force-sender-name .Album,.Message .message-content:not(.custom-shape).is-reply .Album,.Message .message-content:not(.custom-shape).is-reply .media-inner,.Message .message-content:not(.is-forwarded) .message-title~.media-inner{--border-top-left-radius:0;--border-top-right-radius:0}.Message .message-content.is-forwarded .content-inner .message-title{margin-bottom:.25rem}.Message .message-action-button{position:absolute;bottom:0;color:#fff;background-color:rgba(0,0,0,.2);opacity:0;transition:opacity .2s ease}@media (pointer:coarse){.Message .message-action-button{opacity:1!important}}.Message .message-action-button:active,.Message .message-action-button:focus,.Message .message-action-button:hover{background-color:rgba(0,0,0,.28)!important}.Message:hover .message-action-button,.Message[data-is-document-group-hover] .message-action-button{opacity:1}.Message.own .message-action-button{left:-3rem}.Message:not(.own) .message-action-button{right:-3rem}.Message .bottom-marker{height:1px;width:1px;visibility:hidden}.Message .custom-shape .message-action-button{bottom:.25rem}.message-content{position:relative;max-width:var(--max-width)}@media (max-width:600px){.message-content{max-width:69vw}}.message-content .text-content{margin:0;word-break:break-word;line-height:1.3125;text-align:initial;display:flow-root;unicode-bidi:plaintext}.message-content .text-entity-link{unicode-bidi:plaintext}.message-content.document>.MessageMeta,.message-content .text-content>.MessageMeta{position:relative;top:.4375rem;bottom:auto!important;float:right;line-height:1;margin-left:.4375rem;margin-right:-.5rem}.message-content.document:dir(rtl)>.MessageMeta,.message-content .text-content:dir(rtl)>.MessageMeta{float:left;margin-left:-.25rem;margin-right:.4375rem}.message-content.document:not(.text):after{content:"";display:block;clear:both}.message-content.document:not(.text)>.MessageMeta{position:relative;top:auto;bottom:-.5rem!important}.theme-dark .Message.own .message-content .text-entity-link{text-decoration:underline}.theme-dark .Message.own .message-content .text-entity-link:hover{text-decoration:none}.message-content:not(.custom-shape){font-size:var(--message-text-size,1rem)}.message-content:not(.custom-shape)>.content-inner{min-width:0}.message-content .matching-text-highlight{background:#cae3f7;border-radius:.25rem;padding:0 .125rem}.message-content .message-title{white-space:nowrap;font-size:.875rem;font-weight:500;line-height:1.25rem;color:var(--accent-color);unicode-bidi:plaintext;display:flex}.message-content .message-title,.message-content .message-title>.interactive{overflow:hidden;text-overflow:ellipsis}.message-content .message-title.interactive,.message-content .message-title>.interactive{cursor:pointer}.message-content .message-title.interactive:hover,.message-content .message-title>.interactive:hover{opacity:.85}.message-content .message-title>.color-1{color:var(--color-user-1)}.message-content .message-title>.color-2{color:var(--color-user-2)}.message-content .message-title>.color-4{color:var(--color-user-4)}.message-content .message-title>.color-5{color:var(--color-user-5)}.message-content .message-title>.color-6{color:var(--color-user-6)}.message-content .message-title>.color-7{color:var(--color-user-7)}.message-content .message-title>.color-8{color:var(--color-user-8)}.message-content .message-title+.File{margin-top:.25rem}.message-content .message-title .via{padding:0 .2rem;font-weight:400}.message-content .message-title .admin-title{flex:1;margin-left:1rem;text-align:right;font-weight:400;font-size:.75rem;margin-top:-.1rem;color:rgba(var(--color-text-meta-rgb),.75)}.Message.own .message-content .message-title .admin-title{color:var(--accent-color)}.message-content.has-shadow{box-shadow:0 1px 2px var(--color-default-shadow)}.is-album .message-content,.message-content.has-solid-background{background:var(--background-color)}.message-content.has-solid-background{padding:.3125rem .5rem .375rem}.message-content.has-solid-background .forwarded-message>.text-content:not(.with-meta):last-child:after{content:"";display:inline-block;width:var(--meta-safe-area-size);height:1rem}.message-content:not(.has-appendix) .svg-appendix{display:none}.message-content .svg-appendix{position:absolute;bottom:-.1875rem;width:.5625rem;height:1.25rem}.message-content .svg-appendix .corner{fill:var(--background-color)}.Message.own .message-content .svg-appendix{right:-.551rem}.Message:not(.own) .message-content .svg-appendix{left:-.562rem}.message-content[data-has-custom-appendix] .svg-appendix .corner{fill:var(--appendix-bg)}.Message .message-content.has-appendix-thumb .svg-appendix{--background-color:#ccc;opacity:1;transition:opacity .5s ease}.message-content.document{padding:.5rem!important}.theme-dark .message-content.document .File{--color-primary:var(--color-selection-highlight)}.message-content.document .File+.text-content{margin-top:.313rem}.message-content.audio .Embedded,.message-content.audio .message-title,.message-content.voice .Embedded,.message-content.voice .message-title{margin-top:-.1875rem;margin-bottom:.1875rem}.message-content.voice{padding:.5rem!important}.message-content.voice .Voice+.text-content{margin-top:.5rem}.message-content.audio{min-width:17.1875rem;padding:.5rem .5rem .8125rem!important}.message-content.audio .Audio+.text-content{margin-top:.25rem;margin-bottom:-.4375rem}.message-content:not(.custom-shape) .emoji{display:inline-block;width:1.25rem;background-size:1.25rem;color:transparent;margin-inline-end:1px;vertical-align:text-bottom}.message-content:not(.custom-shape) .emoji::selection{background-color:var(--color-selection-highlight-emoji);color:transparent}.message-content:not(.custom-shape) .text-content .emoji{width:calc(1.25*var(--message-text-size, 1rem));background-size:calc(1.25*var(--message-text-size, 1rem))}.message-content .no-media-corners{--border-top-left-radius:0;--border-top-right-radius:0}.message-content.media .media-inner{display:flex;justify-content:center;align-items:center}.message-content.media .media-inner.interactive{cursor:pointer}.message-content.media .media-inner.interactive.dark video{background-color:#232323}.message-content.media.round.is-reply{width:auto!important}.message-content.media.force-sender-name .Album,.message-content.media.force-sender-name .media-inner,.message-content.media.is-reply .Album,.message-content.media.is-reply .media-inner,.message-content.media.is-via-bot .media-inner,.message-content.media.text .media-inner{margin-left:-.5rem;margin-right:-.5rem}.message-content.media.text .media-inner{margin-top:-.3125rem}.message-content.media.force-sender-name .Album,.message-content.media.is-reply .Album,.message-content.media.is-reply .media-inner,.message-content.media .message-title~.media-inner{margin-top:.375rem;margin-bottom:-.375rem}.message-content.media.text .Album,.message-content.media.text .media-inner{margin-bottom:.375rem}.message-content.media .media-loading{display:flex;align-items:center;justify-content:center}.message-content.media .media-loading:not(.open){opacity:.5;transform:scale(0);transition:opacity .3s ease,transform .3s ease}.message-content.media .icon-download,.message-content.media .icon-large-play{position:absolute;display:flex;align-items:center;justify-content:center;color:#fff;opacity:.7;transition:opacity .15s}.message-content.media .icon-download:hover,.message-content.media .icon-large-play:hover{opacity:1}.message-content.media .icon-download:before,.message-content.media .icon-large-play:before{display:flex;align-items:center;justify-content:center;width:3.375rem;height:3.375rem;border-radius:50%;background:rgba(0,0,0,.25)}.message-content.media .icon-download{font-size:1.5rem}.message-content.media .icon-large-play{font-size:2.5rem}.message-content.media .message-media-duration,.message-content.media .message-upload-progress{background:rgba(0,0,0,.25);color:#fff;font-size:.75rem;position:absolute;left:.1875rem;top:.1875rem;z-index:1;padding:0 .375rem;border-radius:.75rem;line-height:1.125rem}.message-content.media .message-media-duration .icon-muted-chat{vertical-align:-.1875rem;margin-left:.375rem;font-size:1.0625rem}.message-content.custom-shape{line-height:1.2;font-size:10rem;display:flex;flex-wrap:wrap;align-items:flex-end}.message-content.custom-shape.has-comments{min-height:5.25rem;margin-top:0!important}.message-content.custom-shape.has-comments.has-replies{min-height:6.5rem}.message-content.custom-shape.is-reply{max-width:100%}.message-content.custom-shape .reply-message{display:flex;align-items:flex-start;flex-direction:row-reverse;direction:ltr}.message-content.custom-shape .reply-message>p{margin-bottom:0}.message-content.custom-shape .reply-message .EmbeddedMessage{margin-left:.5rem;border-radius:var(--border-radius-messages)}@media (max-width:600px){.message-content.custom-shape .reply-message .EmbeddedMessage{max-width:calc(90vw - 13rem)}}.message-content.custom-shape .text-content{margin-bottom:1rem}.message-content.custom-shape .media-inner{line-height:1;font-size:1rem;flex-shrink:0}.message-content.custom-shape .media-inner .full-media{top:0;left:0;bottom:0;right:0}.message-content.custom-shape .emoji{display:inline-block;color:transparent}.message-content.custom-shape .emoji::selection{background-color:var(--color-selection-highlight-emoji);color:transparent}.message-content.custom-shape.emoji-only .text-content{margin-bottom:0}.message-content.custom-shape.emoji-only-1{min-width:8rem;font-size:4.5rem}.message-content.custom-shape.emoji-only-1 .content-inner{height:7rem}.message-content.custom-shape.emoji-only-1 .text-content{line-height:1.5;text-align:center}.Message.was-edited .message-content.custom-shape.emoji-only-1{min-width:10rem}.message-content.custom-shape.emoji-only-1 .emoji{width:5rem;height:5rem}.message-content.custom-shape.emoji-only-2{font-size:4rem;margin-top:.5rem;min-width:10rem}.message-content.custom-shape.emoji-only-2.has-comments{margin-top:1.25rem}.Message.was-edited .message-content.custom-shape.emoji-only-2{min-width:12rem}.message-content.custom-shape.emoji-only-2 .emoji{width:4rem;height:4rem}.message-content.custom-shape.emoji-only-3{font-size:3rem;margin-top:1.75rem;min-width:12rem}.message-content.custom-shape.emoji-only-3.has-comments{margin-top:2.5rem}.Message.was-edited .message-content.custom-shape.emoji-only-3{min-width:14rem}.message-content.custom-shape.emoji-only-3 .emoji{width:3rem;height:3rem}.Message:not(.own) .message-content.custom-shape{--hover-color:var(--color-reply-hover);--active-color:var(--color-reply-active)}.Message.own .message-content.custom-shape{--hover-color:var(--color-reply-own-hover);--active-color:var(--color-reply-own-active)}.Message.own .message-content.custom-shape .reply-message{flex-direction:row}.Message.own .message-content.custom-shape .reply-message .EmbeddedMessage{margin-right:.5rem}.forwarded-message{--border-top-left-radius:var(--border-radius-messages-small);--border-top-right-radius:var(--border-radius-messages-small);--border-bottom-left-radius:var(--border-radius-messages-small);--border-bottom-right-radius:var(--border-radius-messages-small)}.message-content:not(.custom-shape) .forwarded-message{position:relative;margin-top:.25rem;padding-left:.625rem}.message-content:not(.custom-shape) .forwarded-message:before{content:"";display:block;position:absolute;top:0;bottom:0;left:.05rem;width:2px;background:var(--accent-color);border-radius:2px}.message-content:not(.custom-shape) .forwarded-message:dir(rtl){padding-inline-start:.625rem}.message-content:not(.custom-shape) .forwarded-message:dir(rtl):before{left:auto;right:.05rem}.forwarded-message>.media-inner{margin:0 0 .25rem!important}.long-word-break-all{word-break:break-all}.text-entity-link{color:var(--color-links)!important;text-decoration:none;word-break:break-word;cursor:pointer;unicode-bidi:normal}.text-entity-link:active,.text-entity-link:hover,.text-entity-link:visited{color:var(--color-links-hover)!important;text-decoration:underline}.text-entity-code,.text-entity-pre{color:var(--color-code);background:var(--color-code-bg);white-space:pre-wrap;margin:0;padding:1px 2px;border-radius:4px}.MessageList{flex:1;width:100%;overflow-anchor:none;overflow:scroll;overflow-x:hidden;overflow-y:overlay;margin-bottom:.5rem}.mask-image-enabled .MessageList{-webkit-mask-image:linear-gradient(0deg,transparent 0,#000 .5rem);mask-image:linear-gradient(0deg,transparent 0,#000 .5rem)}@media (pointer:coarse){.MessageList{-webkit-user-select:none;-webkit-touch-callout:none;user-select:none;touch-callout:none}}.MessageList.no-avatars .Message>.Avatar{display:none}.MessageList .messages-container{width:100%;max-width:var(--messages-container-width);min-height:100%;margin:0 auto;display:flex;justify-content:flex-end;flex-direction:column;padding:1rem 1rem 0 1.125rem}.force-messages-scroll .MessageList .messages-container{margin-top:100vh!important}@media (max-width:600px){.MessageList .messages-container{width:100vw;padding:2.75rem .5rem 0;margin:0}}.MessageList.no-composer{margin-bottom:0}.MessageList.no-composer .last-in-list{margin-bottom:1rem}.MessageList.select-mode-active,.MessageList.type-pinned{margin-bottom:0}.MessageList.select-mode-active .last-in-list,.MessageList.type-pinned .last-in-list{margin-bottom:5.6875rem}.MessageList.select-mode-active .last-in-list.ActionMessage,.MessageList.type-pinned .last-in-list.ActionMessage{padding-bottom:.0625rem}@media (max-width:600px){.MessageList.select-mode-active .last-in-list,.MessageList.type-pinned .last-in-list{margin-bottom:4.3125rem}}.MessageList .ActionMessage,.MessageList .Message{position:relative;opacity:1;transform:scale(1);transition:opacity .2s ease,transform .2s ease}.MessageList .ActionMessage:not(.open),.MessageList .Message:not(.open){transform:scale(.8);opacity:0}.MessageList .ActionMessage.open.shown,.MessageList .Message.open.shown{transform:none}.MessageList .ActionMessage:before,.MessageList .Message:before{content:"";position:absolute;top:-.3125rem;bottom:-.3125rem;left:-50vw;right:-50vw;background:#000;z-index:-1;opacity:0;transition:opacity var(--select-transition)}body.animation-level-0 .MessageList .ActionMessage:before,body.animation-level-0 .MessageList .Message:before{transition:none!important}.MessageList .ActionMessage:not(.last-in-group):before,.MessageList .Message:not(.last-in-group):before{bottom:-.1875rem}.MessageList .ActionMessage:not(.first-in-group):before,.MessageList .Message:not(.first-in-group):before{top:-.1875rem}.MessageList .ActionMessage.focused:before,.MessageList .Message.focused:before{transition:none!important}.MessageList .ActionMessage.focused:before,.MessageList .ActionMessage.has-menu-open:before,.MessageList .ActionMessage.is-forwarding:before,.MessageList .ActionMessage.is-selected:before,.MessageList .Message.focused:before,.MessageList .Message.has-menu-open:before,.MessageList .Message.is-forwarding:before,.MessageList .Message.is-selected:before{opacity:.1}.MessageList>.empty{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.MessageList .ActionMessage,.MessageList .empty,.MessageList .local-action-message,.MessageList .sticky-date{text-align:center}.MessageList .ActionMessage>span,.MessageList .empty>span,.MessageList .local-action-message>span,.MessageList .sticky-date>span{display:inline-block;background:var(--pattern-color);color:#fff;font-size:.9375rem;font-weight:500;line-height:1.5rem;padding:0 .5rem;border-radius:.75rem;word-break:break-word}.MessageList .ActionMessage.rich>span,.MessageList .empty.rich>span,.MessageList .local-action-message.rich>span,.MessageList .sticky-date.rich>span{max-width:80%;text-align:left}.MessageList .ActionMessage.rich a,.MessageList .ActionMessage.rich a:visited,.MessageList .empty.rich a,.MessageList .empty.rich a:visited,.MessageList .local-action-message.rich a,.MessageList .local-action-message.rich a:visited,.MessageList .sticky-date.rich a,.MessageList .sticky-date.rich a:visited{color:var(--color-links-darker)!important}.MessageList .ActionMessage.rich a:active,.MessageList .ActionMessage.rich a:hover,.MessageList .empty.rich a:active,.MessageList .empty.rich a:hover,.MessageList .local-action-message.rich a:active,.MessageList .local-action-message.rich a:hover,.MessageList .sticky-date.rich a:active,.MessageList .sticky-date.rich a:hover{color:var(--color-links-darker-hover)!important}.MessageList .sticky-date{margin-top:1rem;margin-bottom:1rem;z-index:var(--z-sticky-date);pointer-events:none;opacity:1;transition:opacity .3s ease}body:not(.is-scrolling-messages) .MessageList .sticky-date.stuck{opacity:0}body:not(.is-scrolling-messages) .MessageList .sticky-date.stuck span{pointer-events:none}body.animation-level-0 .MessageList .sticky-date{transition:none}.MessageList .sticky-date.interactive{cursor:pointer}.MessageList .sticky-date span{pointer-events:auto}.MessageList.scrolled .sticky-date{position:sticky;top:.625rem}.has-header-tools .MessageList .sticky-date{top:3.75rem}.MessageList .ActionMessage,.MessageList .local-action-message{margin-top:.5rem;margin-bottom:.5rem}.MessageList .ActionMessage .action-link{cursor:pointer}.MessageList .ActionMessage .action-link:hover{text-decoration:underline}.MessageList .sticky-date+.ActionMessage{margin-top:-.5rem}@media (min-width:1276px){.MessageList{width:100%;transform:translateZ(0);transition:transform var(--layer-transition)}.MessageList .messages-container{width:calc(100% - var(--right-column-width))}body.animation-level-0 .MessageList{transition:none}#Main.right-column-open .MessageList{transform:translate3d(calc(var(--right-column-width)/-2),0,0)}#Main.right-column-open .MessageList:not(.select-mode-active),body.animating-right-column .MessageList:not(.select-mode-active),body:not(.animating-right-column) #Main.right-column-open .MessageList.select-mode-active{width:calc(100% - var(--right-column-width))}#Main.right-column-open .MessageList:not(.select-mode-active) .messages-container,body.animating-right-column .MessageList:not(.select-mode-active) .messages-container,body:not(.animating-right-column) #Main.right-column-open .MessageList.select-mode-active .messages-container{width:100%}}@media (max-width:600px){.MessageList{transition:transform var(--layer-transition)}body.enable-symbol-menu-transforms .MessageList{transform:translateZ(0)}body.is-symbol-menu-open .MessageList{transform:translate3d(0,calc(-1*(var(--symbol-menu-height) + var(--symbol-menu-footer-height))),0)}}.animating>div>.MessageList,.MessageList.has-focusing,.MessageList.select-mode-active,body.has-context-menu .MessageList{padding-right:0}.animating>div>.MessageList::-webkit-scrollbar,.MessageList.has-focusing::-webkit-scrollbar,.MessageList.select-mode-active::-webkit-scrollbar,body.has-context-menu .MessageList::-webkit-scrollbar{width:0}@supports (scrollbar-width:none){.animating>div>.MessageList,.MessageList.has-focusing,.MessageList.select-mode-active,body.has-context-menu .MessageList{padding-right:.6875rem;scrollbar-width:none}}.is-safari.has-context-menu .messages-layout .MessageList,.is-safari .MessageList.has-focusing,.is-safari .MessageList.select-mode-active{padding-right:.375rem}.ScrollDownButton{--base-bottom-pos:6rem;position:absolute;bottom:var(--base-bottom-pos);right:1rem;opacity:0;transform:translateY(4.5rem);transition:transform .25s cubic-bezier(.34,1.56,.64,1),opacity .2s ease;z-index:10;pointer-events:none}body.animation-level-0 .ScrollDownButton{transform:none!important;transition:opacity .15s}@media (max-width:600px){.ScrollDownButton{right:.5rem;bottom:4.5rem}}.ScrollDownButton-inner{display:flex;flex-direction:column;align-items:center}.ScrollDownButton-inner>.Button{box-shadow:0 1px 2px var(--color-default-shadow)}.ScrollDownButton-inner>.Button i{font-size:1.75rem}@media (min-width:1276px){.ScrollDownButton-inner{transform:translateX(0);transition:transform var(--layer-transition)}body.animation-level-0 .ScrollDownButton-inner{transition:none!important}#Main.right-column-open .ScrollDownButton-inner{transform:translateX(calc(-1*var(--right-column-width)))}}@media (max-width:600px){.ScrollDownButton-inner>.Button{width:2.875rem;height:2.875rem}}.ScrollDownButton.revealed{transform:translateY(0);opacity:1;pointer-events:all}.ScrollDownButton.revealed.no-composer{transform:translateY(2.5rem)}.ScrollDownButton .unread-count{min-width:1.5rem;height:1.5rem;padding:0 .45rem;border-radius:.75rem;font-size:.875rem;line-height:1.5rem;font-weight:500;text-align:center;position:absolute;top:-.3rem;right:-.3rem;background:var(--color-green);color:#fff;pointer-events:none}@media (max-width:600px){.ScrollDownButton .unread-count{top:-.7rem;right:auto}}@media (max-width:600px){body.is-symbol-menu-open .ScrollDownButton{bottom:calc(var(--base-bottom-pos) + var(--symbol-menu-height) + var(--symbol-menu-footer-height))}}.ComposerEmbeddedMessage{height:2.625rem;transition:height .15s ease-out,opacity .15s ease-out}.ComposerEmbeddedMessage:not(.open){height:0!important}.ComposerEmbeddedMessage body.animation-level-0{transition:none!important}.ComposerEmbeddedMessage>div{display:flex;align-items:center;padding-right:.625rem;padding-top:.45rem}.ComposerEmbeddedMessage>div>.Button{flex-shrink:0;background:none!important;width:2.125rem;height:2.125rem;margin:0 .625rem;padding:0;align-self:center}.WebPagePreview{height:2.625rem;transition:height .15s ease-out,opacity .15s ease-out;--accent-color:var(--color-primary)}.WebPagePreview:not(.open){height:0!important}.WebPagePreview>div{display:flex;align-items:center;padding-right:.625rem;padding-top:.45rem}.ComposerEmbeddedMessage+.WebPagePreview{margin-top:.75rem}.WebPagePreview>div>.Button{flex-shrink:0;background:none!important;width:2.125rem;height:2.125rem;margin:0 .625rem;padding:0;align-self:center}.WebPagePreview .WebPage{flex-grow:1;margin:.1875rem 0 .1875rem .125rem;max-width:calc(100% - 3.375rem)}.WebPagePreview .WebPage:before{top:.1rem;bottom:.05rem}.WebPagePreview .WebPage .site-description,.WebPagePreview .WebPage .site-title{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:0}@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>.Button{flex-shrink:0;margin-left:.5rem}@media (max-width:600px){.Composer>.Button{width:2.875rem;height:2.875rem}}.Composer>.Button .icon-check,.Composer>.Button .icon-microphone-alt,.Composer>.Button .icon-send{position:absolute}.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-check,.Composer>.Button:not(:active):not(:focus):not(:hover) .icon-send{color:var(--color-primary)}.Composer>.Button.cancel{position:relative;z-index:1}.Composer>.Button.cancel.active,.Composer>.Button.cancel:hover{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-check,.Composer>.Button.send .icon-microphone-alt{animation:hide-icon .4s ease-out forwards}.Composer>.Button.record .icon-microphone-alt{animation:grow-icon .4s ease-out}.Composer>.Button.edit .icon-microphone-alt,.Composer>.Button.edit .icon-send,.Composer>.Button.record .icon-check,.Composer>.Button.record .icon-send{animation:hide-icon .4s ease-out forwards}.Composer>.Button.edit .icon-check{animation:grow-icon .4s ease-out}body.animation-level-0 .Composer>.Button .icon-check,body.animation-level-0 .Composer>.Button .icon-microphone-alt,body.animation-level-0 .Composer>.Button .icon-send,body.animation-level-1 .Composer>.Button .icon-check,body.animation-level-1 .Composer>.Button .icon-microphone-alt,body.animation-level-1 .Composer>.Button .icon-send{animation-duration:0ms!important}.Composer .mobile-symbol-menu-button{width:2.875rem;height:2.875rem;position:relative}.Composer .mobile-symbol-menu-button .icon-keyboard,.Composer .mobile-symbol-menu-button .icon-smile,.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 ease-out forwards}.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 ease-out forwards}.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 ease-out forwards}#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:-.1875rem;right:-.551rem;width:.5625rem;height:1.25rem;transition:opacity .2s}#message-compose .svg-appendix .corner{fill:var(--color-background)}@media (max-width:600px){#message-compose{max-width:calc(100% - 3rem)}}.message-input-wrapper{display:flex}.message-input-wrapper>.Button{flex-shrink:0;background:none!important;width:3.375rem;height:3.375rem;margin:0;padding:.625rem;align-self:flex-end}@media (max-width:600px){.message-input-wrapper>.Button{width:2.875rem;height:2.875rem;margin:0 .25rem}}.message-input-wrapper>.Button+.Button{margin-left:-.25rem}.message-input-wrapper>.Button.scheduled-button i:after{content:"";position:absolute;top:.75rem;right:.75rem;border:.1875rem solid var(--color-background);box-sizing:initial;width:.5rem;height:.5rem;border-radius:50%;background:var(--color-green-darker);box-shadow:-.375rem -.25rem 0 -.1875rem var(--color-background)}@media (max-width:600px){.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}.message-input-wrapper .recording-state:after{content:"";width:10px;height:10px;background:var(--color-error);border-radius:5px;position:absolute;top:50%;margin-top:-5px;right:1.375rem}@media (max-width:600px){.message-input-wrapper .recording-state{height:2.875rem;line-height:2.875rem}}#caption-input-text,#message-input-text{position:relative}#caption-input-text .form-control,#message-input-text .form-control{padding-top:calc(1rem - var(--border-width));padding-bottom:calc(1rem - var(--border-width));overflow:hidden;line-height:1.375rem;font-family:Roboto,-apple-system,Apple Color Emoji,Helvetica Neue,sans-serif;unicode-bidi:plaintext;text-align:initial}#caption-input-text .form-control.overflown,#message-input-text .form-control.overflown{overflow-y:auto;overflow-x:hidden}#caption-input-text .form-control.touched+.placeholder-text,#caption-input-text .form-control:focus+.placeholder-text,#message-input-text .form-control.touched+.placeholder-text,#message-input-text .form-control:focus+.placeholder-text{display:none}#caption-input-text .form-control.focus-disabled,#message-input-text .form-control.focus-disabled{pointer-events:none}#caption-input-text .placeholder-text,#message-input-text .placeholder-text{position:absolute;bottom:.9375rem;color:var(--color-placeholders);pointer-events:none;unicode-bidi:plaintext;text-align:initial}@media (max-width:600px){#caption-input-text .placeholder-text,#message-input-text .placeholder-text{bottom:.6875rem}}#caption-input-text[dir=rtl] .placeholder-text,#message-input-text[dir=rtl] .placeholder-text{right:0}#caption-input-text .text-entity-link,#message-input-text .text-entity-link{color:var(--color-links)!important;cursor:default;text-decoration:none}#caption-input-text .text-entity-link:active,#caption-input-text .text-entity-link:hover,#caption-input-text .text-entity-link:visited,#message-input-text .text-entity-link:active,#message-input-text .text-entity-link:hover,#message-input-text .text-entity-link:visited{color:var(--color-links-hover)!important}#caption-input-text .clone,#message-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-top:calc(1.15625rem - var(--border-width));padding-bottom:calc(1.15625rem - var(--border-width));transition:height .1s ease}@media (max-width:600px){#message-input-text .form-control{height:2.875rem;min-height:2.875rem;max-height:16rem;padding-top:calc(.84375rem - var(--border-width));padding-bottom:calc(.84375rem - var(--border-width))}}body.animation-level-0 #message-input-text .form-control{transition:none!important}#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:.90625rem}.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;overflow-y:overlay;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)}.composer-tooltip:not(.shown){display:none}.composer-tooltip.open{opacity:1;transform:translateY(0)}.composer-tooltip .Loading{margin:1rem 0}#middle-column-bg{position:absolute;top:0;left:0;bottom:0;right:0;overflow:hidden;z-index:-1}#middle-column-bg:after,#middle-column-bg:before{content:"";display:block;position:absolute;top:0;left:0;bottom:0;right:0;background-color:var(--theme-background-color)}#middle-column-bg:after{background-position:50%;background-repeat:no-repeat;background-size:cover}.theme-light #middle-column-bg:after{background-image:url(chat-bg.f607e788298d8a7de37a3b39b76c1efa.jpg)}@media (max-width:600px){.theme-light #middle-column-bg:after{background-image:url(chat-bg-mobile.3ebe59c803c10092f2233e6e00ab2492.jpg)}}body:not(.animation-level-0) #root #middle-column-bg:after{transition:transform var(--layer-transition),opacity .2s!important}body.animation-level-0 #middle-column-bg:after{transition:none}.custom-bg-color>#middle-column-bg:before{filter:blur(0);transform:scale(1.1)}.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:blur(0);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,body.animation-level-2 #middle-column-bg:before{margin:-16rem -5rem -20rem 0;overflow:hidden;transform:scale(1);transform-origin:left center;transition:transform var(--layer-transition)}body.animation-level-2 .custom-bg-image>#middle-column-bg:after{margin:-16rem -5rem -20rem -1rem;transition:transform var(--layer-transition)}body.animation-level-2 #Main.right-column-open :not(.custom-bg-image)>#middle-column-bg:after{transform:scale(.67)}}#MiddleColumn{display:flex;justify-content:center;height:100%;position:relative;z-index:1}@media (max-width:600px){#MiddleColumn{overflow:hidden}}#MiddleColumn .messages-layout{display:flex;flex-direction:column;align-items:center;position:relative}#MiddleColumn .messages-layout,#MiddleColumn .messages-layout>.Transition{width:100%;height:100%;overflow:hidden}#MiddleColumn .messages-layout>.Transition>div{display:flex;flex-direction:column;align-items:center}#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 .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)}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(.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,body.animation-level-0 #MiddleColumn .messaging-disabled .messaging-disabled-inner span{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 .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:translateZ(0);transition: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:before{content:"";position:absolute;top:-.5rem;left:0;right:0;height:1px;background:linear-gradient(90deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.4) 2%,hsla(0,0%,100%,.4) 98%,hsla(0,0%,100%,0));opacity:0;transition:opacity .35s 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,hsla(0,0%,49.8%,0),hsla(0,0%,49.8%,.4) 2%,hsla(0,0%,49.8%,.4) 98%,hsla(0,0%,49.8%,0))}.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:1.25rem}@media (max-width:600px){.Composer,.MessageSelectToolbar,.messaging-disabled{margin-bottom:.5rem}}.Composer,.MessageSelectToolbar,.messaging-disabled,.unpin-all-button{width:100%;display:flex;justify-content:center;position:relative}.mask-image-disabled .MessageSelectToolbar-inner,.mask-image-disabled .messaging-disabled,.mask-image-disabled .unpin-all-button{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow)}.unpin-button-container{width:100%;display:flex;justify-content:center;position:absolute;padding-bottom:1.25rem}.unpin-button-container .unpin-all-button{text-transform:capitalize;color:var(--color-black);height:3.5rem;overflow:visible;transform:scaleX(1);transition:transform var(--select-transition),background-color .15s,color .15s}.unpin-button-container .unpin-all-button:hover .icon-unpin{color:var(--color-white)}.select-mode-active+.middle-column-footer .unpin-button-container .unpin-all-button{box-shadow:none;transform:scaleX(var(--unpin-hidden-scale))}@media (max-width:600px){.unpin-button-container .unpin-all-button{height:2.5rem}}.unpin-button-container .unpin-all-button .icon-unpin{margin-inline-start:-.4375rem;margin-inline-end:.75rem;color:var(--color-text-secondary);font-size:1.5rem;transition:color .15s}@media (max-width:600px){.unpin-button-container{padding-bottom:.75rem}}.mask-image-disabled .unpin-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}.ProfilePhoto{width:100%;height:100%;cursor:pointer;position:relative}.ProfilePhoto img{width:100%;object-fit:cover}.ProfilePhoto .prev-avatar-media{position:absolute;left:0;top:0;z-index:-1}.ProfilePhoto .spinner-wrapper{width:100%;height:100%}.ProfilePhoto.deleted-account,.ProfilePhoto.no-photo,.ProfilePhoto.saved-messages,.ProfilePhoto .spinner-wrapper{display:flex;align-items:center;justify-content:center;color:var(--color-white);background:linear-gradient(var(--color-white) -125%,var(--color-user));cursor:default}.ProfilePhoto.no-photo{font-size:14rem}.ProfilePhoto.deleted-account,.ProfilePhoto.saved-messages{font-size:20rem}.ProfileInfo{aspect-ratio:1/1;position:relative}@supports not (aspect-ratio:1/1){.ProfileInfo:before{float:left;padding-top:100%;content:""}.ProfileInfo:after{display:block;content:"";clear:both}}.ProfileInfo .photo-wrapper{width:100%;position:absolute;left:0;top:0;bottom:0}.ProfileInfo .photo-wrapper>.Transition{width:100%;height:100%}.ProfileInfo .photo-dashes{position:absolute;width:100%;height:.125rem;padding:0 .375rem;z-index:1;display:flex;top:.5rem;left:0}.ProfileInfo .photo-dash{flex:1 1 auto;background-color:var(--color-white);opacity:.5;border-radius:.125rem;margin:0 .125rem}.ProfileInfo .photo-dash.current{opacity:1}.ProfileInfo .navigation{position:absolute;top:0;bottom:0;width:25%;border:none;padding:0;margin:0;-webkit-appearance:none;appearance:none;background:transparent no-repeat;background-size:1.25rem;opacity:.25;transition:opacity .15s;outline:none;cursor:pointer;z-index:1}.is-touch-env .ProfileInfo .navigation,.ProfileInfo .navigation:hover{opacity:1}.ProfileInfo .navigation.prev{left:0;background-image:url(media_navigation_previous.11f3cfece8fead5a78e6349db2545210.svg);background-position:1.25rem 50%}.ProfileInfo .navigation.next{right:0;background-image:url(media_navigation_next.3d6e264d21e73ad725738beb8e9dbbb8.svg);background-position:calc(100% - 1.25rem) 50%}.ProfileInfo .info{position:absolute;bottom:0;left:0;width:100%;min-height:100px;padding:0 1.5rem .5rem;background:linear-gradient(0deg,rgba(0,0,0,.5),transparent);color:var(--color-white);display:flex;flex-direction:column;justify-content:flex-end}.ProfileInfo .info:dir(rtl) .status{text-align:initial;unicode-bidi:plaintext}.ProfileInfo .info[dir=rtl] .status{text-align:initial;unicode-bidi:plaintext}.ProfileInfo .title{display:flex;align-items:center}.ProfileInfo .title h3{font-weight:500;font-size:1.25rem;line-height:1.375rem;white-space:pre-wrap;word-break:break-word;margin-bottom:.25rem}.ProfileInfo .title .VerifiedIcon{margin-left:.25rem;margin-top:-.125rem}.ProfileInfo .title .emoji{width:1.5rem;height:1.5rem;background-size:1.5rem}.ProfileInfo .status{font-size:.875rem;opacity:.5}.ProfileInfo[dir=rtl] .navigation.prev{left:auto;right:0;transform:scaleX(-1)}.ProfileInfo[dir=rtl] .navigation.next{left:0;right:auto;transform:scaleX(-1)}.Profile{height:100%;overflow-y:scroll;overflow-x:hidden}@supports (overflow-y:overlay){.Profile{overflow-y:overlay!important}}.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 -.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}.shared-media{display:flex;flex-direction:column-reverse}.shared-media .TabList{background:var(--color-background);top:-1px}.shared-media .TabList .Tab{padding:1rem .25rem}.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 .message-upload-progress,.shared-media .content.links-list .ProgressSpinner{display:none}.shared-media .content.audio-list{padding:1.25rem}.shared-media .content.audio-list .Audio .media-loading{top:0;left:0;display:flex;align-items:center;justify-content:center}.shared-media .content.audio-list .Audio+.Audio{margin-top:1.6875rem}.shared-media .content.members-list{padding:.5rem 1rem}@media (max-width:600px){.shared-media .content.members-list{padding:.5rem 0}}#RightColumn{position:absolute;top:0;right:0;width:var(--right-column-width);height:100%;transform:translate3d(var(--right-column-width),0,0);background:var(--color-background);border-left:1px solid var(--color-borders);z-index:var(--z-right-column);transition:transform var(--layer-transition)}body.animation-level-0 #RightColumn{transition:none}#RightColumn:not(:hover) .chat-item-clickable:nth-child(n+18){display:none!important}@media (max-width:1275px){#RightColumn{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow);border-left:none}}@media (max-width:600px){#RightColumn{width:100vw;transform:translate3d(110vw,0,0)}}#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:translateZ(0)}#Main{display:flex;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)}}#LeftColumn{flex:1;min-width:18rem;max-width:26.5rem;height:100%}@media (max-width:600px){#LeftColumn{height:calc(var(--vh, 1vh)*100)}}@media (min-width:1680px){#LeftColumn{border-left:1px solid var(--color-borders)}}@media (max-width:1275px){#LeftColumn{flex:2}}@media (max-width:925px){#LeftColumn{position:fixed;left:0;top:0;height:calc(var(--vh, 1vh)*100);width:26.5rem;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:translateZ(0)}#Main:not(.middle-column-open) #LeftColumn:after{opacity:0;pointer-events:none}#Main.middle-column-open #LeftColumn .custom-scroll{overflow:hidden}}@media (max-width:600px){#LeftColumn{max-width:none;width:100vw;transform:translate3d(-20vw,0,0)}}@media (min-width:1680px){#RightColumn{border-right:1px solid var(--color-borders)}}@media (max-width:600px){#RightColumn{height:calc(var(--vh, 1vh)*100 + 1px)}}#MiddleColumn{flex:3;border-left:1px solid var(--color-borders);max-width:75vw}@media (max-width:1275px){#MiddleColumn{max-width:calc(100vw - 26.5rem)}}@media (max-width:66.25rem){#MiddleColumn{max-width:60vw}}@media (min-width:1680px){#MiddleColumn{border-right:1px solid var(--color-borders);max-width:calc(1680px - 26.5rem)}}@media (max-width:925px){#MiddleColumn{max-width:none;position:fixed;left:0;top:0;bottom:0;right:0;transform:translateZ(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)}}@media (max-width:600px){.SymbolMenu{transition:transform var(--layer-transition)}body.animation-level-0 .SymbolMenu{transition:none}body:not(.is-middle-column-open) .SymbolMenu{transform:translate3d(100vw,0,0)!important}} \ No newline at end of file diff --git a/dist/4.75225d931a1e76f26855.js b/dist/4.75225d931a1e76f26855.js new file mode 100644 index 00000000..7762820c --- /dev/null +++ b/dist/4.75225d931a1e76f26855.js @@ -0,0 +1,2 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{104:function(e,t,a){"use strict";a.r(t),a.d(t,"Main",(function(){return Tn}));var s=a(2),n=a(1),c=a(0),r=(a(84),a(37)),o=a(6);window.addEventListener("popstate",e=>{if(!e.state)return;const{chatId:t,threadId:a,messageListType:n}=e.state;Object(s.d)().openChat({id:t,threadId:a,type:n,noPushState:!0})}),Object(s.b)("openChat",(e,t,a)=>{const{id:n,threadId:c=-1,type:i="thread",noPushState:l}=a,d=Object(o.y)(e);return d&&d.chatId===n&&d.threadId===c&&d.type===i||(e=Object(r.n)(e),e={...e,messages:{...e.messages,contentToBeScheduled:void 0},...n!==e.forwardMessages.toChatId&&{forwardMessages:{}}},Object(s.g)(e),l||window.history.pushState({chatId:n,threadId:c,messageListType:i},"")),Object(r.N)(e,n,c,i)}),Object(s.b)("openChatWithInfo",(e,t,a)=>{Object(s.g)({...e,isChatInfoShown:!0}),t.openChat(a)}),Object(s.b)("resetChatCreation",e=>({...e,chatCreation:void 0}));var i=a(5),l=a(20),d=a(3);let b;Object(s.b)("setScrollOffset",(e,t,a)=>{const{chatId:s,threadId:n,scrollOffset:c}=a;return Object(r.x)(e,s,n,"scrollOffset",c)}),Object(s.b)("setReplyingToId",(e,t,a)=>{const{messageId:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c,threadId:i}=n;return Object(r.x)(e,c,i,"replyingToId",s)}),Object(s.b)("setEditingId",(e,t,a)=>{const{messageId:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c,threadId:i,type:l}=n,d="scheduled"===l?"editingScheduledId":"editingId";return Object(r.x)(e,c,i,d,s)}),Object(s.b)("editLastMessage",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(!t||!a)return;const s=Object(o.m)(e,t),n=Object(o.Hb)(e,t,a);if(!s||!n)return;const c=Object(d.g)(n,t=>Boolean(s[t]&&Object(o.b)(e,s[t],a).canEdit));return c?Object(r.x)(e,t,a,"editingId",c):void 0}),Object(s.b)("replyToNextMessage",(e,t,a)=>{const{targetIndexDelta:s}=a,{chatId:n,threadId:c}=Object(o.y)(e)||{};if(!n||!c)return;const r=Object(o.m)(e,n),l=Object(o.Hb)(e,n,c);if(!r||!l)return;const d=Object(o.mb)(e,n,c);let b;if(Object(o.X)(e,n,c)&&d){const e=Object.keys(r),t=e.indexOf(d.toString())+s;b=t<=e.length+1&&t>=0?Number(e[t]):void 0}else if(c===i.MAIN_THREAD_ID){const t=Object(o.f)(e,n);b=t&&t.lastMessage?t.lastMessage.id:void 0}else{const t=Object(o.Cb)(e,n,c);b=t?t.lastMessageId:void 0}t.setReplyingToId({messageId:b}),t.focusMessage({chatId:n,threadId:c,messageId:b})}),Object(s.b)("openMediaViewer",(e,t,a)=>{const{chatId:s,threadId:n,messageId:c,avatarOwnerId:r,profilePhotoIndex:o,origin:i}=a;return{...e,mediaViewer:{chatId:s,threadId:n,messageId:c,avatarOwnerId:r,profilePhotoIndex:o,origin:i},forwardMessages:{}}}),Object(s.b)("closeMediaViewer",e=>({...e,mediaViewer:{}})),Object(s.b)("openAudioPlayer",(e,t,a)=>{const{chatId:s,threadId:n,messageId:c}=a;return{...e,audioPlayer:{chatId:s,threadId:n,messageId:c}}}),Object(s.b)("closeAudioPlayer",e=>({...e,audioPlayer:{}})),Object(s.b)("openPollResults",(e,t,a)=>{const{chatId:n,messageId:c}=a;Object(o.W)(e)?n===e.pollResults.chatId&&c===e.pollResults.messageId||Object(s.g)({...e,pollResults:{chatId:n,messageId:c,voters:{}}}):window.setTimeout(()=>{const e=Object(s.e)();Object(s.g)({...e,pollResults:{chatId:n,messageId:c,voters:{}}})},450)}),Object(s.b)("closePollResults",e=>{Object(s.g)({...e,pollResults:{}})}),Object(s.b)("focusLastMessage",(e,t)=>{const a=Object(o.y)(e);if(!a)return;const{chatId:s,threadId:n}=a;let c;if(n===i.MAIN_THREAD_ID){const t=Object(o.f)(e,s);c=t&&t.lastMessage?t.lastMessage.id:void 0}else{const t=Object(o.Cb)(e,s,n);c=t?t.lastMessageId:void 0}c&&t.focusMessage({chatId:s,threadId:n,messageId:c,noHighlight:!0})}),Object(s.b)("focusMessage",(e,t,a)=>{const{chatId:n,threadId:c=i.MAIN_THREAD_ID,messageListType:d="thread",noHighlight:u,groupedId:m,groupedChatId:h}=a;let{messageId:O}=a;if(void 0!==m){const t=Object(o.J)(e,h,m);t&&t.length&&([O]=t)}const j=Object(o.y)(e),g=!j||n!==j.chatId||c!==j.threadId||d!==j.type;b&&(clearTimeout(b),b=void 0),b=window.setTimeout(()=>{let e=Object(s.e)();e=Object(r.P)(e),e=Object(r.O)(e),Object(s.g)(e)},2e3),e=Object(r.P)(e,n,O,u),e=Object(r.O)(e,void 0),g&&(e=Object(r.O)(e,l.b.Static));const f=Object(o.Hb)(e,n,c);if(f&&f.includes(O))return Object(s.g)(e),void t.openChat({id:n,threadId:c});if(g&&(e=Object(r.x)(e,n,c,"viewportIds",void 0)),e=Object(r.x)(e,n,c,"outlyingIds",void 0),f&&!g){const t=O>f[0]?l.b.Down:l.b.Up;e=Object(r.O)(e,t)}Object(s.g)(e),t.openChat({id:n,threadId:c}),t.loadViewportMessages()}),Object(s.b)("openForwardMenu",(e,t,a)=>{const{fromChatId:s,messageIds:n,groupedId:c}=a;let r;return c&&(r=Object(o.ab)(e,s,c)),{...e,forwardMessages:{fromChatId:s,messageIds:r||n,isModalShown:!0}}}),Object(s.b)("exitForwardMode",e=>{Object(s.g)({...e,forwardMessages:{}})}),Object(s.b)("setForwardChatId",(e,t,a)=>{const{id:n}=a;Object(s.g)({...e,forwardMessages:{...e.forwardMessages,toChatId:n,isModalShown:!1}}),t.openChat({id:n}),t.closeMediaViewer(),t.exitMessageSelectMode()}),Object(s.b)("openForwardMenuForSelectedMessages",(e,t)=>{if(!e.selectedMessages)return;const{chatId:a,messageIds:s}=e.selectedMessages;t.openForwardMenu({fromChatId:a,messageIds:s})}),Object(s.b)("enterMessageSelectMode",(e,t,a)=>{const{messageId:s}=a||{},n=Object(o.r)(e);return n?Object(r.m)(e,n.id,s):e}),Object(s.b)("toggleMessageSelection",(e,t,a)=>{const{messageId:s,groupedId:n,childMessageIds:c,withShift:i}=a,l=Object(o.y)(e);if(!l)return;const{chatId:d,threadId:b,type:u}=l;return Object(r.G)(e,d,b,u,s,n,c,i)}),Object(s.b)("exitMessageSelectMode",r.n),Object(s.b)("openPollModal",e=>({...e,isPollModalOpen:!0})),Object(s.b)("closePollModal",e=>({...e,isPollModalOpen:!1}));Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{query:s}=a,{chatId:n}=e.globalSearch;return Object(r.R)(e,{globalResults:{},localResults:{},resultsByType:void 0,...s?{fetchingStatus:{chats:!n,messages:!0}}:{fetchingStatus:void 0},query:s})}),Object(s.b)("addRecentlyFoundChatId",(e,t,a)=>{const{id:s}=a,{recentlyFoundChatIds:n}=e.globalSearch;if(!n)return Object(r.R)(e,{recentlyFoundChatIds:[s]});const c=n.filter(e=>e!==s);return c.unshift(s),c.length>10&&c.pop(),Object(r.R)(e,{recentlyFoundChatIds:c})}),Object(s.b)("clearRecentlyFoundChats",e=>Object(r.R)(e,{recentlyFoundChatIds:void 0})),Object(s.b)("setGlobalSearchContent",(e,t,a)=>{const{content:s}=a;return Object(r.S)(e,s)}),Object(s.b)("setGlobalSearchChatId",(e,t,a)=>{const{id:s}=a;return Object(r.R)(e,{chatId:s,query:void 0,resultsByType:void 0})});var u=a(50),m=a(4);Object(s.b)("openLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return Object(r.Y)(e,t,a,!0)}),Object(s.b)("closeLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return e=Object(r.Y)(e,t,a,!1),e=Object(r.t)(e,t,a,void 0)}),Object(s.b)("setLocalTextSearchQuery",(e,t,a)=>{const{chatId:s,threadId:n}=Object(o.y)(e)||{};if(!s||!n)return;const{query:c}=a,i=Object(m.a)(s,n),{query:l}=e.localTextSearch.byChatThreadKey[i]||{};return c!==l&&(e=Object(r.t)(e,s,n,u.a)),e=Object(r.Y)(e,s,n,!0,c)}),Object(s.b)("setLocalMediaSearchType",(e,t,a)=>{const{chatId:s}=Object(o.y)(e)||{};if(!s)return;const{mediaType:n}=a;return Object(r.X)(e,s,n)}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,stickers:{...e.stickers,search:{query:s,resultIds:void 0}}}}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,gifs:{...e.gifs,search:{query:s,offsetId:void 0,results:void 0}}}}),Object(s.b)("openUserInfo",(e,t,a)=>{const{id:s}=a;t.openChat({id:s})});Object(s.b)("openChat",e=>Object(r.fb)(e,void 0)),Object(s.b)("setSettingOption",(e,t,a)=>Object(r.v)(e,a)),Object(s.b)("setThemeSettings",(e,t,a)=>{const{theme:s,...n}=a;return Object(r.w)(e,s,n)});var h=a(7),O=a(169);Object(s.b)("toggleChatInfo",e=>({...e,isChatInfoShown:!e.isChatInfoShown})),Object(s.b)("toggleManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}}),Object(s.b)("closeManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}}),Object(s.b)("openChat",(e,t,a)=>{if(!h.g)return;const{id:s}=a;return{...e,isLeftColumnShown:void 0===s}}),Object(s.b)("toggleLeftColumn",e=>({...e,isLeftColumnShown:!e.isLeftColumnShown})),Object(s.b)("addRecentEmoji",(e,t,a)=>{const{emoji:s}=a,{recentEmojis:n}=e;if(!n)return{...e,recentEmojis:[s]};const c=n.filter(e=>e!==s);return c.unshift(s),c.length>18&&c.pop(),{...e,recentEmojis:c}}),Object(s.b)("addRecentSticker",(e,t,a)=>{const{sticker:s}=a,{recent:n}=e.stickers;if(!n)return{...e,stickers:{...e.stickers,recent:{hash:0,stickers:[s]}}};const c=n.stickers.filter(e=>e.id!==s.id);return c.unshift(s),{...e,stickers:{...e.stickers,recent:{...n,stickers:c}}}}),Object(s.b)("showNotification",(e,t,a)=>{const s=a,n=[...e.notifications],c=n.findIndex(e=>e.message===s.message);return-1!==c&&n.splice(c,1),n.push(s),{...e,notifications:n}}),Object(s.b)("dismissNotification",e=>{const t=[...e.notifications];return t.pop(),{...e,notifications:t}}),Object(s.b)("showError",(e,t,a)=>{const{error:s}=a;if(!Object(O.a)(s))return e;const n=[...e.errors],c=n.findIndex(e=>e.message===s.message);return-1!==c&&n.splice(c,1),n.push(s),{...e,errors:n}}),Object(s.b)("dismissError",e=>{const t=[...e.errors];return t.pop(),{...e,errors:t}}),Object(s.b)("toggleSafeLinkModal",(e,t,a)=>{const{url:s}=a;return{...e,safeLinkModalUrl:s}}),Object(s.b)("openHistoryCalendar",(e,t,a)=>{const{selectedAt:s}=a;return{...e,historyCalendarSelectedAt:s}}),Object(s.b)("closeHistoryCalendar",e=>({...e,historyCalendarSelectedAt:void 0})),Object(s.b)("openPaymentModal",(e,t,a)=>{const{messageId:s}=a;return{...e,payment:{...e.payment,messageId:s,isPaymentModalOpen:!0}}}),Object(s.b)("closePaymentModal",e=>{const t=Object(r.h)(e);return Object(r.i)(t)});a(85);var j=a(10),g=a(9);const f=Object(g.g)(e=>e(),1e3,!0),p=Object(g.g)(e=>e(),3e3,!0),I=Object(g.a)(e=>e(),500,!1,!0);async function v(e,t,a){const c=await Object(j.a)("fetchChats",{limit:n.j,offsetDate:a,archived:"archived"===e,withPinned:void 0===Object(s.e)().chats.orderedPinnedIds[e]});if(!c)return;const{chatIds:o}=c;o.length>0&&o[0]===t&&o.shift();let l=Object(s.e)();l=Object(r.f)(l,Object(d.c)(c.users,"id")),l=Object(r.M)(l,Object(d.c)(c.chats,"id")),l=Object(r.I)(l,e,o),l=Object(r.J)(l,e,c),Object.keys(c.draftsById).map(Number).forEach(e=>{l=Object(r.x)(l,e,i.MAIN_THREAD_ID,"draft",c.draftsById[e])}),Object.keys(c.replyingToById).map(Number).forEach(e=>{l=Object(r.x)(l,e,i.MAIN_THREAD_ID,"replyingToId",c.replyingToById[e])}),0!==o.length||l.chats.isFullyLoaded[e]||(l={...l,chats:{...l.chats,isFullyLoaded:{...l.chats.isFullyLoaded,[e]:!0}}}),Object(s.g)(l)}async function y(e){const t=await Object(j.a)("fetchFullChat",e);if(!t)return;const{users:a,fullInfo:n}=t;let c=Object(s.e)();a&&(c=Object(r.f)(c,Object(d.c)(a,"id"))),c=Object(r.H)(c,e.id,{fullInfo:n}),Object(s.g)(c)}async function C(e,t,a){const n=Object(s.e)(),c=Object(o.h)(n,t);if(c&&!c.isMin)return void(a?e.focusMessage({chatId:c.id,messageId:a}):e.openChat({id:c.id}));const i=Object(o.r)(n);e.openChat({id:-1});const l=await Object(j.a)("getChatByUsername",t);if(!l)return i&&e.openChat({id:i.id}),void e.showNotification({message:"User does not exist"});Object(s.g)(Object(r.H)(Object(s.e)(),l.id,l)),a?e.focusMessage({chatId:l.id,messageId:a}):e.openChat({id:l.id})}Object(s.b)("preloadTopChatMessages",(e,t)=>{(async()=>{const a=[];for(let c=0;ce!==l&&!a.includes(e));if(!u)return;a.push(u.id),t.loadViewportMessages({chatId:u.id,threadId:i.MAIN_THREAD_ID})}})()}),Object(s.b)("openChat",(e,t,a)=>{const{id:s,threadId:n}=a,{currentUserId:c}=e,r=Object(o.f)(e,s);if(r&&r.hasUnreadMark&&t.toggleChatUnread({id:s}),r)Object(m.mb)(r)&&!r.isMin&&t.requestChatUpdate({chatId:s});else if(s===c)Object(j.a)("fetchChat",{type:"self"});else{const t=Object(o.Gb)(e,s);t&&Object(j.a)("fetchChat",{type:"user",user:t})}if(n!==i.MAIN_THREAD_ID){Object(o.Eb)(e,s,n)||t.requestThreadInfoUpdate({chatId:s,threadId:n})}}),Object(s.b)("openSupportChat",(e,t)=>{const a=Object(o.Ab)(e);t.openChat({id:a?a.id:-1}),a||(async()=>{const e=await Object(j.a)("fetchChat",{type:"support"});e&&t.openChat({id:e.chatId})})()}),Object(s.b)("openTipsChat",(e,t)=>{t.openChatByUsername({username:n.Cb})}),Object(s.b)("loadMoreChats",(e,t,a)=>{const{listType:s="active"}=a,n=e.chats.listIds[s];if(e.chats.isFullyLoaded[s])return;const c=n?n.map(t=>e.chats.byId[t]).filter(t=>Boolean(t&&t.lastMessage)&&!Object(o.N)(e,t.id)).sort((e,t)=>e.lastMessage.date-t.lastMessage.date)[0]:void 0;f(c?()=>v(s,c.id,c.lastMessage.date):()=>v(s))}),Object(s.b)("loadFullChat",(e,t,a)=>{const{chatId:s,force:n}=a,c=Object(o.f)(e,s);c&&(n?y(c):I(()=>y(c)))}),Object(s.b)("loadTopChats",()=>{p(()=>v("active"))}),Object(s.b)("requestChatUpdate",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);n&&Object(j.a)("requestChatUpdate",n)}),Object(s.b)("updateChatMutedState",(e,t,a)=>{const{chatId:s,isMuted:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("updateChatMutedState",{chat:c,isMuted:n})}),Object(s.b)("createChannel",(e,t,a)=>{const{title:n,about:c,photo:i,memberIds:d}=a;!async function(e,t,a,n){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const c=await Object(j.a)("createChannel",{title:e,about:a,users:t});if(!c)return;const{id:o,accessHash:i}=c;let d=Object(s.e)();d=Object(r.H)(d,o,c),d={...d,chatCreation:{...d.chatCreation,progress:c?l.a.Complete:l.a.Error}},Object(s.g)(d),Object(s.d)().openChat({id:o}),o&&i&&n&&await Object(j.a)("editChatPhoto",{chatId:o,accessHash:i,photo:n})}(n,d.map(t=>Object(o.Gb)(e,t)).filter(Boolean),c,i)}),Object(s.b)("joinChannel",(e,t,a)=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&Object(j.a)("joinChannel",{channelId:c,accessHash:r})}),Object(s.b)("leaveChannel",(e,t,a)=>{(async()=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&await Object(j.a)("leaveChannel",{channelId:c,accessHash:r}),t.openChat({id:void 0})})()}),Object(s.b)("deleteChannel",(e,t,a)=>{(async()=>{const{chatId:s}=a,n=Object(o.f)(e,s);if(!n)return;const{id:c,accessHash:r}=n;c&&r&&await Object(j.a)("deleteChannel",{channelId:c,accessHash:r}),t.openChat({id:void 0})})()}),Object(s.b)("createGroupChat",(e,t,a)=>{const{title:n,memberIds:c,photo:i}=a;!async function(e,t,a){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const n=await Object(j.a)("createGroupChat",{title:e,users:t});if(!n)return;const{id:c}=n;let o=Object(s.e)();o=Object(r.H)(o,c,n),o={...o,chatCreation:{...o.chatCreation,progress:n?l.a.Complete:l.a.Error}},Object(s.g)(o),Object(s.d)().openChat({id:c}),c&&a&&await Object(j.a)("editChatPhoto",{chatId:c,photo:a})}(n,c.map(t=>Object(o.Gb)(e,t)).filter(Boolean),i)}),Object(s.b)("toggleChatPinned",(e,t,a)=>{const{id:s,folderId:c}=a,r=Object(o.f)(e,s);if(r)if(c){const t=Object(o.i)(e,c);if(t){const a=!Object(o.N)(e,s,c),{pinnedChatIds:n,includedChatIds:r}=t,i=a?[s,...n||[]]:(n||[]).filter(e=>e!==s),l=[s,...r];Object(j.a)("editChatFolder",{id:c,folderUpdate:{...t,pinnedChatIds:i,includedChatIds:l}})}}else{const t=Object(o.j)(e,s),a=Object(o.N)(e,s,"archived"===t?n.h:void 0);Object(j.a)("toggleChatPinned",{chat:r,shouldBePinned:!a})}}),Object(s.b)("toggleChatArchived",(e,t,a)=>{const{id:s}=a,c=Object(o.f)(e,s);c&&Object(j.a)("toggleChatArchived",{chat:c,folderId:Object(m.hb)(c)?0:n.h})}),Object(s.b)("loadChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,...e}})}}()}),Object(s.b)("loadRecommendedChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchRecommendedChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,recommended:e}})}}()}),Object(s.b)("editChatFolder",(e,t,a)=>{const{id:s,folderUpdate:n}=a,c=Object(o.i)(e,s);c&&Object(j.a)("editChatFolder",{id:s,folderUpdate:{id:s,emoticon:c.emoticon,pinnedChatIds:c.pinnedChatIds,...n}})}),Object(s.b)("addChatFolder",(e,t,a)=>{const{folder:c}=a,{orderedIds:r}=e.chatFolders;!async function(e,t){const{id:a,description:n,...c}=e;if(await Object(j.a)("editChatFolder",{id:t+1,folderUpdate:{id:t+1,...c}}),!n)return;const r=Object(s.e)(),{recommended:o}=r.chatFolders;o&&Object(s.g)({...r,chatFolders:{...r.chatFolders,recommended:o.filter(({id:e})=>e!==a)}})}(c,r&&r.length?Math.max.apply(Math.max,r):n.h)}),Object(s.b)("deleteChatFolder",(e,t,a)=>{const{id:s}=a;Object(o.i)(e,s)&&async function(e){await Object(j.a)("deleteChatFolder",e)}(s)}),Object(s.b)("toggleChatUnread",(e,t,a)=>{const{id:s}=a,n=Object(o.f)(e,s);n&&(n.unreadCount?Object(j.a)("markMessageListRead",{chat:n,threadId:i.MAIN_THREAD_ID}):Object(j.a)("toggleDialogUnread",{chat:n,hasUnreadMark:!n.hasUnreadMark}))}),Object(s.b)("openTelegramLink",(e,t,a)=>{const{url:s}=a;let c=n.hb.exec(s);if(c){const e=c[1];(async()=>{const a=await Object(j.a)("openChatByInvite",e);a&&t.openChat({id:a.id})})()}else{c=n.ib.exec(s);const e=c[1],a=c[2]?Number(c[2]):void 0;C(t,e,a)}}),Object(s.b)("openChatByUsername",(e,t,a)=>{const{username:s}=a;C(t,s)}),Object(s.b)("togglePreHistoryHidden",(e,t,a)=>{const{chatId:s,isEnabled:n}=a;let c=Object(o.f)(e,s);c&&(async()=>{if(Object(m.ib)(c)){if(c=await Object(j.a)("migrateChat",c),!c)return;t.openChat({id:c.id})}Object(j.a)("togglePreHistoryHidden",{chat:c,isEnabled:n})})()}),Object(s.b)("updateChatDefaultBannedRights",(e,t,a)=>{const{chatId:s,bannedRights:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("updateChatDefaultBannedRights",{chat:c,bannedRights:n})}),Object(s.b)("updateChatMemberBannedRights",(e,t,a)=>{const{chatId:n,userId:c,bannedRights:i}=a;let l=Object(o.f)(e,n);const d=Object(o.Gb)(e,c);l&&d&&(async()=>{if(Object(m.ib)(l)){if(l=await Object(j.a)("migrateChat",l),!l)return;t.openChat({id:l.id})}await Object(j.a)("updateChatMemberBannedRights",{chat:l,user:d,bannedRights:i});const e=Object(s.e)(),a=Object(o.f)(e,n);if(!a||!a.fullInfo)return;const{members:b,kickedMembers:u}=a.fullInfo,h=!!i.viewMessages,O=!Object.keys(i).length;Object(s.g)(Object(r.H)(e,n,{fullInfo:{...a.fullInfo,...b&&h&&{members:b.filter(e=>e.userId!==c)},...b&&!h&&{members:b.map(e=>e.userId===c?{...e,bannedRights:i}:e)},...O&&u&&{kickedMembers:u.filter(e=>e.userId!==c)}}}))})()}),Object(s.b)("updateChatAdmin",(e,t,a)=>{const{chatId:n,userId:c,adminRights:i,customTitle:l}=a;let d=Object(o.f)(e,n);const b=Object(o.Gb)(e,c);d&&b&&(async()=>{if(Object(m.ib)(d)){if(d=await Object(j.a)("migrateChat",d),!d)return;t.openChat({id:d.id})}await Object(j.a)("updateChatAdmin",{chat:d,user:b,adminRights:i,customTitle:l});const e=Object(s.e)(),a=Object(o.f)(e,n);if(!a||!a.fullInfo)return;const{adminMembers:u}=a.fullInfo,h=!Object.keys(i).length;Object(s.g)(Object(r.H)(e,n,{fullInfo:{...a.fullInfo,...u&&h&&{adminMembers:u.filter(e=>e.userId!==c)},...u&&!h&&{adminMembers:u.map(e=>e.userId===c?{...e,adminRights:i,customTitle:l}:e)}}}))})()}),Object(s.b)("updateChat",(e,t,a)=>{const{chatId:n,title:c,about:i,photo:d}=a,b=Object(o.f)(e,n);b&&(async()=>{Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.InProgress)),await Promise.all([b.title!==c?Object(j.a)("updateChatTitle",b,c):void 0,b.fullInfo&&b.fullInfo.about!==i?Object(j.a)("updateChatAbout",b,i):void 0,d?Object(j.a)("editChatPhoto",{chatId:n,accessHash:b.accessHash,photo:d}):void 0]),Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.Complete))})()}),Object(s.b)("toggleSignatures",(e,t,a)=>{const{chatId:s,isEnabled:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("toggleSignatures",{chat:c,isEnabled:n})}),Object(s.b)("loadGroupsForDiscussion",()=>{(async()=>{const e=await Object(j.a)("fetchGroupsForDiscussion");if(!e)return;const t=e.reduce((e,t)=>(t&&(e[t.id]=t),e),{}),a=Object(r.c)(Object(s.e)(),t);Object(s.g)({...a,chats:{...a.chats,forDiscussionIds:Object.keys(t).map(Number)}})})()}),Object(s.b)("linkDiscussionGroup",(e,t,a)=>{const{channelId:s,chatId:n}=a,c=Object(o.f)(e,s);let r=Object(o.f)(e,n);c&&r&&(async()=>{if(Object(m.ib)(r)){if(r=await Object(j.a)("migrateChat",r),!r)return;t.openChat({id:r.id})}let{fullInfo:e}=r;if(!e){const t=await Object(j.a)("fetchFullChat",r);if(!t)return;e=t.fullInfo}e.isPreHistoryHidden&&await Object(j.a)("togglePreHistoryHidden",{chat:r,isEnabled:!1}),Object(j.a)("setDiscussionGroup",{channel:c,chat:r})})()}),Object(s.b)("unlinkDiscussionGroup",(e,t,a)=>{const{channelId:s}=a,n=Object(o.f)(e,s);if(!n)return;let c;n.fullInfo&&n.fullInfo.linkedChatId&&(c=Object(o.f)(e,n.fullInfo.linkedChatId)),(async()=>{await Object(j.a)("setDiscussionGroup",{channel:n}),c&&y(c)})()}),Object(s.b)("setActiveChatFolder",(e,t,a)=>({...e,chatFolders:{...e.chatFolders,activeChatFolder:a}})),Object(s.b)("loadMoreMembers",e=>{(async()=>{const{chatId:t}=Object(o.y)(e)||{},a=t?Object(o.f)(e,t):void 0;if(!a||Object(m.ib)(a))return;const n=a.fullInfo&&a.fullInfo.members&&a.fullInfo.members.length||void 0,c=await Object(j.a)("fetchMembers",a.id,a.accessHash,"recent",n);if(!c)return;const{members:i,users:l}=c;i&&i.length&&(e=Object(s.e)(),e=Object(r.f)(e,Object(d.c)(l,"id")),e=Object(r.H)(e,a.id,{fullInfo:{...a.fullInfo,members:[...(a.fullInfo||{}).members||[],...i||[]]}}),Object(s.g)(e))})()});var E=a(153);const w=new Map,M=Object(g.g)(e=>e(),1e3,!0);async function S(e,t,a,c,i=!1,b=!1){const u=e.id;let m;switch(c){case l.e.Backwards:m=void 0;break;case l.e.Around:m=-(Math.round(n.V/2)+1);break;case l.e.Forwards:m=-(n.V+1)}const h=await Object(j.a)("fetchMessages",{chat:Object(o.Db)(Object(s.e)(),u,t),offsetId:a,addOffset:m,limit:n.V,threadId:t});if(!h)return;const{messages:O,users:g,chats:f,threadInfos:p}=h,I=Object(d.c)(O,"id"),v=Object.keys(I).map(Number);let y=Object(s.e)();y=Object(r.b)(y,u,I),y=i?Object(r.db)(y,u,t,v):Object(r.V)(y,u,t,v),y=Object(r.f)(y,Object(d.c)(g,"id")),y=Object(r.c)(y,Object(d.c)(f,"id")),y=Object(r.lb)(y,u,p);let C=Object(o.Y)(y,u,t);const E=Object(o.gb)(y,u,t);if(i&&C&&E&&Object(d.b)(C,E)&&(y=Object(r.V)(y,u,t,E),C=Object(o.Y)(y,u,t),y=Object(r.x)(y,u,t,"outlyingIds",void 0),i=!1),!b){const e=i?E:C,{newViewportIds:s}=k(e,a,c);y=Object(r.z)(y,u,t,s)}Object(s.g)(y)}function k(e,t,a){const{length:s}=e,c=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex((a,s)=>a===t||at)}(e,t):-1,r=a===l.e.Backwards?c:c+1||s,o=r-n.V,i=r+n.V-1,d=e.slice(Math.max(0,o),i+1);let b,u;switch(a){case l.e.Backwards:b=r>0,u=o>=0;break;case l.e.Forwards:b=r0,u=d.length===n.V}return{newViewportIds:d,areSomeLocal:b,areAllLocal:u}}async function N(e){let t;const a=e.attachment?(e,n)=>{w.has(n)||(t=n,w.set(n,a));const c=Object(s.e)();Object(s.g)({...c,fileUploads:{byMessageLocalId:{...c.fileUploads.byMessageLocalId,[n]:{progress:e}}}})}:void 0;e.replyingTo&&await Object(g.f)();const n=Object(s.e)(),c=Object(o.y)(n);if(!c)return;const{threadId:r}=c;e.replyingTo||r===i.MAIN_THREAD_ID||(e.replyingTo=Object(o.Eb)(n,e.chat.id,r)),await Object(j.a)("sendMessage",e,a),a&&t&&w.delete(t)}Object(s.b)("loadViewportMessages",(e,t,a)=>{const{direction:s=l.e.Around,isBudgetPreload:c=!1}=a||{};let{chatId:i,threadId:d}=a||{};if(!i){const t=Object(o.y)(e);if(!t)return;i=t.chatId,d=t.threadId}const b=Object(o.f)(e,i);if(!b||b.isRestricted)return;const u=Object(o.Hb)(e,i,d),m=Object(o.Y)(e,i,d),h=Object(o.gb)(e,i,d);if(u&&u.length&&s!==l.e.Around){const a=s===l.e.Backwards?u[0]:u[u.length-1],n=Boolean(h),o=n?h:m,{newViewportIds:O,areSomeLocal:j,areAllLocal:g}=k(o,a,s);if(j&&(e=Object(r.z)(e,i,d,O)),async function(e,t,a,s,n,c,r,o){t||await S(n,c,o,r,a,s);s||(await Promise.resolve(),e.loadViewportMessages({chatId:n.id,threadId:c,direction:r,isBudgetPreload:!0}))}(t,g,n,c,b,d,s,a),c)return}else{const t=Object(o.I)(e,i)||Object(o.lb)(e,i,d),a=Boolean(t&&m&&!m.includes(t)),s=(a?h:m)||[],{newViewportIds:u,areSomeLocal:O,areAllLocal:j}=k(s,t,l.e.Around);O&&u.length>=n.V&&(e=Object(r.z)(e,i,d,u)),j||S(b,d,t,l.e.Around,a,c)}return e}),Object(s.b)("loadMessage",(e,t,a)=>{const{chatId:n,messageId:c,replyOriginForId:l}=a,b=Object(o.f)(e,n);b&&async function(e,t,a){const n=await Object(j.a)("fetchMessage",{chat:e,messageId:t});if(!n)return;if(n===i.MESSAGE_DELETED){if(a){let t=Object(s.e)();const n=Object(o.k)(t,e.id,a);t=Object(r.L)(t,e.id,a,{...n,replyToMessageId:void 0}),Object(s.g)(t)}return}let c=Object(s.e)();c=Object(r.L)(c,e.id,t,n.message),c=Object(r.f)(c,Object(d.c)(n.users,"id")),Object(s.g)(c)}(b,c,l)}),Object(s.b)("sendMessage",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:c,threadId:r,type:i}=s;if("scheduled"===i&&!a.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:a}};const l=Object(o.f)(e,c);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:c,threadId:r,value:!1});const b={...a,chat:l,replyingTo:Object(o.mb)(e,c,r),noWebPage:Object(o.cb)(e,c,r)},u=!a.attachments||a.attachments.length<=1,m=!u&&a.attachments&&a.attachments.length>1;if(u){const{attachments:e,...t}=b;N({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:a,...s}=b,c=Object(d.n)(a,n.L);for(let a=0;a0?o:void 0}),r.forEach(e=>{N({...s,attachment:e,groupedId:o})})}}else{const{text:e,entities:t,attachments:a,replyingTo:s,...n}=b;e&&N({...n,text:e,entities:t,replyingTo:s}),a.forEach(e=>{N({...n,attachment:e})})}}),Object(s.b)("editMessage",(e,t,a)=>{const{text:s,entities:n}=a,c=Object(o.y)(e);if(!c)return;const{chatId:r,threadId:i,type:l}=c,d=Object(o.f)(e,r),b=Object(o.D)(e,r,i,l);d&&b&&(Object(j.a)("editMessage",{chat:d,message:b,text:s,entities:n,noWebPage:Object(o.cb)(e,r,i)}),t.setEditingId({messageId:void 0}))}),Object(s.b)("cancelSendingMessage",(e,t,a)=>{const{chatId:s,messageId:n}=a,c=Object(o.k)(e,s,n),r=c&&w.get(c.previousLocalId||c.id);r&&Object(j.b)(r),t.apiUpdate({"@type":"deleteMessages",ids:[n],chatId:s})}),Object(s.b)("saveDraft",(e,t,a)=>{const{chatId:s,threadId:n,draft:c}=a;if(!c)return;const{text:l,entities:d}=c,b=Object(o.f)(e,s);return n===i.MAIN_THREAD_ID&&Object(j.a)("saveDraft",{chat:b,text:l,entities:d,replyToMsgId:Object(o.mb)(e,s,n)}),Object(r.x)(e,s,n,"draft",c)}),Object(s.b)("clearDraft",(e,t,a)=>{const{chatId:s,threadId:n,localOnly:c}=a;if(!Object(o.B)(e,s,n))return;const l=Object(o.f)(e,s);return c||n!==i.MAIN_THREAD_ID||Object(j.a)("clearDraft",l),Object(r.x)(e,s,n,"draft",void 0)}),Object(s.b)("toggleMessageWebPage",(e,t,a)=>{const{chatId:s,threadId:n,noWebPage:c}=a;return Object(r.x)(e,s,n,"noWebPage",c)}),Object(s.b)("pinMessage",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageId:n,isUnpin:c,isOneSide:r,isSilent:i}=a;Object(j.a)("pinMessage",{chat:s,messageId:n,isUnpin:c,isOneSide:r,isSilent:i})}),Object(s.b)("unpinAllMessages",(e,t,a)=>{const n=Object(o.f)(e,a.chatId);n&&async function(e){await Object(j.a)("unpinAllMessages",{chat:e});let t=Object(s.e)();t=Object(r.x)(t,e.id,i.MAIN_THREAD_ID,"pinnedIds",[]),Object(s.g)(t)}(n)}),Object(s.b)("deleteMessages",(e,t,a)=>{const{messageIds:s,shouldDeleteForAll:n}=a,c=Object(o.y)(e);if(!c)return;const{chatId:r,threadId:i}=c,l=Object(o.f)(e,r);Object(j.a)("deleteMessages",{chat:l,messageIds:s,shouldDeleteForAll:n});const d=Object(o.C)(e,r,i);s.includes(d)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteScheduledMessages",(e,t,a)=>{const{messageIds:s}=a,n=Object(o.y)(e);if(!n)return;const{chatId:c}=n,r=Object(o.f)(e,c);Object(j.a)("deleteScheduledMessages",{chat:r,messageIds:s});const i=Object(o.E)(e,c);s.includes(i)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteHistory",(e,t,a)=>{(async()=>{const{chatId:s,shouldDeleteForAll:n}=a,c=Object(o.f)(e,s);if(!c)return;const r=c.lastMessage&&c.lastMessage.id;await Object(j.a)("deleteHistory",{chat:c,shouldDeleteForAll:n,maxId:r}),t.openChat({id:void 0})})()}),Object(s.b)("markMessageListRead",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:n,threadId:c}=s,r=Object(o.Db)(e,n,c);if(!r)return;const{maxId:i}=a;M(()=>{Object(j.a)("markMessageListRead",{chat:r,threadId:c,maxId:i})})}),Object(s.b)("markMessagesRead",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageIds:n}=a;Object(j.a)("markMessagesRead",{chat:s,messageIds:n})}),Object(s.b)("loadWebPagePreview",(e,t,a)=>{const{text:n}=a;!async function(e){const t=await Object(j.a)("fetchWebPagePreview",{message:e});Object(s.g)({...Object(s.e)(),webPagePreview:t})}(n)}),Object(s.b)("clearWebPagePreview",e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}}),Object(s.b)("sendPollVote",(e,t,a)=>{const{chatId:s,messageId:n,options:c}=a,r=Object(o.f)(e,s);r&&Object(j.a)("sendPollVote",{chat:r,messageId:n,options:c})}),Object(s.b)("loadPollOptionResults",(e,t,a)=>{const{chat:n,messageId:c,option:o,offset:i,limit:l,shouldResetVoters:b}=a;!async function(e,t,a,n,c,o){const i=await Object(j.a)("loadPollOptionResults",{chat:e,messageId:t,option:a,offset:n,limit:c});if(!i)return;let l=Object(s.e)();l=Object(r.f)(l,Object(d.c)(i.users,"id"));const{voters:b}=l.pollResults;Object(s.g)({...l,pollResults:{...l.pollResults,voters:{...b,[a]:[...!o&&b&&b[a]?b[a]:[],...i&&i.users.map(e=>e.id)].filter((e,t,a)=>a.indexOf(e)===t)},offsets:{...l.pollResults.offsets?l.pollResults.offsets:{},[a]:i.nextOffset||""}}})}(n,c,o,i,l,b)}),Object(s.b)("forwardMessages",e=>{const{fromChatId:t,messageIds:a,toChatId:n}=e.forwardMessages,c=t?Object(o.f)(e,t):void 0,r=n?Object(o.f)(e,n):void 0,i=t&&a?a.sort((e,t)=>e-t).map(a=>Object(o.k)(e,t,a)).filter(Boolean):void 0;c&&r&&i&&i.length&&function(e,t,a){Object(j.a)("forwardMessages",{fromChat:e,toChat:t,messages:a}),Object(s.g)({...Object(s.e)(),forwardMessages:{}})}(c,r,i)}),Object(s.b)("loadScheduledHistory",e=>{const t=Object(o.r)(e);if(!t)return;const{hash:a}=e.scheduledMessages.byChatId[t.id]||{};!async function(e,t){const a=await Object(j.a)("fetchScheduledHistory",{chat:e,hash:t});if(!a)return;const{hash:n,messages:c}=a,o=Object(d.c)(c,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.u)(b,e.id,o,n),b=Object(r.x)(b,e.id,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(b)}(t,a)}),Object(s.b)("sendScheduledMessages",(e,t,a)=>{const{chatId:s,id:n}=a,c=Object(o.f)(e,s);c&&Object(j.a)("sendScheduledMessages",{chat:c,ids:[n]})}),Object(s.b)("rescheduleMessage",(e,t,a)=>{const{chatId:s,messageId:n,scheduledAt:c}=a,r=Object(o.f)(e,s),i=r&&Object(o.pb)(e,r.id,n);r&&i&&Object(j.a)("rescheduleMessage",{chat:r,message:i,scheduledAt:c})}),Object(s.b)("requestThreadInfoUpdate",(e,t,a)=>{const{chatId:s,threadId:n}=a,c=Object(o.Db)(e,s,n);c&&Object(j.a)("requestThreadInfoUpdate",{chat:c,threadId:n})}),Object(s.b)("loadPinnedMessages",(e,t,a)=>{const{chatId:n}=a,c=Object(o.f)(e,n);c&&async function(e){const t=await Object(j.a)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:a,chats:n,users:c}=t,o=Object(d.c)(a,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.b)(b,e.id,o),b=Object(r.x)(b,e.id,i.MAIN_THREAD_ID,"pinnedIds",l),b=Object(r.f)(b,Object(d.c)(c,"id")),b=Object(r.c)(b,Object(d.c)(n,"id")),Object(s.g)(b)}(c)}),Object(s.b)("loadMessageLink",(e,t,a)=>{const{messageId:s,chatId:n}=a,c=Object(o.f)(e,n),r=Object(o.k)(e,n,s);c&&r&&(async()=>{const e=await Object(j.a)("fetchMessageLink",{chat:c,message:r});e&&Object(E.c)(e.link)})()});var P=a(52);const T=Object(g.g)(e=>e(),500,!1);async function A(e,t){const a=await Object(j.a)("searchGifs",{query:e,offset:t});a&&Object(s.g)(Object(r.Q)(Object(s.e)(),!t,a.gifs,a.nextOffset))}Object(s.b)("loadStickerSets",e=>{const{hash:t}=e.stickers.added||{};!async function(e=0){const t=await Object(j.a)("fetchStickerSets",{hash:e});if(!t)return;Object(s.g)(Object(r.ib)(Object(s.e)(),"added",t.hash,t.sets))}(t)}),Object(s.b)("loadAddedStickers",(e,t)=>{const{setIds:a}=e.stickers.added;a&&a.length&&(async()=>{for(let e=0;e0&&await Object(g.e)(500)})()}),Object(s.b)("loadRecentStickers",e=>{const{hash:t}=e.stickers.recent||{};!async function(e=0){const t=await Object(j.a)("fetchRecentStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,recent:t}})}(t)}),Object(s.b)("loadFavoriteStickers",e=>{const{hash:t}=e.stickers.favorite||{};!async function(e=0){const t=await Object(j.a)("fetchFavoriteStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,favorite:t}})}(t)}),Object(s.b)("loadFeaturedStickers",e=>{const{hash:t}=e.stickers.featured||{};!async function(e=0){const t=await Object(j.a)("fetchFeaturedStickers",{hash:e});if(!t)return;Object(s.g)(Object(r.ib)(Object(s.e)(),"featured",t.hash,t.sets))}(t)}),Object(s.b)("loadStickers",(e,t,a)=>{const{stickerSetId:n}=a;let{stickerSetAccessHash:c}=a;if(!c){const t=Object(o.xb)(e,n);if(!t)return;c=t.accessHash}!async function(e,t){const a=await Object(j.a)("fetchStickers",{stickerSetId:e,accessHash:t});if(!a)return;const{set:n,stickers:c,packs:o}=a;let i=Object(s.e)();i=Object(r.hb)(i,n.id,{...n,stickers:c,packs:o});const l=i.stickers.forEmoji.emoji;l&&o[l]&&(i=Object(r.o)(i));Object(s.g)(i)}(n,c)}),Object(s.b)("loadAnimatedEmojis",()=>{!async function(){const e=await Object(j.a)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:a}=e;Object(s.g)(Object(r.q)(Object(s.e)(),{...t,stickers:a}))}()}),Object(s.b)("loadSavedGifs",e=>{const{hash:t}=e.gifs.saved;!async function(e=0){const t=await Object(j.a)("fetchSavedGifs",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,gifs:{...a.gifs,saved:t}})}(t)}),Object(s.b)("faveSticker",(e,t,a)=>{const{sticker:s}=a;s&&Object(j.a)("faveSticker",{sticker:s})}),Object(s.b)("unfaveSticker",(e,t,a)=>{const{sticker:n}=a;n&&function(e){const t=Object(s.e)();Object(s.g)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter(({id:t})=>t!==e.id)}}}),Object(j.a)("faveSticker",{sticker:e,unfave:!0})}(n)}),Object(s.b)("toggleStickerSet",(e,t,a)=>{const{stickerSetId:s}=a,n=Object(o.xb)(e,s);if(!n)return;const{accessHash:c,installedDate:r}=n;Object(j.a)(r?"uninstallStickerSet":"installStickerSet",{stickerSetId:s,accessHash:c})}),Object(s.b)("loadEmojiKeywords",(e,t,a)=>{const{language:n}=a;let c=Object(o.F)(e,n);c&&c.isLoading||(Object(s.g)({...e,emojiKeywords:{...e.emojiKeywords,[n]:{...c,isLoading:!0}}}),(async()=>{const t=await Object(j.a)("fetchEmojiKeywords",{language:n,fromVersion:c?c.version:0});e=Object(s.e)(),c=Object(o.F)(e,n),t?Object(s.g)({...e,emojiKeywords:{...e.emojiKeywords,[n]:{isLoading:!1,version:t.version,keywords:{...c&&c.keywords,...t.keywords}}}}):Object(s.g)({...e,emojiKeywords:{...e.emojiKeywords,[n]:{...c,isLoading:!1}}})})())}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:n}=a;n&&T(()=>{!async function(e,t=0){const a=await Object(j.a)("searchStickers",{query:e,hash:t});if(!a)return;const n=Object(s.e)(),{setsById:c,added:o}=n.stickers,i=a.sets.map(({id:e})=>e);o.setIds&&o.setIds.forEach(t=>{if(!i.includes(t)){const{title:a}=c[t]||{};a&&Object(P.a)(a,e)&&i.unshift(t)}});Object(s.g)(Object(r.ib)(n,"search",a.hash,a.sets,i))}(n)})}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;"string"==typeof s&&T(()=>{A(s)})}),Object(s.b)("searchMoreGifs",e=>{const{query:t,offset:a}=e.gifs.search;"string"==typeof t&&T(()=>{A(t,a)})}),Object(s.b)("loadStickersForEmoji",(e,t,a)=>{const{emoji:n}=a,{hash:c}=e.stickers.forEmoji;T(()=>{!async function(e,t=0){let a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,forEmoji:{...a.stickers.forEmoji,emoji:e}}});const n=await Object(j.a)("fetchStickersForEmoji",{emoji:e,hash:t});if(a=Object(s.e)(),!n||a.stickers.forEmoji.emoji!==e)return;a=Object(r.jb)(a,e,n.stickers,n.hash),Object(s.g)(a)}(n,c)})}),Object(s.b)("clearStickersForEmoji",e=>({...e,stickers:{...e.stickers,forEmoji:{}}}));var x=a(36);const R=Object(g.g)(e=>e(),500,!1);async function L(e="",t,a,c,i,l){let b;if(c){const s=await Object(j.a)("searchMessagesLocal",{chatOrUser:c,query:e,type:t,limit:n.y,offsetId:a,minDate:l,maxDate:i});if(s){const{messages:e,users:t,totalCount:a,nextOffsetId:n}=s;b={messages:e,users:t,chats:[],totalCount:a,nextRate:n}}}else b=await Object(j.a)("searchMessagesGlobal",{query:e,offsetRate:a,limit:n.y,type:t,maxDate:i,minDate:l});let u=Object(s.e)();const m=Object(o.t)(u);if(!b||""!==e&&e!==m)return void Object(s.g)(Object(r.T)(u,{messages:!1}));const{messages:h,users:O,chats:g,totalCount:f,nextRate:p}=b;g.length&&(u=Object(r.c)(u,Object(d.c)(g,"id"))),O.length&&(u=Object(r.f)(u,Object(d.c)(O,"id"))),h.length&&(u=Object(r.d)(u,h)),u=Object(r.U)(u,h,f,t,p),Object(s.g)(u)}async function F(){const e=await Object(j.a)("fetchChats",{limit:n.j,archived:!0,withPinned:!0});if(!e)return;let t=Object(s.e)();t=Object(r.ob)(t,Object(d.c)(e.users,"id")),t=Object(r.M)(t,Object(d.c)(e.chats,"id")),t=Object(r.r)(t,"archived",e.chatIds),t=Object(r.J)(t,"archived",e),Object(s.g)(t)}async function D(){let e=Object(s.e)();const{recentlyFoundChatIds:t}=e.globalSearch,{userIds:a}=e.contactList||{};if(!(a&&a.length||t&&t.length))return;const n=[...t||[],...a||[]].map(t=>Object(o.Gb)(e,t)).filter(Boolean),c=await Object(j.a)("fetchUsers",{users:n});c&&(e=Object(s.e)(),e=Object(r.ob)(e,Object(d.c)(c,"id")),Object(s.g)(e))}Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{chatId:n}=e.globalSearch,{query:c}=a;c&&!n&&R(()=>{!async function(e){const t=await Object(j.a)("searchChats",{query:e});let a=Object(s.e)();const n=Object(o.t)(a);if(!t||!n||e!==n)return void Object(s.g)(Object(r.T)(a,{chats:!1}));const{localChats:c,localUsers:i,globalChats:l,globalUsers:b}=t;(c.length||l.length)&&(a=Object(r.c)(a,Object(d.c)([...c,...l],"id")));(i.length||b.length)&&(a=Object(r.f)(a,Object(d.c)([...i,...b],"id")));a=Object(r.T)(a,{chats:!1}),a=Object(r.R)(a,{localResults:{chatIds:c.map(({id:e})=>e),userIds:i.map(({id:e})=>e)},globalResults:{...a.globalSearch.globalResults,chatIds:b.map(({id:e})=>e),userIds:l.map(({id:e})=>e)}}),Object(s.g)(a)}(c)})}),Object(s.b)("setGlobalSearchDate",(e,t,a)=>{const{date:n}=a,c=n?Object(x.m)(n):n,i=Object(r.R)(e,{date:n,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}});Object(s.g)(i);const{chatId:l}=e.globalSearch;L("","text",void 0,l?Object(o.f)(e,l):void 0,c,n)}),Object(s.b)("searchMessagesGlobal",(e,t,a)=>{const{query:s,resultsByType:n,chatId:c,date:r}=e.globalSearch,i=r?Object(x.m)(r):r,{type:l}=a,{nextOffsetId:d}=n&&n[l]||{};L(s,l,d,c?Object(o.f)(e,c):void 0,i,r)}),Object(s.b)("searchTextMessagesLocal",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},c=t?Object(o.f)(e,t):void 0,l=Object(o.A)(e);if(!c||!l||!a)return;const{query:b,results:u}=l,m=u?u.nextOffsetId:void 0;let h;if(a!==i.MAIN_THREAD_ID){const s=Object(o.Cb)(e,t,a);h=s?s.topMessageId:void 0}!async function(e,t,a,c,i){const l=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:"text",query:c,topMessageId:a,limit:n.X,offsetId:i});if(!l)return;const{messages:b,users:u,totalCount:m,nextOffsetId:h}=l,O=Object(d.c)(b,"id"),g=Object.keys(O).map(Number);let f=Object(s.e)();const p=Object(o.A)(f);if(!p||c&&c!==p.query)return;f=Object(r.b)(f,e.id,O),f=Object(r.f)(f,Object(d.c)(u,"id")),f=Object(r.Z)(f,e.id,t,g,m,h),Object(s.g)(f)}(c,a,h,b,m)}),Object(s.b)("searchMediaMessagesLocal",e=>{const t=Object(o.w)(e),a=t?e.users.byId[t]||e.chats.byId[t]:void 0,c=Object(o.v)(e);if(!a||!c)return;const{currentType:i,resultsByType:l}=c,b=i&&l&&l[i],u=b?b.nextOffsetId:void 0;i&&async function(e,t,a){const c=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:t,limit:n.ob,offsetId:a});if(!c)return;const{messages:i,users:l,totalCount:b,nextOffsetId:u}=c,m=Object(d.c)(i,"id"),h=Object.keys(m).map(Number);let O=Object(s.e)();if(!Object(o.v)(O))return;O=Object(r.b)(O,e.id,m),O=Object(r.f)(O,Object(d.c)(l,"id")),O=Object(r.W)(O,e.id,t,h,b,u),Object(s.g)(O)}(a,i,u)}),Object(s.b)("searchMessagesByDate",(e,t,a)=>{const{timestamp:n}=a,{chatId:c}=Object(o.y)(e)||{};if(!c)return;const r=Object(o.f)(e,c);r&&async function(e,t){const a=await Object(j.a)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});if(!a)return;Object(s.d)().focusMessage({chatId:e.id,messageId:a})}(r,n)}),Object(s.b)("checkPublicLink",(e,t,a)=>{const{chatId:n}=Object(o.y)(e)||{};if(!n)return;if(e.management.progress===l.f.InProgress)return;const{username:c}=a;(async()=>{e=Object(r.bb)(e,l.f.InProgress),e=Object(r.ab)(e,n,{isUsernameAvailable:void 0}),Object(s.g)(e);const t=await Object(j.a)("checkChatUsername",{username:c});e=Object(s.e)(),e=Object(r.bb)(e,t?l.f.Complete:l.f.Error),e=Object(r.ab)(e,n,{isUsernameAvailable:t}),Object(s.g)(e)})()}),Object(s.b)("updatePublicLink",(e,t,a)=>{const{chatId:n}=Object(o.y)(e)||{};let c=n&&Object(o.f)(e,n);if(!n||!c)return;const{username:i}=a;(async()=>{if(e=Object(r.bb)(e,l.f.InProgress),Object(s.g)(e),Object(m.ib)(c)){if(c=await Object(j.a)("migrateChat",c),!c)return;t.openChat({id:c.id})}const a=await Object(j.a)("setChatUsername",{chat:c,username:i});e=Object(s.e)(),e=Object(r.bb)(e,a?l.f.Complete:l.f.Error),e=Object(r.ab)(e,n,{isUsernameAvailable:void 0}),Object(s.g)(e)})()}),Object(s.b)("updatePrivateLink",e=>{const{chatId:t}=Object(o.y)(e)||{},a=t&&Object(o.f)(e,t);t&&a&&Object(j.a)("updatePrivateLink",{chat:a})}),Object(s.b)("sync",(e,t)=>{!async function(e){n.p&&console.log(">>> START SYNC");await Object(j.a)("fetchCurrentUser");const t=await async function(){const e=await Object(j.a)("fetchChats",{limit:n.j,withPinned:!0});if(!e)return;let t=Object(s.e)();const{recentlyFoundChatIds:a}=t.globalSearch,{userIds:c}=t.contactList||{},{currentUserId:l}=t,b=[...a||[],...c||[],...l?[l]:[]],u=b.map(e=>Object(o.Gb)(t,e)).filter(Boolean),h=b.map(e=>Object(o.f)(t,e)).filter(Boolean),{chatId:O}=Object(o.y)(t)||{};if(O){const e=Object(o.f)(t,O);if(e&&!b.includes(O)&&h.push(e),Object(m.lb)(O)){const e=Object(o.Gb)(t,O);e&&!b.includes(O)&&u.push(e)}}u.push(...e.users),h.push(...e.chats),t=Object(r.s)(t,Object(d.c)(h,"id")),t=Object(r.r)(t,"active",e.chatIds),t={...t,chats:{...t.chats}},t=Object(r.J)(t,"active",e),Object.keys(e.draftsById).map(Number).forEach(a=>{t=Object(r.x)(t,a,i.MAIN_THREAD_ID,"draft",e.draftsById[a])}),Object.keys(e.replyingToById).map(Number).forEach(a=>{t=Object(r.x)(t,a,i.MAIN_THREAD_ID,"replyingToId",e.replyingToById[a])}),Object(s.g)(t),O&&!t.chats.byId[O]&&Object(s.d)().openChat({id:void 0});return u}();await async function(e){let t=!1,a=e||[],c=Object(s.e)();const{chatId:l}=Object(o.y)(c)||{},b=Object.keys(c.messages.byChatId).map(Number).reduce((e,t)=>{const a=Object(o.B)(c,t,i.MAIN_THREAD_ID);return a?{...e,[t]:a}:e},{});if(l){const e=await(u=c.chats.byId[l],Object(j.a)("fetchMessages",{chat:u,threadId:i.MAIN_THREAD_ID,offsetId:u.lastReadInboxMessageId,addOffset:-(Math.round(n.V/2)+1),limit:n.V}));c=Object(s.e)();const{chatId:b}=Object(o.y)(c)||{};if(e&&b===l){const s=c.messages.byChatId[l],n=Object(d.c)(e.messages,"id"),o=Object.keys(n).map(Number);c={...c,messages:{...c.messages,byChatId:{[l]:{byId:n,threadsById:{[i.MAIN_THREAD_ID]:{...s&&s.threadsById[i.MAIN_THREAD_ID],listedIds:o,viewportIds:o,outlyingIds:void 0}}}}}},c=Object(r.M)(c,Object(d.c)(e.chats,"id")),c=Object(r.lb)(c,l,e.threadInfos),t=!0,a=Array.prototype.concat(a,e.users)}}var u;t||(c={...c,messages:{...c.messages,byChatId:{}}});Object.keys(b).map(Number).forEach(e=>{c=Object(r.x)(c,e,i.MAIN_THREAD_ID,"draft",b[e])}),e?c=Object(r.y)(c,Object(d.c)(a,"id")):a&&(c=Object(r.ob)(c,Object(d.c)(a,"id")));Object(s.g)(c);const{chatId:m,messageId:h}=c.audioPlayer;m&&h&&!Object(o.k)(c,m,h)&&Object(s.d)().closeAudioPlayer()}(t),Object(s.g)({...Object(s.e)(),lastSyncTime:Date.now()}),n.p&&console.log(">>> FINISH SYNC");e()}(t.afterSync)}),Object(s.b)("afterSync",(e,t)=>{!async function(e){n.p&&console.log(">>> START AFTER-SYNC");e.loadFavoriteStickers(),await Promise.all([D(),F()]),await Object(j.a)("fetchCurrentUser"),n.p&&console.log(">>> FINISH AFTER-SYNC")}(t)});const B=Object(g.a)(e=>e(),500,!1,!0);function U(e,{visibility:t,allowedIds:a,deniedIds:s}){const{users:{byId:n},chats:{byId:c}}=e,r={visibility:t};let o,i;const l=e=>{if(!Object(m.lb)(e))return;const{id:t,accessHash:a}=n[e]||{};return t?{id:t,accessHash:a}:void 0},d=e=>{if(Object(m.lb)(e))return;const t=c[e];return t?{id:t.id}:void 0};return"contacts"!==t&&"nobody"!==t||(o=a.map(l).filter(Boolean),i=a.map(d).filter(Boolean),o.length>0&&(r.allowedUsers=o),i.length>0&&(r.allowedChats=i)),"everybody"!==t&&"contacts"!==t||(o=s.map(l).filter(Boolean),i=s.map(d).filter(Boolean),o.length>0&&(r.blockedUsers=o),i.length>0&&(r.blockedChats=i)),r}Object(s.b)("loadFullUser",(e,t,a)=>{const{userId:s}=a,n=Object(o.Gb)(e,s);if(!n)return;const{id:c,accessHash:r}=n;B(()=>Object(j.a)("fetchFullUser",{id:c,accessHash:r}))}),Object(s.b)("loadUser",(e,t,a)=>{const{userId:n}=a,c=Object(o.Gb)(e,n);c&&(async()=>{const t=await Object(j.a)("fetchUsers",{users:[c]});t&&(e=Object(s.e)(),e=Object(r.ob)(e,Object(d.c)(t,"id")),Object(s.g)(e))})()}),Object(s.b)("loadTopUsers",e=>{const{hash:t,lastRequestedAt:a}=e.topPeers;(!a||Date.now()-a>6e4)&&async function(e){const t=await Object(j.a)("fetchTopUsers",{hash:e});if(!t)return;const{hash:a,ids:n,users:c}=t;let o=Object(s.e)();o=Object(r.f)(o,Object(d.c)(c,"id")),o={...o,topPeers:{...o.topPeers,hash:a,userIds:n,lastRequestedAt:Date.now()}},Object(s.g)(o)}(t)}),Object(s.b)("loadContactList",e=>{const{hash:t}=e.contactList||{};!async function(e){const t=await Object(j.a)("fetchContactList",{hash:e});if(!t)return;let a=Object(r.f)(Object(s.e)(),Object(d.c)(t.users,"id"));a=Object(r.c)(a,Object(d.c)(t.chats,"id"));const n=e=>e.lastName||e.firstName||"",c=new Intl.Collator("en-US"),o=t.users.sort((e,t)=>c.compare(n(e),n(t))).filter(e=>!e.isSelf);Object(s.g)({...a,contactList:{hash:t.hash,userIds:o.map(e=>e.id)}})}(t)}),Object(s.b)("loadCurrentUser",()=>{Object(j.a)("fetchCurrentUser")}),Object(s.b)("updateContact",(e,t,a)=>{const{userId:n,isMuted:c,firstName:i,lastName:d}=a;!async function(e,t,a,n){const c=Object(s.e)(),i=Object(o.Gb)(c,e);if(!i)return;Object(s.d)().updateChatMutedState({chatId:e,isMuted:t}),Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.InProgress));await Object(j.a)("updateContact",{phone:i.phoneNumber,firstName:a,lastName:n})&&Object(s.g)(Object(r.nb)(Object(s.e)(),i.id,{firstName:a,lastName:n}));Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.Complete))}(n,c,i,d)}),Object(s.b)("deleteUser",(e,t,a)=>{const{userId:n}=a;!async function(e){const t=Object(s.e)(),a=Object(o.Gb)(t,e);if(!a)return;const{id:n,accessHash:c}=a;await Object(j.a)("deleteUser",{id:n,accessHash:c})}(n)}),Object(s.b)("loadProfilePhotos",(e,t,a)=>{const{profileId:n}=a,c=Object(m.lb)(n),i=c?Object(o.Gb)(e,n):void 0,l=c?void 0:Object(o.f)(e,n);(async()=>{const e=await Object(j.a)("fetchProfilePhotos",i,l);if(!e||!e.photos)return;let t=Object(s.e)();c?t=Object(r.nb)(t,n,{photos:e.photos}):(t=Object(r.f)(t,Object(d.c)(e.users,"id")),t=Object(r.H)(t,n,{photos:e.photos})),Object(s.g)(t)})()}),Object(s.b)("clickInlineButton",(e,t,a)=>{const{button:c}=a;switch(c.type){case"command":t.sendBotCommand({command:c.value});break;case"url":c.value.match(n.hb)||c.value.match(n.ib)?t.openTelegramLink({url:c.value}):t.toggleSafeLinkModal({url:c.value});break;case"callback":{const t=Object(o.r)(e);if(!t)return;!async function(e,t,a){const n=await Object(j.a)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:a});if(!n||!n.message)return;const{message:c,alert:r}=n;r?Object(s.d)().showError({error:{message:c}}):Object(s.d)().showNotification({message:c})}(t,c.messageId,c.value);break}case"requestPoll":t.openPollModal();break;case"buy":{const a=Object(o.r)(e),{messageId:s,value:n}=c;if(!a)return;n?t.getReceipt({receiptMessageId:n,chatId:a.id,messageId:s}):(t.getPaymentForm({messageId:s}),t.setInvoiceMessageInfo(Object(o.k)(e,a.id,s)),t.openPaymentModal({messageId:s}));break}}}),Object(s.b)("sendBotCommand",(e,t,a)=>{const{command:s}=a,{currentUserId:n}=e,c=Object(o.r)(e);n&&c&&async function(e,t,a){await Object(j.a)("sendMessage",{chat:e,text:a})}(c,0,s)}),Object(s.b)("updateProfile",(e,t,a)=>{const{photo:n,firstName:c,lastName:i,bio:d,username:b}=a;(async()=>{const{currentUserId:t}=e;if(t){if(Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.InProgress}}),n&&await Object(j.a)("updateProfilePhoto",n),c||i||d){if(await Object(j.a)("updateProfile",{firstName:c,lastName:i,about:d})){e=Object(s.e)();const a=t&&Object(o.Gb)(e,t);a&&Object(s.g)(Object(r.nb)(e,a.id,{firstName:c,lastName:i,fullInfo:{...a.fullInfo,bio:d}}))}}if(b){await Object(j.a)("updateUsername",b)&&t&&Object(s.g)(Object(r.nb)(Object(s.e)(),t,{username:b}))}Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.Complete}})}})()}),Object(s.b)("checkUsername",(e,t,a)=>{const{username:n}=a;(async()=>{if(e.profileEdit&&e.profileEdit.progress===l.j.InProgress)return;Object(s.g)({...e,profileEdit:{progress:e.profileEdit?e.profileEdit.progress:l.j.Idle,isUsernameAvailable:void 0}});const t=await Object(j.a)("checkUsername",n);e=Object(s.e)(),Object(s.g)({...e,profileEdit:{...e.profileEdit,isUsernameAvailable:t}})})()}),Object(s.b)("loadWallpapers",()=>{(async()=>{const e=await Object(j.a)("fetchWallpapers",0);if(!e)return;const t=Object(s.e)();Object(s.g)({...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}})})()}),Object(s.b)("uploadWallpaper",(e,t,a)=>{const n=a,c=URL.createObjectURL(n);Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[{slug:l.n,document:{fileName:"",size:n.size,mimeType:n.type,previewBlobUrl:c}},...e.settings.loadedWallpapers||[]]}}),(async()=>{const t=await Object(j.a)("uploadWallpaper",n);if(!t)return;const{wallpaper:a}=t;if(!(e=Object(s.e)()).settings.loadedWallpapers)return;const r=e.settings.loadedWallpapers[0];if(!r||r.slug!==l.n)return;const o={...a,document:{...a.document,previewBlobUrl:c}};Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[o,...e.settings.loadedWallpapers.slice(1)]}})})()}),Object(s.b)("loadBlockedContacts",()=>{(async()=>{const e=await Object(j.a)("fetchBlockedContacts");if(!e)return;let t=Object(s.e)();e.users&&e.users.length&&(t=Object(r.f)(t,Object(d.c)(e.users,"id"))),e.chats&&e.chats.length&&(t=Object(r.M)(t,Object(d.c)(e.chats,"id"))),t={...t,blocked:{...t.blocked,ids:[...t.blocked.ids||[],...e.blockedIds],totalCount:e.totalCount}},Object(s.g)(t)})()}),Object(s.b)("blockContact",(e,t,a)=>{const{contactId:n}=a;(async()=>{if(!await Object(j.a)("blockContact",n))return;const e=Object(s.e)();Object(s.g)(Object(r.a)(e,n))})()}),Object(s.b)("unblockContact",(e,t,a)=>{const{contactId:n}=a;let c;if(Object(m.lb)(n)){const t=Object(o.Gb)(e,n);if(!t)return;c=t.accessHash}(async()=>{if(!await Object(j.a)("unblockContact",n,c))return;const e=Object(s.e)();Object(s.g)(Object(r.p)(e,n))})()}),Object(s.b)("loadAuthorizations",()=>{(async()=>{const e=await Object(j.a)("fetchAuthorizations");e&&Object(s.g)({...Object(s.e)(),activeSessions:e})})()}),Object(s.b)("terminateAuthorization",(e,t,a)=>{const{hash:n}=a;(async()=>{if(!await Object(j.a)("terminateAuthorization",n))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.hash!==n)})})()}),Object(s.b)("terminateAllAuthorizations",()=>{(async()=>{if(!await Object(j.a)("terminateAllAuthorizations"))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.isCurrent)})})()}),Object(s.b)("loadNotificationExceptions",()=>{Object(j.a)("fetchNotificationExceptions")}),Object(s.b)("loadNotificationSettings",()=>{(async()=>{const e=await Object(j.a)("fetchNotificationSettings");e&&Object(s.g)(Object(r.v)(Object(s.e)(),e))})()}),Object(s.b)("updateNotificationSettings",(e,t,a)=>{const{peerType:n,isSilent:c,shouldShowPreviews:o}=a;(async()=>{await Object(j.a)("updateNotificationSettings",n,{isSilent:c,shouldShowPreviews:o})&&Object(s.g)(Object(r.cb)(Object(s.e)(),n,c,o))})()}),Object(s.b)("updateContactSignUpNotification",(e,t,a)=>{const{isSilent:n}=a;(async()=>{await Object(j.a)("updateContactSignUpNotification",n)&&Object(s.g)(Object(r.v)(Object(s.e)(),{hasContactJoinedNotifications:!n}))})()}),Object(s.b)("loadLanguages",()=>{(async()=>{const e=await Object(j.a)("fetchLanguages");e&&Object(s.g)(Object(r.v)(Object(s.e)(),{languages:e}))})()}),Object(s.b)("loadPrivacySettings",()=>{(async()=>{const[e,t,a,n,c]=await Promise.all([Object(j.a)("fetchPrivacySettings","phoneNumber"),Object(j.a)("fetchPrivacySettings","lastSeen"),Object(j.a)("fetchPrivacySettings","profilePhoto"),Object(j.a)("fetchPrivacySettings","forwards"),Object(j.a)("fetchPrivacySettings","chatInvite")]);if(!(e&&t&&a&&n&&c))return;const r=Object(s.e)();r.settings.privacy.phoneNumber=e,r.settings.privacy.lastSeen=t,r.settings.privacy.profilePhoto=a,r.settings.privacy.forwards=n,r.settings.privacy.chatInvite=c,Object(s.g)(r)})()}),Object(s.b)("setPrivacyVisibility",(e,t,a)=>{const{privacyKey:n,visibility:c}=a,{privacy:{[n]:r}}=e.settings;if(!r)return;const o=U(e,{visibility:c,allowedIds:[...r.allowUserIds,...r.allowChatIds],deniedIds:[...r.blockUserIds,...r.blockChatIds]});(async()=>{const e=await Object(j.a)("setPrivacySettings",n,o);if(e){const t=Object(s.e)();t.settings.privacy[n]=e,Object(s.g)(t)}})()}),Object(s.b)("setPrivacySettings",(e,t,a)=>{const{privacyKey:n,isAllowList:c,contactsIds:r}=a,{privacy:{[n]:o}}=e.settings;if(!o)return;const i=U(e,{visibility:o.visibility,allowedIds:c?r:[...o.allowUserIds,...o.allowChatIds],deniedIds:c?[...o.blockUserIds,...o.blockChatIds]:r});(async()=>{const e=await Object(j.a)("setPrivacySettings",n,i);if(e){const t=Object(s.e)();t.settings.privacy[n]=e,Object(s.g)(t)}})()}),Object(s.b)("loadPasswordInfo",()=>{(async()=>{const e=await Object(j.a)("getPasswordInfo");if(!e)return;let t=Object(s.e)();t=Object(r.v)(t,{hasPassword:e.hasPassword}),t=Object(r.mb)(t,{hint:e.hint}),Object(s.g)(t)})()}),Object(s.b)("checkPassword",(e,t,a)=>{const{currentPassword:n,onSuccess:c}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("checkPassword",n);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1})),e&&c()})()}),Object(s.b)("clearPassword",(e,t,a)=>{const{currentPassword:n,onSuccess:c}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("clearPassword",n);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1})),e&&c()})()}),Object(s.b)("updatePassword",(e,t,a)=>{const{currentPassword:n,password:c,hint:o,email:i,onSuccess:l}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updatePassword",n,c,o,i);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1})),e&&l()})()}),Object(s.b)("updateRecoveryEmail",(e,t,a)=>{const{currentPassword:n,email:c,onSuccess:o}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updateRecoveryEmail",n,c);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1,waitingEmailCodeLength:void 0})),e&&o()})()}),Object(s.b)("provideTwoFaEmailCode",(e,t,a)=>{const{code:s}=a;Object(j.a)("provideRecoveryEmailCode",s)}),Object(s.b)("clearTwoFaError",e=>Object(r.mb)(e,{error:void 0}));var H=a(60);Object(s.b)("validateRequestedInfo",(e,t,a)=>{const{requestInfo:n,saveInfo:c}=a,i=Object(o.hb)(e);i&&async function(e,t,a){const n=await Object(j.a)("validateRequestedInfo",{messageId:e,requestInfo:t,shouldSave:a});if(!n)return;const{id:c,shippingOptions:o}=n;if(!c)return;let i=Object(r.E)(Object(s.e)(),c);o?(i=Object(r.gb)(i,o),i=Object(r.C)(i,l.i.Shipping)):i=Object(r.C)(i,l.i.PaymentInfo);Object(s.g)(i)}(i,n,c)}),Object(s.b)("getPaymentForm",(e,t,a)=>{const{messageId:n}=a;n&&async function(e){const t=await Object(j.a)("getPaymentForm",{messageId:e});if(!t)return;let a=Object(r.B)(Object(s.e)(),t),n=l.i.PaymentInfo;a.payment.invoice&&(a.payment.invoice.shippingAddressRequested||a.payment.invoice.nameRequested||a.payment.invoice.phoneRequested||a.payment.invoice.emailRequested)&&(n=l.i.ShippingInfo);a=Object(r.C)(a,n),Object(s.g)(a)}(n)}),Object(s.b)("getReceipt",(e,t,a)=>{const{receiptMessageId:n,chatId:c,messageId:i}=a;i&&n&&c&&async function(e,t,a){const n=await Object(j.a)("getReceipt",t);if(!n)return;let c=Object(s.e)();const i=Object(o.k)(c,a,e);c=Object(r.D)(c,n,i),Object(s.g)(c)}(i,n,c)}),Object(s.b)("clearPaymentError",e=>{Object(s.g)({...e,payment:{...e.payment,error:void 0}})}),Object(s.b)("clearReceipt",e=>{Object(s.g)({...e,payment:{...e.payment,receipt:void 0}})}),Object(s.b)("sendCredentialsInfo",(e,t,a)=>{const n=Object(o.kb)(e);if(!n)return;const{credentials:c}=a,{data:i}=c;!async function(e,t){const a=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}),n=await fetch("https://api.stripe.com/v1/tokens"+a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:"Bearer "+t}}),c=await n.json();if(c.error){const e=Object(H.b)(c.error),t=Object(s.e)();return void Object(s.g)({...t,payment:{...t.payment,error:{...e}}})}let o=Object(r.F)(Object(s.e)(),{type:c.type,id:c.id});o=Object(r.C)(o,l.i.Checkout),Object(s.g)(o)}(i,n)}),Object(s.b)("sendPaymentForm",(e,t,a)=>{const{shippingOptionId:n,saveCredentials:c}=a,i=Object(o.hb)(e),l=Object(o.ib)(e),d=Object(o.kb)(e),b=Object(o.zb)(e);i&&d&&async function(e,t,a,n){if(await Object(j.a)("sendPaymentForm",{messageId:e,credentials:t,requestedInfoId:a,shippingOptionId:n})){const e=Object(r.h)(Object(s.e)());Object(s.g)(Object(r.i)(e))}}(i,{save:c,data:b},l,n)}),Object(s.b)("setPaymentStep",(e,t,a={})=>Object(r.C)(e,a.step||l.i.ShippingInfo)),Object(s.b)("setInvoiceMessageInfo",(e,t,a)=>Object(r.A)(e,a));a(87);var G=a(29),q=a(78);const _=Object(g.g)(e=>e(),1e3,!0);Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateChat":{a.noTopChatsRequest||Object(o.M)(e,a.id)||t.loadTopChats();const n=Object(r.H)(e,a.id,a.chat,a.newProfilePhoto);Object(s.g)(n);const c=Object(o.q)(n);_(()=>Object(q.a)(c));break}case"updateChatJoin":{const n=Object(o.j)(e,a.id);if(!n)break;e=Object(r.I)(e,n,[a.id]),e=Object(r.H)(e,a.id,{isNotJoined:!1}),Object(s.g)(e);const c=Object(o.f)(e,a.id);c&&t.requestChatUpdate({chatId:c.id});break}case"updateChatLeave":{const t=Object(o.j)(e,a.id);if(!t)break;const{[t]:n}=e.chats.listIds;n&&(e=Object(r.r)(e,t,n.filter(e=>e!==a.id))),e=Object(r.H)(e,a.id,{isNotJoined:!0}),Object(s.g)(e);break}case"updateChatInbox":Object(s.g)(Object(r.H)(e,a.id,a.chat));break;case"updateChatTypingStatus":{const{id:t,typingStatus:n}=a;Object(s.g)(Object(r.H)(e,t,{typingStatus:n})),setTimeout(()=>{const e=Object(s.e)(),a=Object(o.f)(e,t);a&&n&&a.typingStatus&&a.typingStatus.timestamp===n.timestamp&&Object(s.g)(Object(r.H)(e,t,{typingStatus:void 0}))},6e3);break}case"newMessage":{const{message:n}=a,{chatId:c,threadId:l,type:d}=Object(o.y)(e)||{};if(n.senderId===e.currentUserId&&!n.isFromScheduled)return;const b=Object(o.f)(e,a.chatId);if(!b)return;const u="thread"===d&&l===i.MAIN_THREAD_ID&&a.chatId===c;u?setTimeout(()=>{t.requestChatUpdate({chatId:a.chatId})},1e3):Object(s.g)(Object(r.H)(e,a.chatId,{unreadCount:b.unreadCount?b.unreadCount+1:1,...a.message.hasUnreadMention&&{unreadMentionsCount:b.unreadMentionsCount?b.unreadMentionsCount+1:1}}));const m=Object(o.q)(Object(s.e)());Object(q.a)(m),Object(G.b)({chat:b,message:n,isActiveChat:u});break}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:n}=a;if(!1!==n.hasUnreadMention)return;t.forEach(t=>{const s="channelId"in a?a.channelId:Object(o.p)(e,t),n=Object(o.f)(e,s);n&&n.unreadMentionsCount&&(e=Object(r.H)(e,s,{unreadMentionsCount:n.unreadMentionsCount-1}))}),Object(s.g)(e);break}case"updateChatFullInfo":{const{fullInfo:t}=a,n=e.chats.byId[a.id];if(!n)return;Object(s.g)(Object(r.H)(e,a.id,{fullInfo:{...n.fullInfo,...t}}));break}case"updatePinnedChatIds":{const{ids:t,folderId:c}=a,r=c===n.h?"archived":"active";e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:t.length?t:void 0}}},Object(s.g)(e);break}case"updateChatPinned":{const{id:t,isPinned:c}=a,r=Object(o.j)(e,t);if(r){const{[r]:a}=e.chats.orderedPinnedIds;let s=a||[];if(c){if(!s.includes(t)){if("active"===r&&s.length>=n.K){const t=e.chats.listIds.active;s=s.filter(e=>t&&t.includes(e))}s=[t,...s]}}else s=s.filter(e=>e!==t);e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:s.length?s:void 0}}}}Object(s.g)(e);break}case"updateChatListType":{const{id:t,folderId:n}=a;Object(s.g)(Object(r.K)(e,t,n));break}case"updateChatFolder":{const{id:t,folder:n}=a,{byId:c,orderedIds:r}=e.chatFolders,o=n?{...c,[t]:n}:Object(d.l)(c,Object.keys(c).map(Number).filter(e=>e!==t)),i=n?r&&r.includes(t)?r:[...r||[],t]:r?r.filter(e=>e!==t):void 0;Object(s.g)({...e,chatFolders:{...e.chatFolders,byId:o,orderedIds:i}});break}case"updateChatFoldersOrder":{const{orderedIds:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,orderedIds:t}});break}case"updateRecommendedChatFolders":{const{folders:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,recommended:t}});break}case"updateChatMembers":{const t=e.chats.byId[a.id],{replacedMembers:n,addedMember:c,deletedMemberId:o}=a;if(!t)return;let i=!1,l=t.fullInfo&&t.fullInfo.members?[...t.fullInfo.members]:[];if(n)l=n,i=!0;else if(c)l.length&&l.some(e=>e.userId===c.userId)||(l.push(c),i=!0);else if(l.length&&o){const e=l.findIndex(e=>e.userId===o);e>-1&&(l.slice(e,1),i=!0)}if(i){const n=l.filter(({isOwner:e,isAdmin:t})=>e||t);Object(s.g)(Object(r.H)(e,a.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:n}}))}break}case"deleteProfilePhotos":{const{chatId:t,ids:n}=a,c=e.chats.byId[t];c&&c.photos&&Object(s.g)(Object(r.H)(e,t,{photos:c.photos.filter(e=>!n.includes(e.id))}));break}}});function V(e,t,a,s,n=!1){const c=n?Object(o.pb)(e,t,a):Object(o.k)(e,t,a);if(c&&s.content){const{photo:e,video:t,sticker:a,document:n}=Object(m.v)(c);e&&s.content.photo?(s.content.photo.blobUrl=e.blobUrl,s.content.photo.thumbnail=e.thumbnail):t&&s.content.video?s.content.video.blobUrl=t.blobUrl:a&&s.content.sticker?s.content.sticker.isPreloadedGlobally=a.isPreloadedGlobally:n&&s.content.document&&(s.content.document.previewBlobUrl=n.previewBlobUrl)}return n?Object(r.eb)(e,t,a,s):Object(r.L)(e,t,a,s)}function $(e,t){const{id:a,chatId:s}=t;if(e=Object(r.V)(e,s,i.MAIN_THREAD_ID,[a]),Object(o.X)(e,s,i.MAIN_THREAD_ID)){const t=Object(o.H)(e,s,i.MAIN_THREAD_ID),n=Object(r.g)(e,s,i.MAIN_THREAD_ID,a),c=Object(o.Hb)(n,s,i.MAIN_THREAD_ID);t&&!c.includes(t)||(e=n)}const{threadInfo:n,firstMessageId:c}=Object(o.Bb)(e,s,t)||{};return!c&&Object(m.sb)(t)||n&&(e=Object(r.V)(e,s,n.threadId,[a]),Object(o.X)(e,s,n.threadId)&&(e=Object(r.g)(e,s,n.threadId,a),c||(e=Object(r.x)(e,s,n.threadId,"firstMessageId",t.id)),n.lastMessageId||(e=Object(r.x)(e,s,n.threadId,"threadInfo",{...n,lastMessageId:t.id})))),e}function z(e,t,a,s=!1){const{chats:n}=e,c=n.byId[t]&&n.byId[t].lastMessage;if(c&&!s){if(!(c.id===a.id||c.id===a.previousLocalId||a.id>c.id))return e}return Object(r.H)(e,t,{lastMessage:a})}function W(e,t){const a=Object(o.m)(e,t),s=Object(o.Y)(e,t,i.MAIN_THREAD_ID);if(!a||!s)return;let n=s.length;for(;n--;){const e=a[s[n]];if(!e.isDeleting)return e}}function K(e,t,a,n){if(e){t.forEach(t=>{const a=W(n=Object(r.L)(n,e,t,{isDeleting:!0}),e);a&&(n=z(n,e,a,!0))}),Object(s.g)(n),a.requestChatUpdate({chatId:e});const c=[];return t.forEach(t=>{const a=Object(o.k)(n,e,t);if(!a)return;const{threadInfo:s}=Object(o.Bb)(n,e,a)||{};s&&c.push(s.threadId)}),Object(d.o)(c).forEach(t=>{a.requestThreadInfoUpdate({chatId:e,threadId:t})}),void setTimeout(()=>{Object(s.g)(Object(r.j)(Object(s.e)(),e,t))},350)}const c=[];t.forEach(e=>{const t=Object(o.p)(n,e);if(t){c.push(t);const a=W(n=Object(r.L)(n,t,e,{isDeleting:!0}),t);a&&(n=z(n,t,a,!0)),setTimeout(()=>{Object(s.g)(Object(r.j)(Object(s.e)(),t,[e]))},350)}}),Object(s.g)(n),Object(d.o)(c).forEach(e=>{a.requestChatUpdate({chatId:e})})}Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"newMessage":{const{chatId:n,id:c,message:i}=a;e=$(e=V(e,n,c,i),i),i.threadInfo&&(e=Object(r.kb)(e,i.threadInfo.chatId,i.threadInfo.threadId,i.threadInfo)),Object(s.g)(e);const l=Object(o.k)(e,n,c);if(Object(o.a)(e,n,i)){if(i.isOutgoing&&(!i.content||!i.content.action)){const a=Object(o.y)(e);a&&t.focusMessage({chatId:n,threadId:a.threadId,messageId:i.id,noHighlight:!0})}const{threadInfo:a}=Object(o.Bb)(e,n,i)||{};a&&t.requestThreadInfoUpdate({chatId:n,threadId:a.threadId}),i.isOutgoing||setTimeout(()=>{Object(s.g)(z(Object(s.e)(),n,l))},350)}else Object(s.g)(z(Object(s.e)(),n,l));Object(o.M)(e,n)||t.loadTopChats();break}case"newScheduledMessage":{const{chatId:t,id:n,message:c}=a;e=V(e,t,n,c,!0);const l=Object(o.ob)(e,t)||[];e=Object(r.x)(e,t,i.MAIN_THREAD_ID,"scheduledIds",Object(d.o)([...l,n])),Object(s.g)(e);break}case"updateMessage":{const{chatId:t,id:n,message:c}=a;if(!Object(o.k)(e,t,n))return;e=V(e,t,n,c);const i=Object(o.k)(e,t,n);c.threadInfo&&(e=Object(r.kb)(e,c.threadInfo.chatId,c.threadInfo.threadId,c.threadInfo)),e=z(e,t,i),Object(s.g)(e);break}case"updateScheduledMessage":{const{chatId:t,id:n,message:c}=a;if(!Object(o.pb)(e,t,n))return;e=V(e,t,n,c,!0);const l=Object.keys(Object(o.qb)(e,t)||{}).map(Number).sort((e,t)=>t-e);e=Object(r.x)(e,t,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(e);break}case"updateMessageSendSucceeded":{const{chatId:t,localId:n,message:c}=a;e=$(e,c);const i=Object(o.k)(e,t,n);e=Object(r.j)(e,t,[n]),c.isScheduled&&(e=Object(r.k)(e,t,[n])),e=Object(r.L)(e,t,c.id,{...i,...c,previousLocalId:n});const l=Object(o.k)(e,t,c.id);e=z(e,t,l),Object(s.g)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:n,message:c}=a,l=Object(o.ob)(e,t)||[];e=Object(r.x)(e,t,i.MAIN_THREAD_ID,"scheduledIds",[...l,c.id]);const d=Object(o.pb)(e,t,n);e=Object(r.k)(e,t,[n]),e=Object(r.eb)(e,t,c.id,{...d,...c,previousLocalId:n}),Object(s.g)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:n,messageIds:c}=a,l=Object(o.jb)(e,t)||[],d=n?[...l,...c].sort((e,t)=>t-e):l.filter(e=>!c.includes(e));Object(s.g)(Object(r.x)(e,t,i.MAIN_THREAD_ID,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:n,threadInfo:c,firstMessageId:i}=a,l={...Object(o.Cb)(e,t,n),...c};if(!l.threadId)return;e=Object(r.kb)(e,t,n,l),i&&(e=Object(r.x)(e,t,n,"firstMessageId",i)),Object(s.g)(e);break}case"resetMessages":{const{id:n}=a,c=Object(o.m)(e,n);c&&!Object(m.lb)(n)&&(e=Object(r.j)(e,n,Object.keys(c).map(Number)),Object(s.g)(e),t.loadFullChat({chatId:n,force:!0}));break}case"deleteMessages":{const{ids:s,chatId:n}=a;K(n,s,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:n}=a;!function(e,t,a,n){if(!e)return;t.forEach(t=>{n=Object(r.eb)(n,e,t,{isDeleting:!0})}),Object(s.g)(n),setTimeout(()=>{n=Object(r.k)(Object(s.e)(),e,t);const a=Object(o.qb)(n,e);n=Object(r.x)(n,e,i.MAIN_THREAD_ID,"scheduledIds",Object.keys(a||{}).map(Number)),Object(s.g)(n)},350)}(n,t,0,e);break}case"deleteHistory":{const{chatId:s}=a;K(s,Object.keys(e.messages.byChatId[s].byId).map(Number),t,e);break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:n}=a;t.forEach(t=>{const a=Object(o.p)(e,t);a&&(e=Object(r.L)(e,a,t,n))}),Object(s.g)(e);break}case"updateChannelMessages":{const{channelId:t,ids:n,messageUpdate:c}=a;n.forEach(a=>{e=Object(r.L)(e,t,a,c)}),Object(s.g)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:n}=a,c=Object(o.l)(e,t);if(c&&c.content.poll){const t={...c.content.poll,...n},{results:a}=t.results||{};if(a&&!a.some(e=>e.isChosen)){const{results:e}=c.content.poll.results,s=e&&e.filter(e=>e.isChosen);s&&s.forEach(e=>{const s=a.findIndex(t=>t.option===e.option);s>=0&&(t.results.results[s].isChosen=!0)})}Object(s.g)(Object(r.L)(e,c.chatId,c.id,{content:{...c.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:n,options:c}=a,i=Object(o.l)(e,t);if(!i||!i.content.poll||!i.content.poll.results)break;const{poll:l}=i.content,{recentVoterIds:d,totalVoters:b,results:u}=l.results,m=d?[...d]:[],h=b?b+1:1,O=u?[...u]:[];m.push(n),c.forEach(t=>{const a=O.find(e=>e.option===t),s=O.findIndex(e=>e.option===t),c=a?{...a}:{option:t,votersCount:0};c.votersCount+=1,n===e.currentUserId&&(c.isChosen=!0),s?O[s]=c:O.push(c)}),Object(s.g)(Object(r.L)(e,i.chatId,i.id,{content:{...i.content,poll:{...l,results:{...l.results,recentVoterIds:m,totalVoters:h,results:O}}}}));break}}});const Q=Object(g.g)((function(){let e=Object(s.e)();Y.forEach(([t,a])=>{e=Object(r.nb)(e,t,{status:a})}),Object(s.g)(e),Y=[]}),3e3,!0);let Y=[];Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"deleteUser":return Object(r.l)(e,a.id);case"updateUser":return Object(r.nb)(e,a.id,a.user);case"updateUserStatus":return s=a.userId,n=a.status,Y.push([s,n]),void Q();case"updateUserFullInfo":{const{id:t,fullInfo:s}=a,n=e.users.byId[t];if(!n)return;return Object(r.nb)(e,t,{fullInfo:{...n.fullInfo,...s}})}}var s,n}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateStickerSet":return Object(r.hb)(e,a.id,a.stickerSet)}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updatePeerBlocked":return a.isBlocked?Object(r.a)(Object(s.e)(),a.id):Object(r.p)(Object(s.e)(),a.id);case"updateResetContactList":Object(s.g)({...Object(s.e)(),contactList:{hash:0,userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[a.key]=a.rules}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateNotifySettings":return Object(r.cb)(e,a.peerType,a.isSilent,a.shouldShowPreviews);case"updateNotifyExceptions":{const{id:t,isMuted:n,isSilent:c,shouldShowPreviews:o}=a;e.chats.byId[t]&&(e=Object(r.H)(e,t,{isMuted:n})),Object(s.g)(Object(r.e)(e,t,{isMuted:n,isSilent:c,shouldShowPreviews:o}));break}}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:a.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:a.message}}}});var X=a(48),J=a(8),Z=a(35),ee=a(131),te=a(47),ae=a(111),se=a(77),ne=a(25),ce=a(62),re=a(42),oe=a(32),ie=a(154),le=a(141);a(197);var de=Object(c.h)(({id:e,name:t,value:a,label:s,checked:n=!1,disabled:r,inactive:o,noAnimation:i,onChange:l,onCheck:d})=>{const b=Object(c.m)(e=>{l&&l(e),d&&d(e.currentTarget.checked)},[l,d]),u=Object(J.a)("Switcher",r&&"disabled",o&&"inactive",i&&"no-animation");return c.a.createElement("label",{className:u,title:s},c.a.createElement("input",{type:"checkbox",id:e,name:t,value:a,checked:n,disabled:r,onChange:b}),c.a.createElement("span",{className:"widget"}))});a(198);const be=[0,1,2];var ue=Object(c.h)(Object(s.h)(e=>{const{query:t,fetchingStatus:a,chatId:s,date:n}=e.globalSearch,{currentUserId:c}=e,{byId:r}=e.chats,{theme:o,animationLevel:i}=e.settings.byKey;return{searchQuery:t,isLoading:!!a&&Boolean(a.chats||a.messages),currentUserId:c,chatsById:r,globalSearchChatId:s,searchDate:n,theme:o,animationLevel:i}},(e,t)=>Object(d.l)(t,["openChat","openTipsChat","setGlobalSearchDate","setGlobalSearchChatId","setSettingOption"]))(({content:e,contactsFilter:t,onSearchQuery:a,onSelectSettings:s,onSelectContacts:r,onSelectArchived:o,setGlobalSearchChatId:i,onReset:d,searchQuery:b,isLoading:u,currentUserId:O,globalSearchChatId:j,searchDate:g,theme:f,animationLevel:p,chatsById:I,openChat:v,openTipsChat:y,setGlobalSearchDate:C,setSettingOption:E})=>{const w=Object(ne.a)(),M=e===l.d.ChatList,S={date:void 0},k={id:void 0},N=Object(c.p)(()=>g?Object(x.a)(new Date(1e3*g)):void 0,[g]),P=Object(c.p)(()=>M&&I?Object.values(I).reduce((e,t)=>Object(m.hb)(t)&&t.unreadCount?e+1:e,0):0,[M,I]),T=Object(c.p)(()=>({onTrigger:e,isOpen:t})=>c.a.createElement(oe.a,{round:!0,ripple:M&&!h.g,size:"smaller",color:"translucent",className:t?"active":"",onClick:M?e:()=>d(),ariaLabel:M?w("AccDescrOpenMenu2"):"Return to chat list"},c.a.createElement("div",{className:Object(J.a)("animated-menu-icon",!M&&"state-back")})),[M,w,d]),A=Object(c.m)(()=>{b||a("")},[b,a]),R=Object(c.m)(()=>{v({id:O})},[O,v]),L=Object(c.m)(e=>{e.stopPropagation();const t="light"===f?"dark":"light";E({theme:t}),Object(se.a)(t,p>0)},[p,E,f]),F=Object(c.m)(e=>{e.stopPropagation();const t=0===p?2:0;be.forEach((e,a)=>{document.body.classList.toggle("animation-level-"+a,t===a)}),E({animationLevel:t})},[p,E]),D=Boolean(j)||e===l.d.GlobalSearch||e===l.d.Contacts,B=e===l.d.Contacts?w("SearchFriends"):w("Search");return c.a.createElement("div",{className:"LeftMainHeader"},c.a.createElement("div",{id:"LeftMainHeader",className:"left-header"},c.a.createElement(ce.a,{trigger:T,footer:`${n.f} alpha ${n.g}`},c.a.createElement(re.a,{icon:"saved-messages",onClick:R},w("SavedMessages")),c.a.createElement(re.a,{icon:"archive",onClick:o},c.a.createElement("span",{className:"menu-item-name"},w("ArchivedChats")),P>0&&c.a.createElement("div",{className:"archived-badge"},P)),c.a.createElement(re.a,{icon:"user",onClick:r},w("Contacts")),c.a.createElement(re.a,{icon:"settings",onClick:s},w("Settings")),c.a.createElement(re.a,{icon:"darkmode",onClick:L},c.a.createElement("span",{className:"menu-item-name"},w("lng_menu_night_mode")),c.a.createElement(de,{id:"darkmode",label:w("dark"===f?"lng_settings_disable_night_theme":"lng_settings_enable_night_theme"),checked:"dark"===f,noAnimation:!0})),c.a.createElement(re.a,{icon:"animations",onClick:F},c.a.createElement("span",{className:"menu-item-name capitalize"},w("Appearance.Animations").toLowerCase()),c.a.createElement(de,{id:"animations",label:"Toggle Animations",checked:p>0})),c.a.createElement(re.a,{icon:"help",onClick:y},w("TelegramFeatures")),c.a.createElement(re.a,{icon:"bug",href:n.x},"Report Bug"),c.a.createElement(re.a,{icon:"char-K",href:"https://web.telegram.org/k/",onClick:()=>{localStorage.setItem("kz_version",JSON.stringify("K"))}},"Switch to K Version"),c.a.createElement(re.a,{icon:"char-W",href:"https://web.telegram.org/?legacy=1"},"Switch to Old Version")),c.a.createElement(ie.a,{inputId:"telegram-search-input",parentContainerClassName:"LeftSearch",className:j||g?"with-picker-item":"",value:t||b,focused:D,isLoading:u,placeholder:B,autoComplete:"off",canClose:Boolean(j||g),onChange:a,onReset:d,onFocus:A},N&&c.a.createElement(le.a,{icon:"calendar",title:N,canClose:!0,isMinimized:Boolean(j),className:"search-date",onClick:C,clickArg:S}),j&&c.a.createElement(le.a,{chatOrUserId:j,onClick:i,canClose:!0,clickArg:k}))))})),me=a(21);a(199);var he=Object(s.h)(e=>Object(d.l)(e,["connectionState"]))(({connectionState:e})=>{const t=Object(ne.a)();return"connectionStateConnecting"===e&&c.a.createElement("div",{id:"ConnectionState",dir:t.isRtl?"rtl":void 0},c.a.createElement(me.a,{color:"black"}),c.a.createElement("div",{className:"state-text"},t("WaitingForNetwork")))}),Oe=a(132),je=a(51),ge=a(26),fe=(e,t,a)=>{const s=Object(c.q)(),n=(e=>Object(c.p)(()=>Object(g.g)(e=>e(),e),[e]))(t),r=Object(ge.a)();return Object(je.a)(()=>{let t=!0;n(()=>{s.current=e(),t||r()}),t=!1},a),s.current},pe=a(168),Ie=a(189);var ve=Object(c.h)(Object(s.h)(e=>{const{chats:{byId:t},users:{byId:a},chatFolders:{byId:s,orderedIds:n,activeChatFolder:c},currentUserId:r,lastSyncTime:i}=e;return{chatsById:t,usersById:a,chatFoldersById:s,orderedFolderIds:n,lastSyncTime:i,notifySettings:Object(o.eb)(e),notifyExceptions:Object(o.db)(e),activeChatFolder:c,currentUserId:r}},(e,t)=>Object(d.l)(t,["loadChatFolders","setActiveChatFolder","openChat"]))(({chatsById:e,usersById:t,chatFoldersById:a,notifySettings:s,notifyExceptions:n,orderedFolderIds:r,activeChatFolder:o,currentUserId:i,lastSyncTime:l,loadChatFolders:b,setActiveChatFolder:u,openChat:O})=>{const j=Object(c.q)(null),g=Object(ne.a)();Object(c.n)(()=>{l&&b()},[l,b]);const f=Object(c.p)(()=>r?r.map(e=>a[e]||{}).filter(Boolean):void 0,[a,r]),p=fe(()=>{if(!f||!f.length)return;const a=Object.keys(e).map(Number),c=f.map(c=>{const{unreadDialogsCount:r,hasActiveDialogs:o}=Object(m.p)(e,t,c,a,s,n)||{};return{id:c.id,badgeCount:r,isBadgeActive:o}});return Object(d.c)(c,"id")},3e3,[f,e,t,s,n]),I=Object(c.p)(()=>{if(f&&f.length)return[{title:g("FilterAllChats")},...f.map(e=>({title:e.title,...p&&p[e.id]}))]},[f,p,g]),v=Object(c.m)(e=>{u(e)},[u]);Object(c.n)(()=>{I&&I.length&&o>=I.length&&u(0)},[o,I,u]),Object(c.n)(()=>{if(j.current&&h.l&&I&&I.length)return Object(Oe.b)(j.current,{onSwipe:(e,t)=>{t===Oe.a.Left?u(Math.min(o+1,I.length-1)):t===Oe.a.Right&&u(Math.max(0,o-1))}})},[o,I,u]);const y=Object(c.q)();y.current=0!==o,Object(c.n)(()=>y.current?Object(te.a)(()=>{y.current&&u(0)}):void 0,[o,u]),Object(c.n)(()=>{const e=e=>{if(e.metaKey&&e.code.startsWith("Digit")&&I){const[,t]=e.code.match(/Digit(\d)/)||[];if(!t)return;if("0"===t)return void O({id:i});const a=Number(t)-1;if(a>I.length-1)return;u(a),e.preventDefault()}};return document.addEventListener("keydown",e,!0),()=>{document.removeEventListener("keydown",e,!0)}});const{shouldRender:C,transitionClassNames:E}=Object(Z.a)(!r,void 0,!0);function w(e){const t=Object.values(a).find(({title:e})=>e===I[o].title);return t&&0!==o?c.a.createElement(Ie.a,{folderType:"folder",folderId:t.id,noChatsText:g("FilterNoChatsToDisplay"),isActive:e}):c.a.createElement(Ie.a,{folderType:"all",isActive:e})}return c.a.createElement("div",{className:"ChatFolders"},I&&I.length?c.a.createElement(pe.a,{tabs:I,activeTab:o,onSwitchTab:v}):C?c.a.createElement("div",{className:Object(J.a)("tabs-placeholder",E)}):void 0,c.a.createElement(ae.a,{ref:j,name:g.isRtl?"slide-reversed":"slide",activeKey:o,renderCount:I?I.length:void 0},w))})),ye=a(11),Ce=a(17),Ee=a(16);var we=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"LeftSearch");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)});var Me=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"ContactList");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)}),Se=a(53);a(210);let ke;var Ne=Object(c.h)(({isShown:e,onNewPrivateChat:t,onNewChannel:a,onNewGroup:s})=>{const[n,r]=Object(c.r)(!1);Object(c.n)(()=>{e||r(!1)},[e]);const o=Object(ne.a)(),i=Object(J.a)("NewChatButton",e&&"revealed",n&&"menu-is-open"),l=Object(c.m)(()=>{ke&&(clearTimeout(ke),ke=void 0)},[]),d=Object(c.m)(()=>{ke&&(clearTimeout(ke),ke=void 0),ke=window.setTimeout(()=>{r(!1)},750)},[]);return c.a.createElement("div",{className:i,onMouseEnter:l,onMouseLeave:d},c.a.createElement(oe.a,{round:!0,color:"primary",className:n?"active":"",onClick:()=>{r(!n)},ariaLabel:o(n?"Close":"NewMessageTitle"),tabIndex:-1},c.a.createElement("i",{className:"icon-new-chat-filled"}),c.a.createElement("i",{className:"icon-close"})),c.a.createElement(Se.a,{isOpen:n,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},c.a.createElement(re.a,{icon:"channel",onClick:a},o("NewChannel")),c.a.createElement(re.a,{icon:"group",onClick:s},o("NewGroup")),c.a.createElement(re.a,{icon:"user",onClick:t},o("NewMessageTitle"))))});a(211);const Pe=Object.keys(l.d).length/2;let Te;var Ae=Object(c.h)(({content:e,searchQuery:t,searchDate:a,contactsFilter:s,onSearchQuery:n,onContentChange:r,onReset:o})=>{const[i,d]=Object(c.r)(h.l),b=Object(c.q)(!1),u=Object(c.m)(()=>{r(l.d.Settings)},[r]),m=Object(c.m)(()=>{r(l.d.Contacts)},[r]),O=Object(c.m)(()=>{r(l.d.NewChannelStep1)},[r]),j=Object(c.m)(()=>{r(l.d.NewGroupStep1)},[r]),g=Object(c.m)(()=>{r(l.d.Archived)},[r]),f=Object(c.m)(()=>{e===l.d.ChatList&&(b.current=!0,d(!0))},[e]),p=Object(c.m)(()=>{b.current=!1,Te&&(clearTimeout(Te),Te=void 0),Te=window.setTimeout(()=>{b.current||d(!1)},250)},[]);return Object(c.n)(()=>{let t;return e!==l.d.ChatList?t=window.setTimeout(()=>{d(!1)},250):(b.current||h.l)&&d(!0),()=>{t&&(clearTimeout(t),t=void 0)}},[e]),c.a.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.l?void 0:f,onMouseLeave:h.l?void 0:p},c.a.createElement(ue,{content:e,contactsFilter:s,onSearchQuery:n,onSelectSettings:u,onSelectContacts:m,onSelectArchived:g,onReset:o}),c.a.createElement(he,null),c.a.createElement(ae.a,{name:"zoom-fade",renderCount:Pe,activeKey:e},n=>{switch(e){case l.d.ChatList:return c.a.createElement(ve,null);case l.d.GlobalSearch:return c.a.createElement(we,{searchQuery:t,searchDate:a,isActive:n,onReset:o});case l.d.Contacts:return c.a.createElement(Me,{filter:s});default:return}}),c.a.createElement(Ne,{isShown:i,onNewPrivateChat:m,onNewChannel:O,onNewGroup:j}))});var xe=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"Settings");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)});var Re=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"NewChat");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)});var Le,Fe=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"ArchivedChats");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)});a(212);!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"}(Le||(Le={}));const De=Object.keys(Le).length/2;var Be=Object(c.h)(Object(s.h)(e=>{const{globalSearch:{query:t,date:a},chatFolders:{activeChatFolder:s}}=e;return{searchQuery:t,searchDate:a,activeChatFolder:s}},(e,t)=>Object(d.l)(t,["setGlobalSearchQuery","setGlobalSearchChatId","resetChatCreation","setGlobalSearchDate","loadPasswordInfo","clearTwoFaError"]))(({searchQuery:e,searchDate:t,activeChatFolder:a,setGlobalSearchQuery:s,setGlobalSearchChatId:n,resetChatCreation:r,setGlobalSearchDate:o,loadPasswordInfo:i,clearTwoFaError:d})=>{const[b,u]=Object(c.r)(l.d.ChatList),[m,O]=Object(c.r)(l.m.Main),[j,g]=Object(c.r)(""),[f,p]=Object(c.r)(0);let I=Le.Main;switch(b){case l.d.Archived:I=Le.Archived;break;case l.d.Settings:I=Le.Settings;break;case l.d.NewChannelStep1:case l.d.NewChannelStep2:I=Le.NewChannel;break;case l.d.NewGroupStep1:case l.d.NewGroupStep2:I=Le.NewGroup}const v=Object(c.m)(e=>{if(b!==l.d.NewGroupStep2||e){if(b===l.d.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(b===l.d.Settings)switch(m){case l.m.EditProfile:case l.m.Folders:case l.m.General:case l.m.Notifications:case l.m.Privacy:case l.m.Language:return void O(l.m.Main);case l.m.GeneralChatBackground:return void O(l.m.General);case l.m.GeneralChatBackgroundColor:return void O(l.m.GeneralChatBackground);case l.m.PrivacyPhoneNumber:case l.m.PrivacyLastSeen:case l.m.PrivacyProfilePhoto:case l.m.PrivacyForwarding:case l.m.PrivacyGroupChats:case l.m.PrivacyActiveSessions:case l.m.PrivacyBlockedUsers:case l.m.TwoFaDisabled:case l.m.TwoFaEnabled:case l.m.TwoFaCongratulations:return void O(l.m.Privacy);case l.m.PrivacyPhoneNumberAllowedContacts:case l.m.PrivacyPhoneNumberDeniedContacts:return void O(l.m.PrivacyPhoneNumber);case l.m.PrivacyLastSeenAllowedContacts:case l.m.PrivacyLastSeenDeniedContacts:return void O(l.m.PrivacyLastSeen);case l.m.PrivacyProfilePhotoAllowedContacts:case l.m.PrivacyProfilePhotoDeniedContacts:return void O(l.m.PrivacyProfilePhoto);case l.m.PrivacyForwardingAllowedContacts:case l.m.PrivacyForwardingDeniedContacts:return void O(l.m.PrivacyForwarding);case l.m.PrivacyGroupChatsAllowedContacts:case l.m.PrivacyGroupChatsDeniedContacts:return void O(l.m.PrivacyGroupChats);case l.m.TwoFaNewPassword:return void O(l.m.TwoFaDisabled);case l.m.TwoFaNewPasswordConfirm:return void O(l.m.TwoFaNewPassword);case l.m.TwoFaNewPasswordHint:return void O(l.m.TwoFaNewPasswordConfirm);case l.m.TwoFaNewPasswordEmail:return void O(l.m.TwoFaNewPasswordHint);case l.m.TwoFaNewPasswordEmailCode:return void O(l.m.TwoFaNewPasswordEmail);case l.m.TwoFaChangePasswordCurrent:case l.m.TwoFaTurnOff:case l.m.TwoFaRecoveryEmailCurrentPassword:return void O(l.m.TwoFaEnabled);case l.m.TwoFaChangePasswordNew:return void O(l.m.TwoFaChangePasswordCurrent);case l.m.TwoFaChangePasswordConfirm:return void O(l.m.TwoFaChangePasswordNew);case l.m.TwoFaChangePasswordHint:return void O(l.m.TwoFaChangePasswordConfirm);case l.m.TwoFaRecoveryEmail:return void O(l.m.TwoFaRecoveryEmailCurrentPassword);case l.m.TwoFaRecoveryEmailCode:return void O(l.m.TwoFaRecoveryEmail);case l.m.FoldersCreateFolder:case l.m.FoldersEditFolder:return void O(l.m.Folders)}b!==l.d.ChatList||0!==a?(u(l.d.ChatList),g(""),s({query:""}),o({date:void 0}),n({id:void 0}),r(),setTimeout(()=>{p(Date.now())},250)):u(l.d.GlobalSearch)}else u(l.d.NewGroupStep1)},[b,a,s,o,n,r,m]),y=Object(c.m)(t=>{b!==l.d.Contacts?(u(l.d.GlobalSearch),t!==e&&s({query:t})):g(t)},[b,s,e]);return Object(c.n)(()=>b!==l.d.ChatList||0===a?Object(te.a)(()=>v()):void 0,[a,b,v]),Object(c.n)(()=>{d(),m===l.m.Privacy&&i()},[d,i,m]),c.a.createElement(ae.a,{id:"LeftColumn",name:h.g?"slide-layers":"push-slide",renderCount:De,activeKey:I},a=>{switch(I){case Le.Archived:return c.a.createElement(Fe,{isActive:a,onReset:v});case Le.Settings:return c.a.createElement(xe,{currentScreen:m,onScreenSelect:O,onReset:v});case Le.NewChannel:return c.a.createElement(Re,{key:f,isChannel:!0,content:b,onContentChange:u,onReset:v});case Le.NewGroup:return c.a.createElement(Re,{key:f,content:b,onContentChange:u,onReset:v});default:return c.a.createElement(Ae,{content:b,searchQuery:e,searchDate:t,contactsFilter:j,onContentChange:u,onSearchQuery:y,onReset:v})}})})),Ue=a(139),He=a(12),Ge=a(13),qe=a(56);var _e=()=>{const[e,t]=Object(c.r)(qe.a.get());return Object(c.n)(()=>{const e=Object(g.g)(()=>{t(qe.a.get())},250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}},[]),e},Ve=a(175);function $e(e,t){const a=e<=n.db?16:32,s=function(e){if(e>n.ab){const t=Math.min(Math.max(.25*e,288),424),a=Math.min(.25*e,424);return Math.min(e-t-a,728)}if(e>n.Z){const t=Math.min(Math.max(.4*e,288),424);return Math.min(e-t,728)}if(e>728)return 728;return e}(e),c=e<=n.db?54:64,r=t?s-a-c:s-a,o=e>n.db?Math.min(s-a,512):s-a,i=o/r,l=r/o;return{composerHiddenScale:i,toolbarHiddenScale:l,composerTranslateX:t?c/2*l:0,toolbarTranslateX:t?c/2*-1*i:0,unpinHiddenScale:o/258,toolbarForUnpinHiddenScale:258/o}}var ze=a(134),We=a(144),Ke=a(135),Qe=a(49),Ye=a(109),Xe=a(123);var Je=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"HeaderMenuContainer",!t);return a?c.a.createElement(a,e):void 0});var Ze=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const n=Object(o.f)(e,t),c=Boolean(n&&Object(m.jb)(n));if(n&&n.isRestricted)return{noMenu:!0};const r=Object(o.P)(e,t),l="thread"===s&&a===i.MAIN_THREAD_ID,d="thread"===s&&a!==i.MAIN_THREAD_ID,b=Object(o.W)(e),u=Boolean(Object(o.L)(e,t)),O=Boolean(l&&n&&(c||Object(m.nb)(n))&&n.isNotJoined),j=l||d,g=l&&!r&&!O,f=!Object(o.S)(e),p=l&&!O;return{noMenu:!(h.g&&O||h.g&&j||g||f||p),isChannel:c,isRightColumnShown:b,canStartBot:u,canSubscribe:O,canSearch:j,canMute:g,canSelect:f,canLeave:p}},(e,t)=>Object(d.l)(t,["joinChannel","sendBotCommand","openLocalTextSearch"]))(({chatId:e,threadId:t,noMenu:a,isChannel:s,canStartBot:n,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,isRightColumnShown:b,joinChannel:u,sendBotCommand:m,openLocalTextSearch:O})=>{const j=Object(c.q)(null),[g,f]=Object(c.r)(!1),[p,I]=Object(c.r)(void 0),v=Object(c.m)(()=>{f(!0);const e=j.current.getBoundingClientRect();I({x:e.right,y:e.bottom})},[]),y=Object(c.m)(()=>{f(!1)},[]),C=Object(c.m)(()=>{I(void 0)},[]),E=Object(c.m)(()=>{u({chatId:e})},[u,e]),w=Object(c.m)(()=>{m({command:"/start"})},[m]),M=Object(c.m)(()=>{if(O(),h.g){document.querySelector("#MobileSearch input").focus()}else setTimeout(()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()},400)},[O]),S=Object(ne.a)();return c.a.createElement("div",{className:"HeaderActions"},!h.g&&r&&c.a.createElement(oe.a,{size:"tiny",ripple:!0,fluid:!0,onClick:E},S(s?"Subscribe":"Join Group")),!h.g&&n&&c.a.createElement(oe.a,{size:"tiny",ripple:!0,fluid:!0,onClick:w},S("Start")),!h.g&&o&&c.a.createElement(oe.a,{round:!0,ripple:b,color:"translucent",size:"smaller",onClick:M,ariaLabel:"Search in this chat"},c.a.createElement("i",{className:"icon-search"})),(h.g||!r)&&c.a.createElement(oe.a,{ref:j,className:g?"active":"",round:!0,ripple:!h.g,size:"smaller",color:"translucent",disabled:a,ariaLabel:"More actions",onClick:v},c.a.createElement("i",{className:"icon-more"})),p&&c.a.createElement(Je,{chatId:e,threadId:t,isOpen:g,anchor:p,isChannel:s,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,onSubscribeChannel:E,onSearchClick:M,onClose:y,onCloseAnimationEnd:C}))})),et=a(115),tt=a(23),at=a(108),st=a(44);function nt(e){const t=e&&Object(m.E)(e),{sticker:a}=e&&e.content||{},s=t&&a&&!Object(h.p)()&&t.includes("image/webp"),[r,o]=Object(c.r)(st.a),i=e&&e.id;return Object(c.o)(()=>{s&&Object(st.c)("b64-"+i,t).then(o).catch(e=>{n.p&&console.error(e)})},[i,s,t]),s?r:t}var ct=a(117),rt=a(43),ot=a(34);function it(e,t,a,s,n){return`M${e},${t+n}a${n},${n},0,0,1,\n ${a},0v${s-2*n}a${n},${n},0,0,1,${-a},0Z`}var lt=Object(c.h)(({count:e,index:t})=>{const a=Object(c.q)(null),s=Object(c.p)(()=>function(e,t){const a=e-t-1,s=function(e){let t=8;1===e?t=36:2===e?t=17:3===e?t=11:(4===e||e>3)&&(t=7.5);return t}(e),n=function(e,t){let a=36;1===e?a=36:2===e?a=17:3===e?a=1===t?12:11:(4===e||e>3)&&(a=7.5);return a}(e,a),c=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,s),r="clipPath"+e,o=function(e,t,a){let s="";if(3===a)s=it(0,0,2,t,1)+it(0,12,2,t+1,1)+it(0,25,2,t,1);else for(let e=0;e\n \n `}(r,s,e),i=function(e,t,a){if(1===a)return 0;if(2===a)return 0===e?0:t+2;return 3===a?0===e?0:1===e?12:25:(t+2)*e}(a,s,e),l=function(e,t,a,s){if(t<=4)return 0;if(e<=1)return 0;if(e>=t-2)return s-36;return(a+4)/2+(e-2)*(a+2)}(a,e,s,c);return{markHeight:n,clipPath:o,markTranslateY:i,trackTranslateY:l,trackHeight:c,clipPathId:r}}(e,t),[e,t]);if(Object(c.n)(()=>{if(!a.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:n,markTranslateY:c,clipPathId:r,clipPath:o}=s,i=a.current.firstElementChild;if(a&&a.current){const s=a.current,{style:l}=s;l.height=e+"px",l.transform=`translateY(-${t}px)`,l.clipPath=`url("#${r}")`;const d=s.querySelector("svg"),b=s.querySelector("div"),u=s.querySelector("defs");d||i&&(i.innerHTML=` ${o} `),u&&(u.innerHTML=o),b&&(b.style.height=n+"px",b.style.transform=`translateY(${c}px)`)}},[s]),1===e)return c.a.createElement("div",{className:"pinned-message-border"},c.a.createElement("div",{className:"pinned-message-border-wrapper-1",ref:a}));const{trackHeight:n,trackTranslateY:r,markHeight:o,markTranslateY:i,clipPathId:l}=s;return c.a.createElement("div",{className:Object(J.a)("pinned-message-border",e>4&&"pinned-message-border-mask")},c.a.createElement("div",{className:"pinned-message-border-wrapper",ref:a,style:`clip-path: url("#${l}"); width: 2px;\n height: ${n}px; transform: translateY(-${r}px);`},c.a.createElement("span",null),c.a.createElement("div",{className:"pinned-message-border-mark",style:`height: ${o}px; transform: translateY(${i}px);`})))});var dt=Object(c.h)(({message:e,count:t,index:a,customTitle:s,className:n,onUnpinMessage:r,onClick:o,onAllPinnedClick:i})=>{const l=Object(ne.a)(),d=nt(e),b=Object(at.a)(Object(m.D)(e,"pictogram")),u=Object(m.N)(l,e,Boolean(d)),[h,O,j]=Object(ot.a)(),g=Object(c.m)(()=>{j(),r&&r(e.id)},[j,r,e.id]);return c.a.createElement("div",{className:Object(J.a)("HeaderPinnedMessage-wrapper",n)},t>1&&c.a.createElement(oe.a,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:l("EventLogFilterPinnedMessages"),onClick:i},c.a.createElement("i",{className:"icon-pin-list"})),r&&c.a.createElement(oe.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:l("UnpinMessageAlertTitle"),className:"unpin-button",onClick:O},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(ct.a,{isOpen:h,onClose:j,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:g}),c.a.createElement("div",{className:"HeaderPinnedMessage",onClick:o,dir:l.isRtl?"rtl":void 0},c.a.createElement(lt,{count:t,index:a}),d&&function(e,t){const{width:a,height:s}=Object(et.k)();return c.a.createElement("img",{src:t||e,width:a,height:s,alt:""})}(d,b),c.a.createElement("div",{className:"message-text"},c.a.createElement("div",{className:"title",dir:"auto"},s||`${l("PinnedMessage")} ${a>0?"#"+(t-a):""}`),c.a.createElement("p",{dir:"auto"},Object(tt.a)(u))),c.a.createElement(rt.a,null)))}),bt=a(54),ut=a(176);a(215);var mt=Object(s.h)((e,{message:t})=>({sender:Object(o.tb)(e,t)}),(e,t)=>Object(d.l)(t,["focusMessage","closeAudioPlayer"]))(({message:e,className:t,noUi:a,sender:s,focusMessage:n,closeAudioPlayer:r})=>{const o=Object(ne.a)(),i=s?Object(m.V)(o,s):void 0,l=bt.c(Object(m.D)(e,"inline")),{playPause:d,isPlaying:b}=Object(ut.a)(Object(m.A)(e),Object(m.r)(e),l,void 0,void 0,!0),u=Object(c.m)(()=>{n({chatId:e.chatId,messageId:e.id})},[n,e.chatId,e.id]),O=Object(c.m)(()=>{b&&d(),r()},[r,b,d]);if(a)return;const j=Object(m.u)(e);return c.a.createElement("div",{className:Object(J.a)("AudioPlayer",t),dir:o.isRtl?"rtl":void 0},c.a.createElement(oe.a,{round:!0,ripple:!h.g,color:"translucent",size:"smaller",className:Object(J.a)("toggle-play",b?"pause":"play"),onClick:d,ariaLabel:b?"Pause audio":"Play audio"},c.a.createElement("i",{className:"icon-play"}),c.a.createElement("i",{className:"icon-pause"})),c.a.createElement("div",{className:"AudioPlayer-content",onClick:u},j?function(e){const{title:t,performer:a,fileName:s}=e;return c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"title",dir:"auto"},Object(tt.a)(t||s)),a&&c.a.createElement("div",{className:"subtitle",dir:"auto"},Object(tt.a)(a)))}(j):function(e,t){return c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"title",dir:"auto"},t&&Object(tt.a)(t)),c.a.createElement("div",{className:"subtitle",dir:"auto"},e))}(o("AttachAudio"),i),c.a.createElement(rt.a,null)),c.a.createElement(oe.a,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:O,ariaLabel:"Close player"},c.a.createElement("i",{className:"icon-close"})))});a(216);var ht=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const{isLeftColumnShown:n,lastSyncTime:c}=e,{byId:r}=e.chats,l=Object(o.f)(e,t),{typingStatus:d}=l||{},{chatId:b,messageId:u}=e.audioPlayer,m=b&&u?Object(o.k)(e,b,u):void 0,h=Object(o.Db)(e,t,a);let O;if("pinned"===s){const a=Object(o.jb)(e,t);O=a&&a.length}else if("scheduled"===s){const a=Object(o.ob)(e,t);O=a&&a.length}else if("thread"===s&&a!==i.MAIN_THREAD_ID){const s=Object(o.Cb)(e,t,a);s&&(O=s.messagesCount)}const j={typingStatus:d,isLeftColumnShown:n,isRightColumnShown:Object(o.W)(e),isSelectModeActive:Object(o.S)(e),audioMessage:m,chat:l,chatsById:r,originChatId:h?h.id:t,messagesCount:O,isChatWithSelf:Object(o.P)(e,t),isChatWithBot:l&&Object(o.O)(e,l),lastSyncTime:c,notifySettings:Object(o.eb)(e),notifyExceptions:Object(o.db)(e)},g=Object(o.m)(e,t);if("thread"!==s||!g)return j;if(Object.assign(j,{messagesById:g}),a!==i.MAIN_THREAD_ID){const s=Object(o.Eb)(e,t,a),n=s?Object(o.k)(e,t,s):void 0,c=n?Object(o.K)(e,n):void 0;return{...j,pinnedMessageIds:s,canUnpin:!1,topMessageSender:c}}const f=Object(o.jb)(e,t);if(f&&f.length){const t=g[f[0]],{canUnpin:s}=t&&Object(o.b)(e,t,a)||{};return{...j,pinnedMessageIds:f,canUnpin:s}}return j},(e,t)=>Object(d.l)(t,["openChatWithInfo","pinMessage","focusMessage","openChat","loadPinnedMessages","toggleLeftColumn","exitMessageSelectMode"]))(({chatId:e,threadId:t,messageListType:a,pinnedMessageIds:s,messagesById:r,canUnpin:o,topMessageSender:l,typingStatus:d,isSelectModeActive:b,isLeftColumnShown:u,isRightColumnShown:O,audioMessage:j,chat:g,chatsById:f,originChatId:p,messagesCount:I,isChatWithSelf:v,isChatWithBot:y,lastSyncTime:C,notifySettings:E,notifyExceptions:w,openChatWithInfo:M,pinMessage:S,focusMessage:k,openChat:N,loadPinnedMessages:P,toggleLeftColumn:T,exitMessageSelectMode:A})=>{const x=Object(ne.a)(),[R,L]=Object(c.r)(0),F=Array.isArray(s)?s[R]:s,D=r&&F?r[F]:void 0,B=Array.isArray(s)?s.length:s?1:0,U=g&&Object(m.l)(x,g).length,H=l?Object(m.V)(x,l):void 0;Object(c.n)(()=>{t===i.MAIN_THREAD_ID&&C&&P({chatId:e})},[e,P,C,t]),Object(c.n)(()=>{L(0)},[s]),Object(We.a)(e,F,D);const{width:G}=_e(),q=G<=n.Z,_=G>=n.db&&u,V=Object(c.q)(null),$=Object(c.q)(!0),z=Object(c.m)(()=>{M({id:e})},[M,e]),W=Object(c.m)(t=>{S({chatId:e,messageId:t,isUnpin:!0})},[S,e]),K=Object(c.m)(()=>{if(D){k({chatId:D.chatId,threadId:t,messageId:D.id});const e=Object(ze.a)(B,R+1);L(e)}},[D,k,t,B,R]),Q=Object(c.m)(()=>{N({id:e,threadId:i.MAIN_THREAD_ID,type:"pinned"})},[N,e]),Y=Object(c.m)(()=>{if(h.g){const e=document.getElementById(n.v);e&&e.blur()}t!==i.MAIN_THREAD_ID||"thread"!==a?("scheduled"===a&&b&&A(),N({id:p,threadId:i.MAIN_THREAD_ID})):h.g?N({id:void 0}):T()},[N,p,t,a,T,b,A]),X=Object(c.p)(()=>{if(!q||!f)return;let e=!1;const t=Object.values(f).reduce((t,a)=>{if(Object(m.hb)(a))return t;const s=a.unreadCount||0;return!s||Object(m.Cb)(a,E,w)&&!a.unreadMentionsCount||(e=!0),t+s},0);return t?{isActive:e,totalCount:t}:void 0},[q,f,E,w]),ee=G>=n.Z&&Gn.db&&G30),te=ee||G>n.ab&&G{const e=V.current;if(e)return te&&ue?void(O||ee?($.current&&(e.classList.add("tools-stacked","animated"),$.current=!1),setTimeout(()=>{e.classList.remove("animated")},350)):(e.classList.remove("tools-stacked"),$.current=!0)):(e.classList.remove("tools-stacked","animated"),void($.current=!0))},[te,ue,ee,O]),c.a.createElement("div",{className:"MiddleHeader",ref:V},c.a.createElement(ae.a,{name:"slide-fade",activeKey:"thread"===a?t:1},me),c.a.createElement("div",{className:"header-tools"},ie&&de&&!se&&c.a.createElement(dt,{key:e,message:de,count:B,index:R,customTitle:be,className:le,onUnpinMessage:o?W:void 0,onClick:K,onAllPinnedClick:Q}),se&&re&&c.a.createElement(mt,{key:Object(m.A)(re),message:re,className:ce}),c.a.createElement(Ze,{chatId:e,threadId:t,messageListType:a})))})),Ot=a(159);function jt(e){return"albumId"in e}function gt(e,t){let a,s=[],n={originalDate:e[0].date,datetime:Number(Object(x.j)(1e3*e[0].date)),senderGroups:[s]};const c=[n];return e.forEach((r,o)=>{r.isInAlbum?a?(a.messages.push(r),r.content.text&&(a.mainMessage=r)):a={albumId:r.groupedId,messages:[r],mainMessage:r}:s.push(r);const i=e[o+1];if(!a||i&&i.groupedId&&i.groupedId===a.albumId||(s.push(a),a=void 0),i){const e=Number(Object(x.j)(1e3*i.date));n.datetime!==e?(n={originalDate:i.date,datetime:e,senderGroups:[]},c.push(n),s=[],n.senderGroups.push(s)):(i.id===t||r.senderId!==i.senderId||r.isOutgoing!==i.isOutgoing||Object(m.db)(r)||Object(m.db)(i)||r.forwardInfo&&i.forwardInfo&&(r.forwardInfo.senderUserId!==i.forwardInfo.senderUserId||r.forwardInfo.fromChatId!==i.forwardInfo.fromChatId||r.forwardInfo.hiddenUserName!==i.forwardInfo.hiddenUserName)||r.inlineButtons||i.inlineButtons)&&(s=[],n.senderGroups.push(s))}}),c}var ft=a(107);function pt(){const[e,t]=Object(ot.a)(!1),a=(s=1e3,n=!1,Object(c.p)(()=>Object(g.a)(e=>e(),s,n,r),[s,n,r]));var s,n,r;return{isScrolled:e,updateStickyDates:Object(c.m)((e,s)=>{t(),document.body.classList.contains("is-scrolling-messages")||Object(g.b)(()=>{document.body.classList.add("is-scrolling-messages")}),a(()=>{Object(g.b)(()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const a=function(e,t){const a=e.querySelectorAll(".sticky-date"),s=e.scrollTop;return Array.from(a).find(e=>{const{offsetTop:a,offsetHeight:n}=e,c=a-s;return-n<=c&&c<=(t?60:10)})}(e,s);a&&a.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")})})},[t,a])}}var It=a(155),vt=a(124);let yt=!1;var Ct=({containerRef:e,className:t,messageIds:a,focusingId:s,loadMoreForwards:r,loadMoreBackwards:o,isViewportNewest:i,firstUnreadId:l,onFabToggle:d,onNotchToggle:b,children:u})=>{const m=Object(c.q)(null),h=Object(c.q)(null),O=Object(c.q)(null),j=Object(c.m)(()=>{if(yt)return;if(!a||!a.length)return d(!1),void b(!1);if(!i)return d(!0),void b(!0);const{offsetHeight:t,scrollHeight:s,scrollTop:n}=e.current,c=s-n-t,r=c<=0;d(l?!r:!(c<=50)),b(!r)},[a,i,e,d,l,b]),{observe:g,freeze:f,unfreeze:p}=Object(ft.a)({rootRef:e,margin:n.U},t=>{if(!r||!o)return;const a=t.find(({isIntersecting:e})=>e);if(!a)return;const{target:s}=a;"backwards-trigger"===s.className?(Object(It.a)(e.current),o()):"forwards-trigger"===s.className&&(Object(It.a)(e.current),r())});Object(ft.c)(m,g),Object(ft.c)(h,g);const{observe:I,freeze:v,unfreeze:y}=Object(ft.a)({rootRef:e,margin:50},j);Object(ft.c)(O,I);const{observe:C}=Object(ft.a)({rootRef:e},j);return Object(ft.c)(O,C),Object(je.a)(()=>{s?(f(),v()):(y(),p())},[s]),Object(je.a)(()=>{yt=!0,setTimeout(()=>{yt=!1},100)},[a]),Object(c.n)(j,[l]),c.a.createElement("div",{className:t,teactFastList:!0},c.a.createElement("div",{ref:m,key:"backwards-trigger",className:"backwards-trigger"}),u,c.a.createElement("div",{ref:h,key:"forwards-trigger",className:"forwards-trigger"}),c.a.createElement("div",{ref:O,key:"fab-trigger",className:"fab-trigger"}))},Et=a(145),wt=a(146);function Mt(e){return"number"==typeof e}function St(e,t){return e?t?238:175:100}function kt(e){const t=Object(m.tb)(e),a=Object(m.qb)(e),s=Object(m.G)(e)||Object(m.R)(e),n=Object(m.P)(e),c=Boolean(Object(m.R)(e)),{width:r,height:o}=s?Object(et.f)(s,t,a,c):Object(et.h)(n,t,a),i=St(Boolean(Object(m.O)(e)));let l=1;re+t,t)}function Lt(e,t,a){return ea?a:e}function Ft(e){const t={width:0,height:0};return e.forEach(({dimensions:e,sides:a})=>{a&Tt&&(t.width=e.width+e.x),a&At&&(t.height=e.height+e.y)}),t}function Dt(e,t,a,s){const c=a.messages.map(e=>{const t=kt(e);return t.width/t.height});const r=function(e){return e.map(e=>e>1.2?"w":e<.8?"n":"q").join("")}(c),o=function(e){return e.reduce((e,t)=>t+e,1)/e.length}(c),i=c.length,l=c.some(e=>e>2),d=function(e,t,a){return a<=n.db?a/100*69-(t?1.625:0)*et.c:((e?30:29)-(t?1.625:0))*et.c}(e,t,s);let b;const u={ratios:c,proportions:r,averageRatio:o,maxWidth:d,minWidth:100,maxHeight:d,spacing:2};return b=i>=5||l?function({ratios:e,averageRatio:t,maxWidth:a,minWidth:s,spacing:n,maxHeight:c=4*a/3}){const r=function(e,t){return e.map(e=>t>1.1?Lt(e,1,2.75):Lt(e,.6667,1))}(e,t),o=e.length,i=new Array(o),l=[],d=e=>{const t=[];let s=0;e.forEach(e=>{t.push(((e,t)=>{const s=Rt(r.slice(e,e+t),0);return(a-(t-1)*n)/s})(s,e)),s+=e}),l.push({lineCounts:e,heights:t})};for(let e=1;e!==o;++e){const t=o-e;e<=3&&t<=3&&d([e,t])}for(let e=1;e!==o-1;++e)for(let a=1;a!==o-e;++a){const s=o-e-a;e<=3&&a<=(t<.85?4:3)&&s<=3&&d([e,a,s])}for(let e=1;e!==o-1;++e)for(let t=1;t!==o-e;++t)for(let a=1;a!==o-e-t;++a){const s=o-e-t-a;e<=3&&t<=3&&a<=3&&s<=4&&d([e,t,a,s])}let b,u=0;for(let e=0;e{for(let e=1;e!==r;++e)if(a[e-1]>a[e])return 1.5;return 1})(),m=Math.abs(o-c)*i*d;(!b||m1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:n}=e,c=Math.round(Math.min(a/t[0],Math.min(a/t[1],(n-s)/2)));return[{dimensions:{x:0,y:0,width:a,height:c},sides:xt|Pt|Tt},{dimensions:{x:0,y:c+s,width:a,height:c},sides:xt|At|Tt}]}(e):"ww"===a||"qq"===a?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:n}=e,c=(a-s)/2,r=Math.round(Math.min(c/t[0],Math.min(c/t[1],n)));return[{dimensions:{x:0,y:0,width:c,height:r},sides:Pt|xt|At},{dimensions:{x:c+s,y:0,width:c,height:r},sides:Pt|Tt|At}]}(e):function(e){const{ratios:t,minWidth:a,maxWidth:s,spacing:n,maxHeight:c}=e,r=Math.round(1.5*a),o=Math.min(Math.round(Math.max(.4*(s-n),(s-n)/t[0]/(1/t[0]+1/t[1]))),s-n-r),i=s-o-n,l=Math.min(c,Math.round(Math.min(i/t[0],o/t[1])));return[{dimensions:{x:0,y:0,width:i,height:l},sides:Pt|xt|At},{dimensions:{x:i+n,y:0,width:o,height:l},sides:Pt|Tt|At}]}(e)}(u):3===i?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:a,ratios:s,maxWidth:n,minWidth:c}=e,r=t,o=Math.round(Math.min((t-a)/2,s[1]*(n-a)/(s[2]+s[1]))),i=r-o-a,l=Math.max(c,Math.round(Math.min((n-a)/2,Math.min(o*s[2],i*s[1])))),d=Math.min(Math.round(r*s[0]),n-a-l);return[{dimensions:{x:0,y:0,width:d,height:r},sides:Pt|xt|At},{dimensions:{x:d+a,y:0,width:l,height:i},sides:Pt|Tt},{dimensions:{x:d+a,y:i+a,width:l,height:o},sides:At|Tt}]}(e):function(e){const{maxWidth:t,ratios:a,maxHeight:s,spacing:n}=e,c=t,r=Math.round(Math.min(c/a[0],.66*(s-n))),o=(t-n)/2,i=Math.min(s-r-n,Math.round(Math.min(o/a[1],o/a[2])));return[{dimensions:{x:0,y:0,width:c,height:r},sides:xt|Pt|Tt},{dimensions:{x:0,y:r+n,width:o,height:i},sides:At|xt},{dimensions:{x:o+n,y:r+n,width:c-o-n,height:i},sides:At|Tt}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function({maxWidth:e,ratios:t,spacing:a,maxHeight:s,minWidth:n}){const c=e,r=Math.round(Math.min(c/t[0],.66*(s-a))),o=Math.round((e-2*a)/(t[1]+t[2]+t[3])),i=Math.max(n,Math.round(Math.min(.4*(e-2*a),o*t[1]))),l=Math.round(Math.max(Math.max(n,.33*(e-2*a)),o*t[3])),d=c-i-l-2*a,b=Math.min(s-r-a,o);return[{dimensions:{x:0,y:0,width:c,height:r},sides:xt|Pt|Tt},{dimensions:{x:0,y:r+a,width:i,height:b},sides:At|xt},{dimensions:{x:i+a,y:r+a,width:d,height:b},sides:At},{dimensions:{x:i+a+d+a,y:r+a,width:l,height:b},sides:Tt|At}]}(e):function({maxHeight:e,ratios:t,maxWidth:a,spacing:s,minWidth:n}){const c=e,r=Math.round(Math.min(c*t[0],.6*(a-s))),o=Math.round((e-2*s)/(1/t[1]+1/t[2]+1/t[3])),i=Math.round(o/t[1]),l=Math.round(o/t[2]),d=c-i-l-2*s,b=Math.max(n,Math.min(a-r-s,o));return[{dimensions:{x:0,y:0,width:r,height:c},sides:Pt|xt|At},{dimensions:{x:r+s,y:0,width:b,height:i},sides:Pt|Tt},{dimensions:{x:r+s,y:i+s,width:b,height:l},sides:Tt},{dimensions:{x:r+s,y:i+l+2*s,width:b,height:d},sides:At|Tt}]}(e)}(u),{layout:b,containerStyle:Ft(b)}}let Bt;function Ut(e){return Bt||(Bt=document.createElement("span"),Bt.style.font='400 12px Roboto, "Helvetica Neue", "Apple Color Emoji", sans-serif',Bt.style.whiteSpace="nowrap",Bt.style.position="absolute",Bt.style.left="-999px",Bt.style.opacity=".01",document.body.appendChild(Bt)),Bt.innerHTML=e,Bt.offsetWidth}function Ht(e,t,a,s,n){Object(c.o)(()=>{if(a&&e.current){const t=e.current.closest(".MessageList");Object(vt.a)(t,e.current,n?"end":"center",20,void 0===s?1500:1e3,s)}},[e,t,a,s,n])}var Gt=a(112),qt=a(67);var _t=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"ContextMenuContainer",!t);return a?c.a.createElement(a,e):void 0});var Vt=Object(c.h)(Object(s.h)((e,{message:t})=>{const a=t.senderId,{targetUserId:s,targetChatId:n}=t.content.action||{},c=t.replyToMessageId,r=c?Object(o.k)(e,t.chatId,c):void 0,i=Object(o.U)(e,t),{direction:l,noHighlight:d}=i&&e.focusedMessage||{},b=Object(o.f)(e,t.chatId);return{sender:b&&(Object(m.jb)(b)||a===t.chatId)?b:a?Object(o.Gb)(e,a):void 0,...s&&{targetUser:Object(o.Gb)(e,s)},targetChatId:n,targetMessage:r,isFocused:i,...i&&{focusDirection:l,noFocusHighlight:d}}})(({message:e,observeIntersection:t,isEmbedded:a,appearanceOrder:s=0,isLastInList:n,sender:r,targetUser:o,targetMessage:i,targetChatId:l,isFocused:d,focusDirection:b,noFocusHighlight:u})=>{const m=Object(c.q)(null);Object(ft.c)(m,t),Object(We.a)(e.chatId,e.replyToMessageId,i),Ht(m,e.chatId,d,b,u);const h=Object(ne.a)(),O=s<=0,[j,g]=Object(ot.a)(O);Object(c.n)(()=>{O||setTimeout(g,10*s)},[s,g,O]);const{transitionClassNames:f}=Object(Z.a)(j,void 0,O,!1),p=Object(qt.a)(h,e,r,o,i,l,a?{isEmbedded:!0,asPlain:!0}:void 0),{isContextMenuOpen:I,contextMenuPosition:v,handleBeforeContextMenu:y,handleContextMenu:C,handleContextMenuClose:E,handleContextMenuHide:w}=Object(Et.a)(m),M=void 0!==v;if(a)return c.a.createElement("span",{className:"embedded-action-message"},Object(tt.a)(p));const S=Object(J.a)("ActionMessage message-list-item",d&&!u&&"focused",M&&"has-menu-open",n&&"last-in-list",f);return c.a.createElement("div",{ref:m,id:"message"+e.id,className:S,"data-message-id":e.id,onMouseDown:y,onContextMenu:C},c.a.createElement("span",null,p),v&&c.a.createElement(_t,{isOpen:I,anchor:v,message:e,messageListType:"thread",onClose:E,onCloseAnimationEnd:w}))}));a(217);var $t=({className:e,message:t,sender:a,title:s,customText:n,observeIntersection:r,onClick:o})=>{const i=Object(c.q)(null),l=Object(ft.b)(i,r),d=Object(at.a)(t&&Object(m.D)(t,"pictogram"),!l),b=t&&"sticker-reply-thumb"+t.id,u=nt(t),h=Boolean(t&&Object(m.I)(t)),O=Object(ne.a)(),j=a&&Object(m.V)(O,a);return c.a.createElement("div",{ref:i,className:Object(J.a)("EmbeddedMessage",e),onClick:t?o:void 0},u&&function(e,t,a,s){const{width:n,height:r}=Object(et.k)();return c.a.createElement("img",{id:e,src:a||t,width:n,height:r,alt:"",className:s?"round":""})}(b,u,d,h),c.a.createElement("div",{className:"message-text"},c.a.createElement("p",{dir:"auto"},t?Object(m.db)(t)?c.a.createElement(Vt,{message:t,isEmbedded:!0}):Object(tt.a)(Object(m.N)(O,t,Boolean(u))):n||" "),c.a.createElement("div",{className:"message-title",dir:"auto"},Object(tt.a)(j||s||" "))))},zt=a(160),Wt=a(167),Kt=a(172);a(221);var Qt=Object(c.h)(({message:e,outgoingStatus:t,signature:a,onClick:s})=>{const n=Object(ne.a)();return c.a.createElement("span",{className:"MessageMeta",dir:n.isRtl?"rtl":"ltr",onClick:s},Boolean(e.views)&&c.a.createElement(c.a.Fragment,null,c.a.createElement("span",{className:"message-views"},Object(Qe.b)(e.views)),c.a.createElement("i",{className:"icon-channelviews"})),a&&c.a.createElement("span",{className:"message-signature"},Object(tt.a)(a)),c.a.createElement("span",{className:"message-time"},e.isEdited&&n("EditedMessage")+" ",Object(x.h)(1e3*e.date)),t&&c.a.createElement(Kt.a,{status:t}))}),Yt=a(114),Xt=a(116),Jt=a(161);a(222);var Zt=({message:e,observeIntersection:t,observeIntersectionForPlaying:a,shouldLoop:s,lastSyncTime:r})=>{const o=Object(c.q)(null),[i,l,d]=Object(ot.a)(),b=e.content.sticker,{isAnimated:u,stickerSetId:h}=b,O=h===n.S,j=Object(ft.b)(o,t),g=Object(ft.b)(o,a),f=b.isPreloadedGlobally?"sticker"+b.id:Object(m.D)(e,"inline"),p=nt(e),I=Object(at.a)(f,!j,Object(m.C)(e,"inline",!0),r),v=Boolean(I),[y,C]=Object(ot.a)(v),E=u?y:v,{shouldRenderFullMedia:w,transitionClassNames:M}=Object(Yt.a)(E,"slow"),{width:S,height:k}=Object(et.l)(b),N=Object(J.a)("thumbnail",!p&&"empty"),P=Object(J.a)("Sticker media-inner",O&&"inactive");return c.a.createElement("div",{ref:o,className:P,onClick:O?void 0:l},!E&&c.a.createElement("img",{id:"sticker-thumb-"+e.id,src:p,width:S,height:k,alt:"",className:N}),!u&&w&&c.a.createElement("img",{id:"sticker-"+e.id,src:I,width:S,height:k,alt:"",className:Object(J.a)("full-media",M)}),u&&v&&c.a.createElement(Xt.a,{key:f,className:Object(J.a)("full-media",M),id:f,animationData:I,size:S,play:g,noLoop:!s,onLoad:C}),c.a.createElement(Jt.a,{isOpen:i,fromSticker:b,onClose:d}))},ea=a(128),ta=a(120),aa=a(162);function sa(e,t){return Object(aa.a)(Object(m.E)(e),Boolean(t),h.g&&!h.c)}var na=a(38);var ca=async(e,t,a,s)=>s?"rgba(255,255,255,1)":async function(e,t){const a=new Image;a.src=e,a.width||await new Promise(e=>{a.onload=e});const s=document.createElement("canvas"),n=s.getContext("2d");s.width=a.width,s.height=a.height,n.drawImage(a,0,0,a.width,a.height);const c=t?a.width-1:0,r=a.height-1;return`rgba(${Array.from(n.getImageData(c,r,1,1).data).join(",")})`}(e,t);var ra=a(121);var oa=({id:e,message:t,observeIntersection:a,shouldAutoLoad:s,isInSelectMode:n,isSelected:r,uploadProgress:o,size:i="inline",dimensions:l,nonInteractive:d,shouldAffectAppendix:b,onClick:u,onCancelUpload:h})=>{const O=Object(c.q)(null),j=(Object(m.G)(t)||Object(m.R)(t)).blobUrl,g=Object(ft.b)(O,a),[f,p]=Object(c.r)(s),I=f&&g,{mediaData:v,downloadProgress:y}=Object(ta.a)(Object(m.D)(t,i),!I),C=j||v,E=sa(t,C),{isUploading:w,isTransferring:M,transferProgress:S}=Object(m.s)(t,o||y,I&&!C),k=!1===Object(na.a)(f),{shouldRender:N,transitionClassNames:P}=Object(Z.a)(M,void 0,k,"slow"),{shouldRenderThumb:T,shouldRenderFullMedia:A,transitionClassNames:x}=Object(Yt.a)(C,"slow"),R=Object(c.m)(()=>{w?h&&h(t):C?u&&u(t.id):p(e=>!e)},[C,w,t,h,u]),L=Object(m.tb)(t);Object(c.o)(()=>{if(!b)return;const e=O.current.closest(".message-content");C?ca(C,L,0,r).then(t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute("data-has-custom-appendix","")}):e.classList.add("has-appendix-thumb")},[C,L,b,n,r]);const{width:F,height:D,isSmall:B}=l||kt(t),U=Object(J.a)("media-inner",!w&&!d&&"interactive",B&&"small-image",F===D&&"square-image"),H=l?`width: ${F}px; height: ${D}px; left: ${l.x}px; top: ${l.y}px;`:"";return c.a.createElement("div",{id:e,ref:O,className:U,style:H,onClick:w?void 0:R},T&&c.a.createElement("canvas",{ref:E,className:"thumbnail",style:`width: ${F}px; height: ${D}px`}),A&&c.a.createElement("img",{src:C,className:"full-media "+x,width:F,height:D,alt:""}),N&&c.a.createElement("div",{className:"media-loading "+P},c.a.createElement(ra.a,{progress:S,onClick:w?R:void 0})),!C&&!f&&c.a.createElement("i",{className:"icon-download"}),M&&c.a.createElement("span",{className:"message-upload-progress"},Math.round(100*S),"%"))},ia=a(137),la=a(136);function da(e,t){const a=Object(c.q)();a.current=t;const s=Object(c.m)(()=>{e.current&&e.current.pause()},[e]),n=Object(c.m)(()=>{e.current&&a.current&&Object(la.a)(e.current)},[e]);Object(X.a)(s,n)}var ba=a(147),ua=(e,t=!1)=>{const a=Object(c.q)(!1),s=Object(c.q)(!1),n=Object(c.m)(()=>{s.current=!0,t&&e.current&&(a.current||(a.current=!e.current.paused),e.current.pause())},[t,e]),r=Object(c.m)(()=>{t&&e.current&&a.current&&document.body.contains(e.current)&&Object(la.a)(e.current),a.current=!1,s.current=!1},[t,e]),o=Object(c.m)(()=>{Object(g.b)(r)},[r]);document.hasFocus()||n(),Object(ee.a)(n,o)};function ma(){return(ma=Object.assign||function(e){for(var t=1;t{const b=Object(c.q)(null),u=Object(c.q)(null),h=t.content.video,O=h.blobUrl,j=Boolean(O)||Object(m.b)(h),g=Object(ft.b)(b,a),[f,p]=Object(c.r)(s),I=Boolean(f&&g&&o),[v,y]=Object(c.r)(n),C=Object(at.a)(Object(m.D)(t,"pictogram"),!(g&&o),Object(m.C)(t,"pictogram"),o),E=sa(t),{mediaData:w,downloadProgress:M}=Object(ta.a)(Object(m.D)(t,"inline"),!I,Object(m.C)(t,"inline"),o),S=O||w,k=Boolean(j&&g&&S),{isBuffered:N,bufferingHandlers:P}=Object(ia.a)(!s),{isUploading:T,isTransferring:A,transferProgress:R}=Object(m.s)(t,r||M,I&&j&&!N),L=!1===Object(na.a)(f),{shouldRender:F,transitionClassNames:D}=Object(Z.a)(A,void 0,L),{shouldRenderThumb:B,transitionClassNames:U}=Object(Yt.a)(S,"slow"),[H,G]=Object(c.r)(0),q=Object(c.m)(e=>{G(Math.max(0,e.currentTarget.currentTime-1))},[]),_=Object(m.tb)(t),V=Object(m.qb)(t),{width:$,height:z}=i||Object(et.h)(h,_,V);da(u,Boolean(k&&n)),ua(u,v),Object(ba.a)(u,[k]);const W=Object(c.m)(()=>{T?d&&d(t):j&&!S?p(e=>!e):j&&S&&!v?(y(!0),u.current.play()):l&&l(t.id)},[T,j,S,v,l,d,t]),K=Object(J.a)("media-inner dark",!T&&"interactive"),Q=Object(J.a)("full-media",U),Y=i?`width: ${$}px; height: ${z}px; left: ${i.x}px; top: ${i.y}px;`:"",X=k,ee=!j&&w,te=!j||f&&!v&&!F,ae=j&&!f;return c.a.createElement("div",{ref:b,id:e,className:K,style:Y,onClick:T?void 0:W},(!k||B)&&c.a.createElement("canvas",{ref:E,className:"thumbnail",style:`width: ${$}px; height: ${z}px;`}),C&&c.a.createElement("img",{src:C,className:"thumbnail",style:`width: ${$}px; height: ${z}px;`,alt:""}),X&&c.a.createElement("video",ma({ref:u,className:Q,width:$,height:z,autoPlay:v,muted:!0,loop:!0,playsInline:!0},P,{onTimeUpdate:q}),c.a.createElement("source",{src:S})),ee&&c.a.createElement("img",{src:w,className:"full-media "+U,width:$,height:z,alt:""}),te&&c.a.createElement("i",{className:"icon-large-play"}),F&&c.a.createElement("div",{className:"media-loading "+D},c.a.createElement(ra.a,{progress:R,onClick:T?W:void 0})),ae&&c.a.createElement("i",{className:"icon-download"}),A&&!j?c.a.createElement("span",{className:"message-upload-progress"},Math.round(100*R),"%"):A&&j?c.a.createElement("span",{className:"message-upload-progress"},"..."):c.a.createElement("div",{className:"message-media-duration"},h.isGif?"GIF":Object(x.e)(h.duration-H)))},Oa=a(18);a(224);var ja=Object(s.h)((e,{contact:t})=>({user:Object(o.Gb)(e,t.userId)}),(e,t)=>Object(d.l)(t,["openUserInfo"]))(({contact:e,user:t,openUserInfo:a})=>{const{firstName:s,lastName:n,phoneNumber:r,userId:o}=e,i=Object(c.m)(()=>{a({id:o})},[a,o]);return c.a.createElement("div",{className:Object(J.a)("Contact",Boolean(o)&&"interactive"),onClick:o?i:void 0},c.a.createElement(Gt.a,{size:"large",user:t,text:s||n}),c.a.createElement("div",{className:"contact-info"},c.a.createElement("div",{className:"contact-name"},s," ",n),c.a.createElement("div",{className:"contact-phone"},Object(Oa.c)(r))))}),ga=a(46);var fa=Object(c.h)(({id:e,options:t,selected:a=[],disabled:s,round:n,loadingOptions:r,onChange:o})=>{const[i,l]=Object(c.r)([]),d=Object(c.m)(e=>{const{value:t,checked:a}=e.currentTarget;let s;s=a?[...i,t]:i.filter(e=>e!==t),l(s),o(s)},[o,i]);return c.a.createElement("div",{id:e,className:"radio-group"},t.map(e=>c.a.createElement(ga.a,{label:e.label,subLabel:e.subLabel,value:e.value,checked:-1!==a.indexOf(e.value),disabled:s,round:n,isLoading:r?-1!==r.indexOf(e.value):void 0,onChange:d})))}),pa=a(126),Ia=a(180);a(227);function va(e,t){return t>0?(e/t*100).toFixed():0}var ya=({answer:e,voteResults:t,totalVoters:a,maxVotersCount:s,correctResults:n,shouldAnimate:r})=>{const o=t&&t.find(t=>t.option===e.option),i=0===n.length||-1!==n.indexOf(e.option),l=n.length>0&&i||o&&o.isChosen,d=o?va(o.votersCount,a||0):0,[b,u]=Object(c.r)(r?0:d),m=Object(c.q)(null),h=o?va(o.votersCount,s||0):0,O=b{r&&u(d)},[r,d]),Object(c.n)(()=>{const e=m.current;if(e&&r){const t=e.firstElementChild,a=O?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",a):e.innerHTML=`\n \n \n `}},[O,r]),!t||!o)return;const j=`width: ${h}%; transform:scaleX(${O?0:1})`;return c.a.createElement("div",{className:"PollOption",dir:"ltr"},c.a.createElement("div",{className:"poll-option-share "+("100"===d?"limit-width":"")},d,"%",l&&c.a.createElement("span",{className:Object(J.a)("poll-option-chosen",!i&&"wrong",r&&"animate")},c.a.createElement("i",{className:i?"icon-check":"icon-close"}))),c.a.createElement("div",{className:"poll-option-right"},c.a.createElement("div",{className:"poll-option-text",dir:"auto"},Object(tt.a)(e.text)),c.a.createElement("div",{className:Object(J.a)("poll-option-answer",l&&!i&&"wrong")},c.a.createElement("div",{className:"poll-option-corner",ref:m}),c.a.createElement("div",{className:"poll-option-line",style:j}))))};a(228);var Ca=Object(c.h)(Object(s.h)((e,{poll:t})=>{const{recentVoterIds:a}=t.results,{byId:s}=e.users;return a&&0!==a.length?{recentVoterIds:a,usersById:s}:{}},(e,t)=>Object(d.l)(t,["loadMessage","openPollResults"]))(({message:e,poll:t,recentVoterIds:a,usersById:s,loadMessage:n,onSendVote:r,openPollResults:o})=>{const{id:i,chatId:l}=e,{summary:d,results:b}=t,[u,m]=Object(c.r)(!1),[h,O]=Object(c.r)([]),[j,g]=Object(c.r)(!1),[f,p]=Object(c.r)(!1),[I,v]=Object(c.r)(!d.closed&&d.closeDate&&d.closeDate>0?Math.min(d.closeDate-Math.floor(Date.now()/1e3),d.closePeriod):0),y=Object(c.q)(null),{results:C,totalVoters:E}=b,w=C&&C.some(e=>e.isChosen),M=!d.closed&&!w,S=!M&&d.isPublic&&Number(b.totalVoters)>0,k=M&&d.multipleChoice,N=C?Math.max(...C.map(e=>e.votersCount)):E,P=C?C.reduce((e,t)=>(t.isCorrect&&e.push(t.option),e),[]):[],T=d.answers.map(e=>({label:e.text,value:e.option,hidden:Boolean(d.quiz&&d.closePeriod&&I<=0)}));Object(c.n)(()=>{u&&t.results.results&&t.results.results.some(e=>e.isChosen)&&m(!1)},[u,t.results.results]),Object(c.n)(()=>{I>0&&setTimeout(()=>v(I-1),1e3);const e=y.current;if(e){const t=12*Math.PI,a=e.lastElementChild,s=e.firstElementChild;if(I<=5&&e.classList.add("hurry-up"),a&&s){const e=(d.closePeriod-I)/d.closePeriod*t;s.textContent=Object(x.e)(I),a.firstElementChild.setAttribute("stroke-dashoffset","-"+e)}else e.innerHTML=`\n ${Object(x.e)(I)}\n \n \n `}},[I,d.closePeriod]),Object(c.n)(()=>{d.quiz&&(I<=0||w&&!d.closed)&&n({chatId:l,messageId:i})},[l,I,w,n,i,d.closed,d.quiz]),Object(c.n)(()=>{let e;return d.quiz&&!d.closed&&d.closePeriod&&d.closePeriod>0&&(e=window.setTimeout(()=>{n({chatId:l,messageId:i})},1e3*d.closePeriod)),()=>{e&&window.clearTimeout(e)}},[M,l,n,i,d.closePeriod,d.closed,d.quiz]);const A=Object(c.p)(()=>a?a.reduce((e,t)=>{const a=s[t];return a&&e.push(a),e},[]):[],[s,a]),R=Object(c.m)(e=>{O([e]),m(!0),p(!0),r([e])},[r]),L=Object(c.m)(e=>{O(e)},[]),F=Object(c.m)(()=>{m(!0),p(!0),r(h)},[r,h]),D=Object(c.m)(()=>{o({chatId:l,messageId:i})},[l,i,o]),B=Object(c.m)(()=>{g(!0)},[]),U=Object(c.m)(()=>{g(!1),p(!1)},[]);Object(c.n)(()=>{if(f&&w&&d.quiz&&b.results&&t.results.solution){b.results.find(e=>e.isChosen&&e.isCorrect)||g(!0)}},[w,f,b.results,d.quiz,t.results.solution]);const H=Object(ne.a)();return c.a.createElement("div",{className:"Poll",dir:H.isRtl?"auto":"ltr"},j&&t.results.solution&&c.a.createElement(Ia.a,{message:Object(wt.b)(t.results.solution,t.results.solutionEntities),duration:5e3,onDismiss:U,containerId:"#middle-column-portals"}),c.a.createElement("div",{className:"poll-question"},Object(tt.a)(d.question)),c.a.createElement("div",{className:"poll-type"},H(function(e){if(void 0===e.isPublic)return" ";if(e.quiz)return e.isPublic?"QuizPoll":"AnonymousQuizPoll";if(e.closed)return"FinalResults";return e.isPublic?"PublicPoll":"AnonymousPoll"}(d)),A.length>0&&c.a.createElement("div",{className:"poll-recent-voters"},A.map(e=>c.a.createElement(Gt.a,{size:"micro",user:e}))),I>0&&M&&c.a.createElement("div",{ref:y,className:"poll-countdown"}),d.quiz&&t.results.solution&&!M&&c.a.createElement(oe.a,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:j,onClick:B,ariaLabel:"Show Solution"},c.a.createElement("i",{className:"icon-lamp"}))),M&&c.a.createElement("div",{className:"poll-answers"},k?c.a.createElement(fa,{options:T,onChange:L,disabled:e.isScheduled||u,loadingOptions:u?h:void 0,round:!0}):c.a.createElement(pa.a,{name:"poll-"+i,options:T,onChange:R,disabled:e.isScheduled||u,loadingOption:u?h[0]:void 0})),!M&&c.a.createElement("div",{className:"poll-results"},d.answers.map((function(e){return c.a.createElement(ya,{key:e.option,shouldAnimate:f,answer:e,voteResults:C,totalVoters:E,maxVotersCount:N,correctResults:P})}))),!S&&!k&&c.a.createElement("div",{className:"poll-voters-count"},function(e,t,a){if(!a)return e(t?"Chat.Quiz.TotalVotesEmpty":"Chat.Poll.TotalVotesResultEmpty");return e(t?"Answer":"Vote",a,"i")}(H,d.quiz,b.totalVoters)),k&&c.a.createElement(oe.a,{isText:!0,disabled:0===h.length,size:"tiny",onClick:F},H("PollSubmitVotes")),S&&c.a.createElement(oe.a,{isText:!0,size:"tiny",onClick:D},H("PollViewResults")))})),Ea=a(39),wa=a(57);a(229);var Ma=Object(c.h)(({message:e,observeIntersection:t,shouldAutoLoad:a,inPreview:s,onMediaClick:n,onCancelMediaTransfer:r})=>{const o=Object(m.Q)(e);let i=!1;if(o&&o.photo){const{width:t,height:a}=kt(e);i=t===a}const l=Object(c.m)(()=>{n()},[n]);if(!o)return;const{siteName:d,url:b,displayUrl:u,title:h,description:O,photo:j}=o,g=j&&n&&!i&&!o.hasDocument,f=Object(Ea.a)(O,170),p=Object(J.a)("WebPage",j?i&&"with-square-photo":!s&&"without-photo");return c.a.createElement("div",{className:p,"data-initial":(d||u)[0],dir:"auto"},j&&c.a.createElement(oa,{message:e,observeIntersection:t,shouldAutoLoad:a,size:i?"pictogram":"inline",nonInteractive:!g,onClick:g?l:void 0,onCancelUpload:r}),c.a.createElement("div",{className:"WebPage-text"},c.a.createElement(wa.a,{className:"site-name",url:b,text:d||u}),!s&&h&&c.a.createElement("p",{className:"site-title"},Object(tt.a)(h)),f&&c.a.createElement("p",{className:"site-description"},Object(tt.a)(f,["emoji","br"]))))});a(230);var Sa=Object(c.h)(({message:e})=>{const t=Object(m.z)(e),{title:a,text:s,description:n,photoUrl:r}=t;return c.a.createElement("div",{className:"Invoice"},a&&c.a.createElement("p",{className:"title"},Object(tt.a)(a)),s&&c.a.createElement("p",null,Object(tt.a)(s,["emoji","br"])),c.a.createElement("div",{className:"description "+(r?"has-image":"")},r&&c.a.createElement("img",{className:"invoice-image",src:r,alt:""}),n&&c.a.createElement("p",{className:"description-text"},Object(tt.a)(n,["emoji","br"]))))});function ka(e){return Object(c.h)(Object(s.h)((e,t)=>{const{message:a}=t;return{isInSelectMode:Object(o.S)(e),isSelected:Object(o.V)(e,a.id)}},(e,t)=>Object(d.l)(t,["toggleMessageSelection"]))(t=>{const{isInSelectMode:a,isSelected:s,message:n,toggleMessageSelection:r,dimensions:o}=t,i=Object(c.m)(e=>{e.stopPropagation(),r({messageId:n.id,withShift:e&&e.shiftKey})},[r,n]),l=Object(c.p)(()=>({...t,isInSelectMode:a,isSelected:s,dimensions:{...t.dimensions,x:0,y:0},onClick:a?void 0:t.onClick}),[t,a,s]);return c.a.createElement("div",{className:Object(J.a)("album-item-select-wrapper",s&&"is-selected"),style:o?`left: ${o.x}px; top: ${o.y}px;`:"",onClick:a?i:void 0},a&&c.a.createElement("div",{className:"message-select-control"},s&&c.a.createElement("i",{className:"icon-select"})),c.a.createElement(e,l))}))}a(231);const Na=ka(oa),Pa=ka(ha);var Ta=Object(s.h)(e=>({uploadsById:e.fileUploads.byMessageLocalId}),(e,t)=>Object(d.l)(t,["cancelSendingMessage"]))(({album:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,hasCustomAppendix:n,lastSyncTime:r,isOwn:o,albumLayout:i,onMediaClick:l,uploadsById:d,cancelSendingMessage:b})=>{const u=e.messages.length,h=Object(c.m)(e=>{b({chatId:e.chatId,messageId:e.id})},[b]);const{width:O,height:j}=i.containerStyle;return c.a.createElement("div",{className:"Album",style:`width: ${O}px; height: ${j}px;`},e.messages.map((function(e,b){const{photo:O,video:j}=Object(m.v)(e),g=d[e.previousLocalId||e.id],f=g?g.progress:void 0,{dimensions:p,sides:I}=i.layout[b];if(O){const s=n&&(o?b===u-1:Boolean(I&xt&&I&At));return c.a.createElement(Na,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAffectAppendix:s,uploadProgress:f,dimensions:p,onClick:l,onCancelUpload:h})}if(j)return c.a.createElement(Pa,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,uploadProgress:f,lastSyncTime:r,dimensions:p,onClick:l,onCancelUpload:h})})))});a(232);function Aa(){return(Aa=Object.assign||function(e){for(var t=1;t{const r=Object(c.q)(null),o=Object(c.q)(null),i=Object(c.q)(null),l=e.content.video,d=Object(ft.b)(r,t),[b,u]=Object(c.r)(a&&s),h=Boolean(b&&d&&n),{mediaData:O,downloadProgress:j}=Object(ta.a)(Object(m.D)(e,"inline"),!h,Object(m.C)(e,"inline"),n),g=sa(e,O),{isBuffered:f,bufferingHandlers:p}=Object(ia.a)(),I=b&&!f,v=!1===Object(na.a)(b),{shouldRender:y,transitionClassNames:C}=Object(Z.a)(I||!f,void 0,v),{shouldRenderThumb:E,transitionClassNames:w}=Object(Yt.a)(O,"slow"),[M,S]=Object(c.r)(!1),[k,N]=Object(c.r)(0);Object(c.n)(()=>{if(!M)return;const e=188*Math.PI,t=e-k*e,a=i.current,s=o.current,n=s.firstElementChild;n?n.firstElementChild.setAttribute("stroke-dashoffset",t.toString()):s.innerHTML=`\n \n `,N(a.currentTime/a.duration)},[M,k]);const P=Boolean(O&&d),T=()=>{S(!1),N(0),Object(la.a)(i.current),requestAnimationFrame(()=>{o.current.innerHTML=""})},A=(R=T,()=>{xa&&xa(),xa=R});var R;Object(c.n)(()=>{i.current&&(P?Object(la.a)(i.current):i.current.pause())},[P]),da(i,P),ua(i,Boolean(O)),Object(ba.a)(i,[O]);const L=Object(c.m)(()=>{if(!O)return void u(e=>!e);const e=i.current;M?e.paused?Object(la.a)(e):e.pause():(A(),e.currentTime=0,S(!0))},[A,M,O]),F=Object(c.m)(e=>{const t=e.currentTarget;N(t.currentTime/t.duration)},[]),D=Object(J.a)("full-media",w);return c.a.createElement("div",{ref:r,className:"RoundVideo media-inner",onClick:L},E&&c.a.createElement("div",{className:"thumbnail-wrapper"},c.a.createElement("canvas",{ref:g,className:"thumbnail",style:`width: ${et.d}px; height: ${et.d}px`})),O&&c.a.createElement("div",{className:"video-wrapper"},c.a.createElement("video",Aa({ref:i,className:D,width:et.d,height:et.d,autoPlay:!0,muted:!M,loop:!M,playsInline:!0,onEnded:M?T:void 0},p,{onTimeUpdate:M?F:void 0}),c.a.createElement("source",{src:O}))),c.a.createElement("div",{className:"progress",ref:o}),y&&c.a.createElement("div",{className:"media-loading "+C},c.a.createElement(ra.a,{progress:j})),!O&&!b&&c.a.createElement("i",{className:"icon-large-play"}),c.a.createElement("div",{className:"message-media-duration"},M?Object(x.e)(i.current.currentTime):Object(x.e)(l.duration),(!M||i.current.paused)&&c.a.createElement("i",{className:"icon-muted-chat"})))};a(233);var La=({message:e,onClick:t})=>c.a.createElement("div",{className:"InlineButtons"},e.inlineButtons.map(e=>c.a.createElement("div",{className:"row"},e.map(e=>c.a.createElement(oe.a,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>t({button:e})},e.text,"url"===e.type&&c.a.createElement("i",{className:"icon-arrow-right"}))))));a(234);var Fa=Object(c.h)(Object(s.h)((e,{message:t})=>{const{threadId:a,chatId:s}=t.threadInfo,n=Object(o.Cb)(e,s,a)||t.threadInfo,{byId:c}=e.users,{byId:r}=e.chats;return{threadInfo:n,usersById:c,chatsById:r}},(e,t)=>Object(d.l)(t,["openChat"]))(({disabled:e,threadInfo:t,usersById:a,chatsById:s,openChat:n})=>{const r=Object(ne.a)(),{threadId:o,chatId:i,messagesCount:l,lastMessageId:d,lastReadInboxMessageId:b,recentReplierIds:u}=t,h=Object(c.m)(()=>{n({id:i,threadId:o})},[n,i,o]);if(void 0===l)return;const O=u&&u.map(e=>Object(m.lb)(e)?a[e]:s[e]).filter(Boolean);const j=Boolean(b&&d&&b0&&c.a.createElement("div",{className:"recent-repliers",dir:r.isRtl?"rtl":"ltr"},O.map(e=>c.a.createElement(Gt.a,{key:e.id,size:"small",user:Object(m.lb)(e.id)?e:void 0,chat:Object(m.lb)(e.id)?void 0:e}))),c.a.createElement("div",{className:"label",dir:"auto"},l?r("Comments",l,"i"):r("LeaveAComment")),c.a.createElement("i",{className:"icon-next"}))}));a(235);function Da(e){const t=Ua(e.currentTarget);t&&t.setAttribute("data-is-document-group-hover","")}function Ba(e){const t=Ua(e.currentTarget);t&&t.removeAttribute("data-is-document-group-hover")}function Ua(e){let t=e;do{t=t.nextElementSibling}while(t&&!t.classList.contains("last-in-document-group"));return t}var Ha=Object(c.h)(Object(s.h)((e,t)=>{const{focusedMessage:a,forwardMessages:s,lastSyncTime:n}=e,{message:c,album:r,withSenderName:i,withAvatar:l,threadId:d,messageListType:b}=t,{id:u,chatId:h,viaBotId:O,replyToMessageId:j,isOutgoing:g}=c,f=Object(o.f)(e,h),p=Object(o.P)(e,h),I=f&&Object(m.jb)(f),v=!p&&Object(m.eb)(c),y=i||l||v?Object(o.tb)(e,c):void 0,C=Object(o.K)(e,c),E=O?Object(o.Gb)(e,O):void 0,w=d?Object(o.Eb)(e,h,d):void 0,M=c.id===w,S=j===w,k=j&&!S?Object(o.k)(e,h,j):void 0,N=k&&Object(o.tb)(e,k),P=Object(o.Fb)(e,c),T="thread"===b&&(r?r.messages.some(t=>Object(o.U)(e,t)):Object(o.U)(e,c)),{direction:A,noHighlight:x}=T&&a||{},R=s.messageIds&&s.messageIds.includes(u),{query:L}=Object(o.A)(e)||{},F=Object(m.L)(c);let D;return D=r&&r.messages?r.messages.every(({id:t})=>Object(o.V)(e,t)):Object(o.V)(e,u),{forceSenderName:v,sender:y,originSender:C,botSender:E,shouldHideReply:S,isThreadTop:M,replyMessage:k,replyMessageSender:N,...g&&{outgoingStatus:Object(o.fb)(e,c,"scheduled"===b)},..."number"==typeof P&&{uploadProgress:P},isFocused:T,...T&&{focusDirection:A,noFocusHighlight:x},isForwarding:R,isChatWithSelf:p,isChannel:I,lastSyncTime:n,highlight:L,isSingleEmoji:Boolean(F),animatedEmoji:F?Object(o.c)(e,F):void 0,isInSelectMode:Object(o.S)(e),isSelected:D,isGroupSelected:!!c.groupedId&&!c.isInAlbum&&Object(o.Q)(e,h,c.groupedId),threadId:d,isPinnedList:"pinned"===b,shouldAutoLoadMedia:f?Object(o.ub)(e,c,f,y):void 0,shouldAutoPlayMedia:Object(o.vb)(e,c),shouldLoopStickers:Object(o.wb)(e)}},(e,t)=>Object(d.l)(t,["focusMessage","openMediaViewer","openAudioPlayer","cancelSendingMessage","openUserInfo","openChat","markMessagesRead","sendPollVote","toggleMessageSelection","setReplyingToId","openForwardMenu","clickInlineButton"]))(({message:e,observeIntersectionForBottom:t,observeIntersectionForMedia:a,observeIntersectionForAnimatedStickers:s,album:n,withAvatar:r,withSenderName:o,noComments:d,appearanceOrder:b,isFirstInGroup:u,isLastInGroup:h,isFirstInDocumentGroup:O,isLastInDocumentGroup:j,isLastInList:g,forceSenderName:f,sender:p,originSender:I,botSender:v,isThreadTop:y,shouldHideReply:C,replyMessage:E,replyMessageSender:w,outgoingStatus:M,uploadProgress:S,isFocused:k,focusDirection:N,noFocusHighlight:P,isForwarding:T,isChatWithSelf:A,isChannel:x,lastSyncTime:R,highlight:L,animatedEmoji:F,isInSelectMode:D,isSelected:B,isGroupSelected:U,threadId:H,messageListType:G,isPinnedList:q,shouldAutoLoadMedia:_,shouldAutoPlayMedia:V,shouldLoopStickers:$,focusMessage:z,openMediaViewer:W,openAudioPlayer:K,openUserInfo:Q,openChat:Y,cancelSendingMessage:X,markMessagesRead:ee,sendPollVote:te,toggleMessageSelection:ae,setReplyingToId:se,openForwardMenu:ce,clickInlineButton:re})=>{const ie=Object(c.q)(null),le=Object(c.q)(null),de=Object(c.q)(null);Object(ft.c)(le,t);const{width:be}=_e(),{isContextMenuOpen:ue,contextMenuPosition:me,handleBeforeContextMenu:he,handleContextMenu:Oe,handleContextMenuClose:je,handleContextMenuHide:ge}=Object(Et.a)(ie,!1,!0),fe=b<=0,[pe,Ie]=Object(ot.a)(fe);Object(c.n)(()=>{fe||setTimeout(Ie,10*b)},[b,Ie,fe]);const{transitionClassNames:ve}=Object(Z.a)(pe,void 0,fe,!1),{chatId:ye,id:Ce,threadInfo:Ee}=e,we=Object(m.tb)(e),Me="scheduled"===G||e.isScheduled,Se=Object(m.ub)(e)&&!C,ke=Boolean(Ee)&&"thread"===G,{forwardInfo:Ne,viaBotId:Pe}=e,Te=Ne&&!A&&!Ne.isLinkedChannelPost,Ae=!!e.groupedId&&!e.isInAlbum,xe=Boolean(n)&&n.messages.length>1,{text:Re,photo:Le,video:Fe,audio:De,voice:Be,document:Ue,sticker:He,contact:Ge,poll:qe,webPage:Ve,invoice:$e}=Object(m.v)(e),ze=Object(m.x)(e),Ke=Object(wt.a)(e,L,Mt(ze)),Qe=void 0!==me,Ye=Object(J.a)("Message message-list-item",u&&"first-in-group",h&&"last-in-group",O&&"first-in-document-group",j&&"last-in-document-group",g&&"last-in-list",we&&"own",Boolean(e.views)&&"has-views",e.isEdited&&"was-edited",Se&&"has-reply",Qe&&"has-menu-open",k&&!P&&"focused",T&&"is-forwarding",e.isDeleting&&"is-deleting",Ae&&"is-in-document-group",xe&&"is-album",e.hasUnreadMention&&"has-unread-mention",B&&"is-selected",D&&"is-in-selection-mode",y&&"is-thread-top",Boolean(e.inlineButtons)&&"has-inline-buttons",ve),Xe=function(e,{hasReply:t,customShape:a,isLastInGroup:s,asForwarded:n,hasThread:c,forceSenderName:r,hasComments:o}={}){const{text:i,photo:l,video:d,audio:b,voice:u,document:h,poll:O,webPage:j,contact:g}=Object(m.v)(e),f=["message-content"],p=(l||d)&&!i,I=Boolean(e.viaBotId);return Mt(a)?f.push("emoji-only emoji-only-"+a):i&&f.push("text"),a&&(f.push("custom-shape"),d&&d.isRound&&f.push("round"),o&&f.push("has-comments")),l||d?f.push("media"):b?f.push("audio"):u?f.push("voice"):h?f.push("document"):g?f.push("contact"):O?f.push("poll"):j&&(f.push("web-page"),j.photo&&f.push("media")),n&&!a&&f.push("is-forwarded"),t&&f.push("is-reply"),c&&f.push("has-replies"),I&&f.push("is-via-bot"),r&&f.push("force-sender-name"),a||(f.push("has-shadow"),(t||n||!p||I||r)&&f.push("has-solid-background"),!s||!l&&p||f.push("has-appendix")),f.join(" ")}(e,{hasReply:Se,customShape:ze,isLastInGroup:h,asForwarded:Te,hasThread:ke,forceSenderName:f,hasComments:e.threadInfo&&e.threadInfo.messagesCount>0}),Je=!Ne||!A&&p?p:I,Ze=Ne?I:p,at=x&&e.adminTitle||Ne&&!Te&&Ne.adminTitle||void 0,st=e.threadInfo&&(!Ae||j)&&"thread"===G&&!d,nt=Xe.includes("has-appendix");Object(We.a)(ye,Se?e.replyToMessageId:void 0,E,e.id),Ht(ie,ye,k,N,P),Object(c.o)(()=>{de.current&&(de.current.innerHTML=we?'':'')},[we,nt]);const ct=Object(c.m)(t=>{t.stopPropagation(),ae({messageId:Ce,groupedId:e.groupedId})},[Ce,e.groupedId,ae]),rt=Object(c.m)(e=>{const t=xe&&n&&n.messages?{messageId:Ce,childMessageIds:n.messages.map(({id:e})=>e),withShift:e&&e.shiftKey}:{messageId:Ce,withShift:e&&e.shiftKey};ae(t)},[ae,Ce,xe,n]),it=Object(c.m)(()=>{se({messageId:Ce})},[se,Ce]),lt=Object(c.m)(e=>{e.stopPropagation()},[]),dt=Object(c.m)(()=>{Je&&(Object(m.lb)(Je.id)?Q({id:Je.id}):Y({id:Je.id}))},[Je,Q,Y]),bt=Object(c.m)(()=>{Ze&&(Object(m.lb)(Ze.id)?Q({id:Ze.id}):Y({id:Ze.id}))},[Ze,Q,Y]),ut=Object(c.m)(()=>{v&&Q({id:v.id})},[v,Q]),mt=Object(c.m)(()=>{z({chatId:ye,threadId:H,messageId:e.replyToMessageId})},[z,ye,H,e.replyToMessageId]),ht=Object(c.m)(()=>{W({chatId:ye,threadId:H,messageId:Ce,origin:Me?l.h.ScheduledInline:l.h.Inline})},[ye,H,Ce,W,Me]),Ot=Object(c.m)(()=>{K({chatId:ye,messageId:Ce})},[ye,Ce,K]),jt=Object(c.m)(e=>{W({chatId:ye,threadId:H,messageId:e,origin:Me?l.h.ScheduledAlbum:l.h.Album})},[ye,H,W,Me]),gt=Object(c.m)(()=>{ee({messageIds:[Ce]})},[Ce,ee]),pt=Object(c.m)(()=>{X({chatId:ye,messageId:Ce})},[X,ye,Ce]),It=Object(c.m)(e=>{te({chatId:ye,messageId:Ce,options:e})},[ye,Ce,te]),vt=Object(c.m)(()=>{ce({fromChatId:ye,groupedId:e.groupedId})},[ce,ye,e.groupedId]),yt=Object(c.m)(()=>{if(n&&n.messages){const e=n.messages.map(({id:e})=>e);ce({fromChatId:ye,messageIds:e})}else ce({fromChatId:ye,messageIds:[Ce]})},[n,ce,ye,Ce]),Ct=Object(c.m)(()=>{z({chatId:ye,threadId:i.MAIN_THREAD_ID,messageId:Ce})},[z,ye,Ce]),Nt=Object(c.m)(()=>{z(Ae?{chatId:Ne.fromChatId,groupedId:e.groupedId,groupedChatId:ye}:{chatId:Ne.fromChatId,messageId:Ne.fromMessageId})},[z,Ne,e,ye,Ae]),Pt=Object(ne.a)();let Tt,At="",xt=!1;const Rt=Object(c.p)(()=>xe?Dt(we,Boolean(Te),n,be):void 0,[xe,be,we,Te,n]),Lt=Te?28:0;if(xe||!Le&&!Fe)Rt&&(Tt=Math.max(St(Boolean(Re),st),Rt.containerStyle.width),Tt-Rt.containerStyle.width>18&&(xt=!0));else{let t;Le?t=kt(e).width:Fe&&(t=Fe.isRound?et.d:kt(e).width),t&&(Tt=Math.max(St(Boolean(Re),st),t),Tt-t>18&&(xt=!0))}Tt&&(At=`width: ${Tt+Lt}px`);const Ft=Object(c.p)(()=>at?Ut(at):void 0,[at]),Bt=!(Qe||D||T)&&(!Ae||j),qt=Bt&&x&&!Me,Vt=Bt&&(Ne&&(Ne.isChannelPost||A&&!we)&&Ne.fromMessageId||q);return c.a.createElement("div",{ref:ie,id:"message"+Ce,className:Ye,style:Ft?`--meta-safe-author-width: ${Ft}px`:void 0,"data-message-id":Ce,onClick:D?rt:void 0,onDoubleClick:D?void 0:it,onMouseDown:D?void 0:he,onContextMenu:D?void 0:Oe,onMouseEnter:Ae&&!j?Da:void 0,onMouseLeave:Ae&&!j?Ba:void 0},c.a.createElement("div",{ref:le,className:"bottom-marker","data-message-id":Ce,"data-last-message-id":n?n.messages[n.messages.length-1].id:void 0,"data-has-unread-mention":e.hasUnreadMention}),!Ae&&c.a.createElement("div",{className:"message-select-control"},B&&c.a.createElement("i",{className:"icon-select"})),j&&c.a.createElement("div",{className:Object(J.a)("message-select-control group-select",U&&"is-selected"),onClick:ct},U&&c.a.createElement("i",{className:"icon-select"})),r&&function(){const e=Je&&Object(m.lb)(Je.id),t=Je&&e?Je:void 0,a=Je&&!e?Je:void 0,s=!Je&&Ne?Ne.hiddenUserName:void 0;return c.a.createElement(Gt.a,{size:"small",user:t,chat:a,text:s,lastSyncTime:R,onClick:t||a?dt:void 0})}(),c.a.createElement("div",{className:"message-content-wrapper",onClick:D&&Ae?rt:void 0},c.a.createElement("div",{className:Xe,style:At,dir:"auto"},nt&&c.a.createElement("div",{className:"svg-appendix",ref:de}),Te&&!ze&&(!Ae||O)&&c.a.createElement("div",{className:"message-title"},Pt("ForwardedMessage")),function(){const t=Object(J.a)("content-inner",Te&&!ze&&"forwarded-message",Se&&"reply-message",xt&&"no-media-corners"),r=h&&!Ke&&!Te&&!ke,i=!Ve&&!F&&Ke;return c.a.createElement("div",{className:t,onDoubleClick:lt,dir:"auto"},function(){if(ze||!(o&&!Le&&!Fe||Te||Pe||f)||Ae&&!O)return;let t,a;Ze?(t=Object(m.V)(Pt,Ze),Te||(a="color-"+Object(m.X)(Ze))):Ne&&Ne.hiddenUserName&&(t=Ne.hiddenUserName);return c.a.createElement("div",{className:"message-title",dir:"ltr"},t?c.a.createElement("span",{className:Object(J.a)(Ze&&"interactive",a),onClick:Ze?bt:void 0,dir:"auto"},Object(tt.a)(t)):v?void 0:" ",v&&c.a.createElement(c.a.Fragment,null,c.a.createElement("span",{className:"via"},Pt("ViaBot")),c.a.createElement("span",{className:"interactive",onClick:ut},Object(tt.a)("@"+v.username))),Ne&&Ne.isLinkedChannelPost?c.a.createElement("span",{className:"admin-title",dir:"auto"},Pt("DiscussChannel")):e.adminTitle&&!x?c.a.createElement("span",{className:"admin-title",dir:"auto"},e.adminTitle):void 0)}(),Se&&c.a.createElement($t,{message:E,sender:w,observeIntersection:a,onClick:mt}),He&&c.a.createElement(Zt,{message:e,observeIntersection:a,observeIntersectionForPlaying:s,shouldLoop:$,lastSyncTime:R}),F&&c.a.createElement(ea.a,{isInline:!0,sticker:F,observeIntersection:a,lastSyncTime:R}),xe&&c.a.createElement(Ta,{album:n,albumLayout:Rt,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:V,isOwn:we,hasCustomAppendix:r,lastSyncTime:R,onMediaClick:jt}),!xe&&Le&&c.a.createElement(oa,{message:e,observeIntersection:a,shouldAutoLoad:_,uploadProgress:S,shouldAffectAppendix:r,onClick:ht,onCancelUpload:pt}),!xe&&Fe&&Fe.isRound&&c.a.createElement(Ra,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:V,lastSyncTime:R}),!xe&&Fe&&!Fe.isRound&&c.a.createElement(ha,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:V,uploadProgress:S,lastSyncTime:R,onClick:ht,onCancelUpload:pt}),(De||Be)&&c.a.createElement(Wt.a,{message:e,uploadProgress:S,lastSyncTime:R,isSelectable:Ae,isSelected:B,onPlay:Ot,onReadMedia:!Be||we&&!A?void 0:gt,onCancelUpload:pt}),Ue&&c.a.createElement(zt.a,{message:e,observeIntersection:a,uploadProgress:S,isSelectable:Ae,isSelected:B,onCancelUpload:pt}),Ge&&c.a.createElement(ja,{contact:Ge}),qe&&c.a.createElement(Ca,{message:e,poll:qe,onSendVote:It}),!F&&Ke&&c.a.createElement("p",{className:"text-content "+(i?"with-meta":""),dir:"auto"},Ke,i&&c.a.createElement(Qt,{message:e,outgoingStatus:M,signature:at,onClick:rt})),Ve&&c.a.createElement(Ma,{message:e,observeIntersection:a,shouldAutoLoad:_,onMediaClick:ht,onCancelMediaTransfer:pt}),$e&&c.a.createElement(Sa,{message:e}))}(),(!Ae||j)&&!(!Ve&&!F&&Ke)&&c.a.createElement(Qt,{message:e,outgoingStatus:M,signature:at,onClick:rt}),qt?c.a.createElement(oe.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:Pt("lng_context_forward_msg"),onClick:j?vt:yt},c.a.createElement("i",{className:"icon-share-filled"})):Vt?c.a.createElement(oe.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:q?Ct:Nt},c.a.createElement("i",{className:"icon-arrow-right"})):void 0,st&&c.a.createElement(Fa,{message:e,disabled:d}),Xe.includes("has-appendix")&&c.a.createElement("div",{className:"svg-appendix",ref:de})),e.inlineButtons&&c.a.createElement(La,{message:e,onClick:re})),me&&c.a.createElement(_t,{isOpen:ue,anchor:me,message:e,album:n,messageListType:G,onClose:je,onCloseAnimationEnd:ge}))}));a(236);const Ga=h.b?1e3:350,qa=h.g?300:500,_a=Object(g.a)(e=>e(),200,!1);var Va=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,type:s})=>{const n=Object(o.f)(e,t);if(!n)return{};const c=Object(o.x)(e,t,a,s),r="scheduled"===s?Object(o.qb)(e,t):Object(o.m)(e,t),l=Object(o.Eb)(e,t,a);if(a!==i.MAIN_THREAD_ID&&!(r&&l&&r[l]))return{};const{isRestricted:d,restrictionReason:b,lastMessage:u}=n,h=Object(o.I)(e,t),O=a===i.MAIN_THREAD_ID&&!c&&!n.unreadCount&&!h&&u&&!u.groupedId;let j;if(Object(o.L)(e,t)){const a=Object(o.g)(e,t);j=a.fullInfo?a.fullInfo.botDescription||"NoMessages":"Updating bot info..."}return{isChatLoaded:!0,isRestricted:d,restrictionReason:b,isChannelChat:Object(m.jb)(n),isChatWithSelf:Object(o.P)(e,t),messageIds:c,messagesById:r,firstUnreadId:Object(o.H)(e,t,a),isViewportNewest:"thread"!==s||Object(o.X)(e,t,a),threadFirstMessageId:Object(o.G)(e,t,a),focusingId:h,isSelectModeActive:Object(o.S)(e),animationLevel:e.settings.byKey.animationLevel,...O&&{lastMessage:u},botDescription:j,threadTopMessageId:l,hasLinkedChat:n.fullInfo&&"linkedChatId"in n.fullInfo?Boolean(n.fullInfo.linkedChatId):void 0}},(e,t)=>Object(d.l)(t,["loadViewportMessages","markMessageListRead","markMessagesRead","setScrollOffset","openHistoryCalendar"]))(({chatId:e,threadId:t,type:a,hasTools:r,onFabToggle:i,onNotchToggle:b,isChatLoaded:u,isChannelChat:h,canPost:O,isChatWithSelf:j,messageIds:f,messagesById:p,firstUnreadId:I,isViewportNewest:v,threadFirstMessageId:y,isRestricted:C,restrictionReason:E,focusingId:w,isSelectModeActive:M,animationLevel:S,loadViewportMessages:k,markMessageListRead:N,markMessagesRead:P,setScrollOffset:T,lastMessage:A,botDescription:R,threadTopMessageId:L,hasLinkedChat:F,openHistoryCalendar:D})=>{const B=Object(c.q)(null),U=Object(c.q)("thread"===a&&Object(o.rb)(Object(s.e)(),e,t)||0),H=Object(c.q)(),G=Object(c.q)(),q=Object(c.q)(),_=Object(c.q)(),V=Object(c.q)(),$=Object(c.q)(),z=Object(c.q)(!1),W=Object(c.q)(!f),[K,Q]=Object(c.r)(),[Y,Z]=Object(c.r)(Boolean(w)),ee=Boolean(f);Object(je.a)(()=>{ee&&Object(g.d)(()=>{W.current=!1})},[ee]),Object(je.a)(()=>{V.current=I,_.current||(_.current=I)},[I]);const{observe:te,freeze:ae,unfreeze:se}=Object(ft.a)({rootRef:B,throttleMs:Ga,margin:qa}),{observe:ce,freeze:re,unfreeze:oe}=Object(ft.a)({rootRef:B},e=>{if("thread"!==a)return;let t=0;const s=[];e.forEach(e=>{const{isIntersecting:a,target:n}=e;if(!a)return;const{dataset:c}=n,r=Number(c.lastMessageId||c.messageId);r>t&&(t=r),c.hasUnreadMention&&s.push(r)}),V.current&&t>=V.current&&N({maxId:t}),s.length&&P({messageIds:s})});Object(je.a)(()=>{$.current=w,w?(ae(),re()):(oe(),se())},[w]);const{observe:ie}=Object(ft.a)({rootRef:B,throttleMs:Ga});Object(c.n)(()=>{w?Z(!0):setTimeout(()=>{Z(!1)},200)},[w]);const le=Object(c.p)(()=>{if(!f||!p)return;const e=!L||f[0]&&y!==f[0]?f:[L,...f];if(!e.length)return;const t=e.map(e=>p[e]);return gt(Object(d.k)(t,["date","id"]),_.current)},[f,p,y,L]),[de,be,ue]=Object(c.p)(()=>"thread"===a?[Object(g.a)(()=>k({direction:l.e.Backwards}),1e3,!0,!1),Object(g.a)(()=>k({direction:l.e.Forwards}),1e3,!0,!1),Object(g.a)(()=>k({direction:l.e.Around}),1e3,!0,!1)]:[],[k,f]),{isScrolled:me,updateStickyDates:he}=pt(),Oe=Object(c.m)(()=>{if(z.current)return void(z.current=!1);const s=B.current;$.current||he(s,r),_a(()=>{Object(g.b)(()=>{s.parentElement&&(U.current=s.scrollHeight-s.scrollTop,"thread"===a&&T({chatId:e,threadId:t,scrollOffset:U.current}))})})},[he,r,a,T,e,t]);Object(c.n)(()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver(([e])=>{e.target.offsetParent&&Q(e.contentRect.height)});return e.observe(B.current),()=>{e.disconnect()}},[]);const{height:ge}=_e();Object(c.n)(()=>{B.current.dataset.normalHeight=String(B.current.offsetHeight)},[ge]),Object(c.n)(()=>{if(!ue||!u||C||w)return;const e=B.current;(!f||f.length{if(!f||!q.current)return;const e=q.current.filter(e=>f.includes(Number(e.dataset.messageId))),t=e[1]||e[0];t&&(H.current=t.id,G.current=t.getBoundingClientRect().top)},[f,v,K,r]),Object(Ot.a)(([e,t,a])=>{const s=B.current;if(q.current=Array.from(s.querySelectorAll(".message-list-item")),!s.offsetParent)return;const c=v&&f&&f.length{s.parentElement&&s.parentElement.classList.remove("force-messages-scroll")},1e3));const{scrollTop:o,scrollHeight:i,offsetHeight:l}=s,d=U.current,b=q.current[q.current.length-1],u=b?b.offsetHeight:0,m=v&&t&&d-(a||l)-u<=100;let h;const O=f&&e&&f[0]!==e[0],j=f&&e&&f[f.length-1]!==e[e.length-1],p=f&&$.current===f[f.length-1];if(m&&j&&!O&&!p&&(b&&Object(g.b)(()=>{Object(vt.a)(s,b,"end",20,void 0,void 0,void 0,!0)}),h=i-l,U.current=Math.max(i-h,l),!c))return;const I=void 0!==a&&a!==K,y=H.current&&s.querySelector("#"+H.current),C=!y&&_.current&&s.querySelector(".unread-divider");if(m&&I){if(Object(vt.b)())return;h=i-l}else if(y){h=o+(y.getBoundingClientRect().top-(G.current||0))}else h=C?C.offsetTop-(r?60:10):i-d;Object(It.a)(s,h),$.current||(z.current=!0,Object(g.b)(()=>{z.current=!1})),U.current=Math.max(i-h,l)},[f,v,K,r]),Object(c.n)(()=>{(!S||S>0)&&Object(X.b)(200+n.c)},[S,M]);const fe=Object(ne.a)(),pe=Boolean(e&&Object(m.lb)(e)),Ie=Boolean(!pe&&!h||j),ve=Object(J.a)("MessageList custom-scroll",!Ie&&"no-avatars",h&&"no-avatars",!O&&"no-composer","pinned"===a&&"type-pinned",M&&"select-mode-active",Y&&"has-focusing",me&&"scrolled");return c.a.createElement("div",{ref:B,className:ve,onScroll:Oe},C?c.a.createElement("div",{className:"empty"},c.a.createElement("span",null,E?E.text:"This is a private "+(h?"channel":"chat"))):R?c.a.createElement("div",{className:"empty rich"},c.a.createElement("span",null,Object(tt.a)(fe(R),["br","emoji","links"]))):f&&!le?c.a.createElement("div",{className:"empty"},c.a.createElement("span",null,fe("NoMessages"))):f&&le||A?c.a.createElement(Ct,{containerRef:B,className:"messages-container",messageIds:f||[A.id],focusingId:w,loadMoreForwards:be,loadMoreBackwards:de,isViewportNewest:v,firstUnreadId:I,onFabToggle:i,onNotchToggle:b},function(e,t,a,s,r,o,i,l,b,u,h,O,j,g,f,p){const I=c.a.createElement("div",{className:Object(J.a)("unread-divider","local-action-message"),key:"unread-messages"},c.a.createElement("span",null,e("UnreadMessages"))),v=f?0:t.reduce((e,t)=>e+Object(d.h)(t.senderGroups).length,0);let y=0;const C=t.map((t,O,f)=>{const C=t.senderGroups.map((t,n,g)=>{if(1===t.length&&!jt(t[0])&&Object(m.db)(t[0])){const e=t[0],s=n===g.length-1&&O===f.length-1;return Object(d.e)([e.id===l.current&&I,c.a.createElement(Vt,{key:e.id,message:e,observeIntersection:a,appearanceOrder:v-++y,isLastInList:s})])}let p;return Object(d.h)(t.map((C,E)=>{const w=jt(C)?C.mainMessage:C,M=jt(C)?C:void 0,S=Object(m.tb)(w),k=jt(C),N=t[E+1];w.previousLocalId&&i.current==="message"+w.previousLocalId&&(i.current="message"+w.id);const P=!k&&w.groupedId?w.groupedId:void 0,T=N&&!jt(N)?N.groupedId:void 0,A={isFirstInGroup:0===E,isLastInGroup:E===t.length-1,isFirstInDocumentGroup:Boolean(P&&P!==p),isLastInDocumentGroup:Boolean(P&&P!==T),isLastInList:E===t.length-1&&n===g.length-1&&O===f.length-1};p=P;const x=Object(m.F)(w),R="scheduled"!==u?x:`${w.date}_${x}`;return Object(d.e)([w.id===l.current?I:void 0,c.a.createElement(Ha,{key:R,message:w,observeIntersectionForBottom:a,observeIntersectionForMedia:s,observeIntersectionForAnimatedStickers:r,album:M,withAvatar:A.isLastInGroup&&o&&!S&&!(w.id===h),withSenderName:A.isFirstInGroup&&o&&!S,threadId:b,messageListType:u,noComments:!1===j,appearanceOrder:v-++y,isFirstInGroup:A.isFirstInGroup,isLastInGroup:A.isLastInGroup,isFirstInDocumentGroup:A.isFirstInDocumentGroup,isLastInDocumentGroup:A.isLastInDocumentGroup,isLastInList:A.isLastInList}),w.id===h&&c.a.createElement("div",{className:"local-action-message",key:"discussion-started"},c.a.createElement("span",null,e("DiscussionStarted")))])}))});return c.a.createElement("div",{className:"message-date-group",key:t.datetime,teactFastList:!0},c.a.createElement("div",{className:Object(J.a)("sticky-date",!g&&"interactive"),key:"date-header",onClick:g?void 0:()=>p({selectedAt:t.datetime})},c.a.createElement("span",{dir:"auto"},g&&t.originalDate===n.lb&&e("MessageScheduledUntilOnline"),g&&t.originalDate!==n.lb&&e("MessageScheduledOn",Object(x.c)(e,t.datetime,void 0,!0)),!g&&Object(x.c)(e,t.datetime))),Object(d.h)(C))});return Object(d.h)(C)}(fe,le||gt([A]),ce,te,ie,Ie,H,_,t,a,L,0,Boolean(F),!!le&&"scheduled"===a,!le||!W.current,D)):c.a.createElement(Ee.a,{color:"white"}))}));a(237);var $a=Object(c.h)(Object(s.h)(e=>{const t=Object(o.y)(e);if(!t)return{};const{chatId:a,threadId:s,type:n}=t,c=Object(o.f)(e,a);return{messageListType:n,unreadCount:c&&s===i.MAIN_THREAD_ID&&"thread"===n?c.unreadCount:void 0}},(e,t)=>Object(d.l)(t,["focusLastMessage"]))(({isShown:e,canPost:t,messageListType:a,unreadCount:s,focusLastMessage:n})=>{const r=Object(ne.a)(),o=Object(c.q)(null),i=Object(c.m)(()=>{if(e)if("thread"===a)n();else{const e=o.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),a=t[t.length-1];if(!a)return;Object(vt.a)(e,a,"end",20)}},[e,a,n]),l=Object(J.a)("ScrollDownButton",e&&"revealed",!t&&"no-composer");return c.a.createElement("div",{ref:o,className:l},c.a.createElement("div",{className:"ScrollDownButton-inner"},c.a.createElement(oe.a,{color:"secondary",round:!0,onClick:i,ariaLabel:r("AccDescrPageDown")},c.a.createElement("i",{className:"icon-arrow-down"})),Boolean(s)&&c.a.createElement("div",{className:"unread-count"},Object(Qe.b)(s))))})),za=a(129),Wa=a(138);async function Ka(e,t,a,s){const n=URL.createObjectURL(t),{type:c,size:r}=t;let o,i;if(c.startsWith("image/"))if(a){const a=await Object(Ge.g)(n),{width:r,height:i}=a;if(r>1280||i>1280||"image/jpeg"!==c){const c=await function(e){return new Promise(t=>{const a=document.createElement("canvas"),s=a.getContext("2d");let{width:n,height:c}=e;(n>1280||c>1280)&&(n>=c?(c*=1280/n,n=1280):(n*=1280/c,c=1280)),a.width=n,a.height=c,s.drawImage(e,0,0,e.width,e.height,0,0,n,c),a.toBlob(t,"image/jpeg",100)})}(a);return c?(URL.revokeObjectURL(n),Ka(e,c,!0,s)):Ka(e,t,!1,s)}o={width:r,height:i}}else i=n;else if(c.startsWith("video/")){if(r<10485760){const{videoWidth:e,videoHeight:t,duration:a}=await Object(Ge.h)(n);o={width:e,height:t,duration:a}}i=await Object(Ge.c)(n)}return{blobUrl:n,filename:e,mimeType:c,size:r,quick:o,previewBlobUrl:i,...s}}var Qa=a(181),Ya=a.p+"8ccc0b555efcec3616377aea078dda16.js";const Xa={encoderPath:Ya,reuseWorker:!0},Ja={type:"audio/ogg"};let Za,es,ts;async function as(){return Za||(Za=a.e(9).then(a.t.bind(null,316,7)),es=(await Za).default,ts=new es(Xa)),Za}async function ss(e){await async function(){await as(),await ts.start()}();const t=Date.now();let a;const s=[],n=[];ts.ondataavailable=e=>{s.push(e)};const c=function(e,t){const a=e.sourceNode,s=a.context.createAnalyser();s.fftSize=64,a.connect(s);const n=s.frequencyBinCount,c=new Uint8Array(n);let r=!1;return function e(){if(r)return;s.getByteFrequencyData(c);const a=c.reduce((e,t)=>e+t,0),o=a/n/255;t(o<.1?0:o),requestAnimationFrame(e)}(),()=>{r=!0}}(ts,t=>{n.push(255*t),e(t)});return{stop:()=>new Promise((e,r)=>{ts.onstop=()=>{e({blob:new Blob(s,Ja),duration:Math.round(((a||Date.now())-t)/1e3),waveform:n})},ts.onerror=r;const o=Math.max(0,t+1e3-Date.now());setTimeout(()=>{ts.stop(),c()},o)}),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout(()=>{ts.pause(),a=Date.now(),c()},e)}}}const ns=["image/png","image/jpeg","image/gif"];function cs(e){const{text:t,entities:a}=e||{};if(!t)return"";const s=Object(wt.b)(t,a,void 0,void 0,!0);return Array.isArray(s)?s.join(""):s}let rs,os;var is=a(64);var ls=a(182),ds=a(190);var bs=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"DeleteMessageModal",!t);return a?c.a.createElement(a,e):void 0});function us(){return(us=Object.assign||function(e){for(var t=1;t{const a=Object(c.q)(!1),s=Object(c.m)(()=>{if(a.current=!0,hs)return hs=!1,void e();ms&&(clearTimeout(ms),ms=void 0),ms=window.setTimeout(()=>{a.current&&e()},200)},[e]),n=Object(c.m)(()=>{a.current=!1},[]);return c.a.createElement(oe.a,us({},t,{onMouseEnter:h.l?void 0:s,onMouseLeave:h.l?void 0:n,onClick:h.l?e:void 0}))});var js=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"AttachMenu",!t);return a?c.a.createElement(a,e):void 0});var gs=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"SymbolMenu",!t);return a?c.a.createElement(a,e):void 0});var fs=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"MentionTooltip",!t);return a?c.a.createElement(a,e):void 0});var ps=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"CustomSendMenu",!t);return a?c.a.createElement(a,e):void 0});var Is=e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"StickerTooltip",!t);return a?c.a.createElement(a,e):void 0},vs=a(183);var ys=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"BotKeyboardMenu",!t);return a?c.a.createElement(a,e):void 0}),Cs=a(184),Es=a(119);a(239);var ws=Object(c.h)(Object(s.h)(e=>{const{chatId:t,threadId:a,type:s}=Object(o.y)(e)||{};if(!t||!a||!s)return{};const{currentUserId:n,forwardMessages:{fromChatId:c,toChatId:r,messageIds:i}}=e,l=Object(o.mb)(e,t,a),d="scheduled"===s?Object(o.E)(e,t):Object(o.C)(e,t,a),b=e.settings.byKey.animationLevel>=1,u=r===t;let h,O;if(l?h=Object(o.k)(e,t,l):d?h=Object(o.D)(e,t,a,s):u&&1===i.length&&(h=Object(o.k)(e,c,i[0])),l&&h){const{forwardInfo:a}=h,s=t===n;a&&(a.isChannelPost||s)&&(O=Object(o.K)(e,h)),O||(O=Object(o.tb)(e,h))}else u&&(O=Object(m.lb)(c)?Object(o.Gb)(e,c):Object(o.f)(e,c));return{replyingToId:l,editingId:d,message:h,sender:O,shouldAnimate:b,forwardedMessagesCount:u?i.length:void 0}},(e,t)=>Object(d.l)(t,["setReplyingToId","setEditingId","focusMessage","exitForwardMode"]))(({replyingToId:e,editingId:t,message:a,sender:s,shouldAnimate:n,forwardedMessagesCount:r,setReplyingToId:o,setEditingId:i,focusMessage:l,exitForwardMode:d})=>{const b=Boolean((e||t)&&a||s&&r),u=Object(Es.a)([r],r?300:void 0),{shouldRender:m,transitionClassNames:h}=Object(Z.a)(u&&b,void 0,!n,void 0,!n),O=Object(c.m)(()=>{e?o({messageId:void 0}):t?i({messageId:void 0}):r&&d()},[e,t,r,o,i,d]);Object(c.n)(()=>b?Object(te.a)(O):void 0,[b,O]);const j=Object(c.m)(()=>{l({chatId:a.chatId,messageId:a.id})},[l,a]),g=Object(J.a)("ComposerEmbeddedMessage",h),f=r&&r>1?r+" forwarded messages":void 0;if(m)return c.a.createElement("div",{className:g},c.a.createElement("div",null,c.a.createElement(oe.a,{round:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:O},c.a.createElement("i",{className:"icon-close"})),c.a.createElement($t,{className:"inside-input",message:a,sender:s,customText:f,title:t?"Edit Message":void 0,onClick:j})))}));var Ms=Object(c.h)(e=>{const{attachments:t}=e,a=Object(Ce.a)(ye.a.Extra,"AttachmentModal",!t.length);return a?c.a.createElement(a,e):void 0});var Ss=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"PollModal",!t);return a?c.a.createElement(a,e):void 0});var ks=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"DropArea",!t);return a?c.a.createElement(a,e):void 0});a(240);const Ns=new RegExp(n.gb,"i");var Ps=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a})=>{const s=Object(o.cb)(e,t,a);return{webPagePreview:e.webPagePreview,noWebPage:s}},(e,t)=>Object(d.l)(t,["loadWebPagePreview","clearWebPagePreview","toggleMessageWebPage"]))(({chatId:e,threadId:t,messageText:a,disabled:s,webPagePreview:n,noWebPage:r,loadWebPagePreview:o,clearWebPagePreview:l,toggleMessageWebPage:d})=>{const b=Object(c.p)(()=>{const{text:e,entities:t}=Object(Wa.a)(a),s=t&&t.find(({type:e})=>e===i.ApiMessageEntityTypes.TextUrl);if(s)return s.url;const n=e.match(Ns);return n?n[0]:void 0},[a]);Object(c.n)(()=>{b?o({text:b}):(l(),d({chatId:e,threadId:t}))},[e,d,l,b,o,t]),Object(je.a)(()=>{l(),d({chatId:e,threadId:t})},[e]);const u=Boolean(n&&a.length&&!r&&!s),{shouldRender:m,transitionClassNames:h}=Object(Z.a)(u),O=Object(Ke.a)(n);if(!m||!O)return;const{photo:j,...g}=O,f={content:{webPage:g}};return c.a.createElement("div",{className:Object(J.a)("WebPagePreview",h)},c.a.createElement("div",null,c.a.createElement(oe.a,{round:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{d({chatId:e,threadId:t,noWebPage:!0})}},c.a.createElement("i",{className:"icon-close"})),c.a.createElement(Ma,{message:f,inPreview:!0})))})),Ts=a(122);var As=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"CalendarModal",!t);return a?c.a.createElement(a,e):void 0});var xs=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"PaymentModal",!t);return a?c.a.createElement(a,e):void 0});var Rs,Ls=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"ReceiptModal",!t);return a?c.a.createElement(a,e):void 0});a(241);!function(e){e.Send="send",e.Record="record",e.Edit="edit"}(Rs||(Rs={}));var Fs=Object(c.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const n=Object(o.f)(e,t),c=n&&Object(o.o)(e,n),r=n?Object(o.O)(e,n):void 0,l=Object(o.P)(e,t),d=r&&Object(o.bb)(e,t),b=Object(o.ob)(e,t),{language:u}=e.settings.byKey,h=Object(o.F)(e,u);return{editingMessage:Object(o.D)(e,t,a,s),connectionState:e.connectionState,draft:Object(o.B)(e,t,a),chat:n,isChatWithBot:r,isChatWithSelf:l,canScheduleUntilOnline:!l&&!r&&n&&c&&Object(m.lb)(t)&&c.status&&Boolean(c.status.wasOnline),isRightColumnShown:Object(o.W)(e),isSelectModeActive:Object(o.S)(e),withScheduledButton:a===i.MAIN_THREAD_ID&&"thread"===s&&Boolean(b&&b.length),shouldSchedule:"scheduled"===s,botKeyboardMessageId:d?d.id:void 0,isForwarding:t===e.forwardMessages.toChatId,canSuggestMembers:n&&Object(m.kb)(n),isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:n&&n.fullInfo&&n.fullInfo.members,currentUserId:e.currentUserId,usersById:e.users.byId,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),shouldSuggestStickers:e.settings.byKey.shouldSuggestStickers,recentEmojis:e.recentEmojis,language:u,emojiKeywords:h?h.keywords:void 0}},(e,t)=>Object(d.l)(t,["sendMessage","editMessage","saveDraft","clearDraft","showError","setStickerSearchQuery","setGifSearchQuery","forwardMessages","openPollModal","closePollModal","closePaymentModal","clearReceipt","loadScheduledHistory","openChat","addRecentEmoji","loadEmojiKeywords"]))(({dropAreaState:e,shouldSchedule:t,canScheduleUntilOnline:a,onDropHide:r,editingMessage:o,chatId:l,threadId:d,messageListType:b,draft:u,chat:O,connectionState:j,isChatWithBot:f,isChatWithSelf:p,isRightColumnShown:I,isSelectModeActive:v,isForwarding:y,canSuggestMembers:C,isPollModalOpen:E,isPaymentModalOpen:w,isReceiptModalOpen:M,botKeyboardMessageId:S,withScheduledButton:k,stickersForEmoji:N,groupChatMembers:P,currentUserId:T,usersById:A,lastSyncTime:R,contentToBeScheduled:L,shouldSuggestStickers:F,language:D,emojiKeywords:B,recentEmojis:U,sendMessage:H,editMessage:G,saveDraft:q,clearDraft:_,showError:V,setStickerSearchQuery:$,setGifSearchQuery:z,forwardMessages:W,openPollModal:K,closePollModal:Q,loadScheduledHistory:Y,closePaymentModal:X,openChat:Z,clearReceipt:ee,addRecentEmoji:ae,loadEmojiKeywords:se})=>{const ce=Object(c.q)(null),[re,ie]=Object(c.r)(""),le=Object(c.q)(),de=Object(na.a)(e),[be,ue,he]=Object(ot.a)(),[Oe,je]=Object(c.r)(),ge=Object(c.q)(re);Object(c.n)(()=>{ge.current=re},[re]),Object(c.n)(()=>{le.current=void 0},[l]),Object(c.n)(()=>{l&&R&&d===i.MAIN_THREAD_ID&&Y()},[l,Y,R,d]),Object(c.o)(()=>{ce.current&&(ce.current.innerHTML='')},[]),Object(c.n)(()=>{L&&(je(L),ue())},[L,ue]);const[fe,pe]=Object(c.r)([]),[Ie,ve,ye]=Object(ot.a)(),[Ce,Ee,we]=Object(ot.a)(),[Me,Se,ke]=Object(ot.a)(),[Ne,Pe,Te]=Object(ot.a)(),[Ae,xe]=Object(ot.a)(),[Re,Le,Fe]=Object(ot.a)(),{startRecordingVoice:De,stopRecordingVoice:Be,pauseRecordingVoice:He,activeVoiceRecording:Ge,currentRecordTime:qe,recordButtonRef:_e,startRecordTimeRef:Ve}=(()=>{const e=Object(c.q)(null),[t,a]=Object(c.r)(),s=Object(c.q)(),[n,r]=Object(c.r)();Object(c.n)(()=>{h.e&&as()},[]);const o=Object(c.m)(async()=>{try{const{stop:t,pause:n}=await ss(t=>{e.current&&(s.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),r(Date.now()))});s.current=Date.now(),r(Date.now()),a({stop:t,pause:n})}catch(e){console.error(e)}},[]),i=Object(c.m)(()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}},[t]),l=Object(c.m)(()=>{if(t){a(void 0),s.current=void 0,r(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}},[t]);return Object(c.n)(()=>t?Object(te.a)(l):void 0,[t,l]),{startRecordingVoice:o,pauseRecordingVoice:i,stopRecordingVoice:l,activeVoiceRecording:t,currentRecordTime:n,recordButtonRef:e,startRecordTimeRef:s}})(),$e=o?Rs.Edit:!h.m||Ge||re&&!fe.length||y?Rs.Send:Rs.Record,ze=!t,{isMentionTooltipOpen:We,mentionFilter:Ke,closeMentionTooltip:Qe,insertMention:Ye,mentionFilteredMembers:Xe}=Object(ds.a)(C&&!fe.length,re,ie,void 0,P,T,A),{isContextMenuOpen:Je,handleContextMenu:Ze,handleContextMenuClose:et,handleContextMenuHide:at}=Object(Et.a)(_e,!($e===Rs.Send&&ze)),st=Object(c.p)(()=>Object(m.c)(O,f),[O,f]),nt=O&&Object(m.gb)(O),ct=Object(m.k)(O),{isStickerTooltipOpen:rt,closeStickerTooltip:it}=function(e,t,a){const{loadStickersForEmoji:n,clearStickersForEmoji:r}=Object(s.d)(),o=h.d&&1===Object(is.a)(t)||!h.d&&Boolean(t.match(/^]*?>$/g)),i=Boolean(a)&&o;return Object(c.n)(()=>{e&&o?n({emoji:t}):!i&&o||r()},[t,o,r,n,e]),{isStickerTooltipOpen:i,closeStickerTooltip:r}}(Boolean(F&&st.canSendStickers&&!fe.length),re,N),{isEmojiTooltipOpen:lt,closeEmojiTooltip:dt,filteredEmojis:bt,insertEmoji:ut}=Object(ls.a)(Boolean(F&&st.canSendStickers&&!fe.length),re,U,void 0,ie,B),mt=Object(c.m)((e,t=n.v)=>{const a=window.getSelection(),s=document.getElementById(t),c=Object(tt.a)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(a.rangeCount){const t=a.getRangeAt(0);if(Object(Qa.a)(t))return void(h.d?document.execCommand("insertText",!1,e):(!function(e){const t=window.getSelection();if(t&&t.getRangeAt&&t.rangeCount){const a=t.getRangeAt(0);a.deleteContents();const s=a.createContextualFragment(e),n=s.lastChild;a.insertNode(s),n&&(a.setStartAfter(n),a.setEndAfter(n),t.removeAllRanges(),t.addRange(a))}}(c),s.dispatchEvent(new Event("input",{bubbles:!0}))))}ie(`${ge.current}${c}`),h.g||requestAnimationFrame(()=>{Object(za.a)(s)})},[]),ht=Object(c.m)(()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if(Object(Qa.a)(t))return void document.execCommand("delete",!1)}ie(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 a=t.lastChild;if(a.lastChild)for(;a.lastChild;)a=a.lastChild;const s=a.textContent.length,n=document.createRange(),c=window.getSelection();n.setStart(a,s),n.setEnd(a,s),c.removeAllRanges(),c.addRange(n),document.execCommand("delete",!1);const r=t.innerHTML;return document.body.removeChild(t),r}(ge.current))},[]),Ot=Object(c.m)(()=>{ie(""),pe([]),it(),he(),je(void 0),Qe(),dt(),h.g?setTimeout(()=>ke(),350):ke()},[it,he,Qe,dt,ke]),jt=Object(na.a)(l);Object(c.n)(()=>{jt&&l!==jt&&(Be(),Ot())},[l,jt,Ot,Be]);const gt=((e,t,a,s,r,o)=>{Object(c.n)(()=>{a?(t(cs(a.content.text)),requestAnimationFrame(()=>{const e=document.getElementById(n.v);Object(za.a)(e,!0)})):t("")},[a,t]);return Object(c.m)(()=>{const{text:t,entities:n}=Object(Wa.a)(e.current);a&&(t||Object(m.cb)(a)?(o({messageId:a.id,text:t,entities:n}),s()):r())},[o,a,e,r,s])})(ge,ie,o,Ot,Pe,G);((e,t,a,s,r,o,i,l,d)=>{const b=Object(c.m)((e,t)=>{r.current.length&&!i?l({chatId:e,threadId:t,draft:Object(Wa.a)(r.current)}):d({chatId:e,threadId:t})},[d,i,r,l]),u=Object(c.p)(()=>Object(g.a)(e=>e(),n.u,!1),[t]),m=Object(na.a)(t),h=Object(na.a)(a);Object(c.n)(()=>(rs=t,os=a,()=>{rs=void 0,os=void 0,b(t,a)}),[t,a,b]),Object(c.n)(()=>{t===m&&a===h||e&&(o(cs(e)),requestAnimationFrame(()=>{const e=document.getElementById(n.v);Object(za.a)(e,!0)}))},[t,a,e,o,b,m,h]);const O=Object(na.a)(s);Object(c.n)(()=>{t&&a&&m===t&&h===a&&O!==s&&(s.length?u(()=>{rs===t&&os===a&&b(t,a)}):b(t,a))},[t,s,m,O,h,u,a,b]),Object(c.n)(()=>{function e(){t&&a&&b(t,a)}return window.addEventListener("blur",e),()=>{window.removeEventListener("blur",e)}},[t,a,b])})(u,l,d,re,ge,ie,o,q,_),((e,t,a)=>{Object(c.n)(()=>{async function s(s){if(!s.clipboardData)return;const c=document.activeElement;if(c&&"INPUT"===c.tagName&&![n.v,n.w].includes(c.id))return;const{items:r}=s.clipboardData,o=Array.from(r).find(e=>ns.includes(e.type)),i=o&&o.getAsFile(),l=s.clipboardData.getData("text").substring(0,4096);if(i||l){if(s.preventDefault(),i&&!a){const e=await Ka(i.name,i,!0);t(t=>[...t,e])}l&&e(l,c?c.id:void 0)}}return document.addEventListener("paste",s,!1),()=>{document.removeEventListener("paste",s,!1)}},[e,a,t])})(mt,pe,o);const ft=Object(c.m)(async(e,t)=>{pe(await Promise.all(e.map(e=>Ka(e.name,e,t))))},[]),pt=Object(c.m)(async(e,t)=>{pe([...fe,...await Promise.all(e.map(e=>Ka(e.name,e,t)))])},[fe]),It=Object(c.m)(()=>{pe([])},[]),vt=Object(c.m)(async(e=!1,t)=>{if("connectionStateReady"!==j)return;let a=fe;if(Ge){const e=await Be();if(e){const{blob:t,duration:s,waveform:n}=e;a=[await Ka("wonderful-voice-message.ogg",t,!1,{voice:{duration:s,waveform:n}})]}}const{text:s,entities:c}=Object(Wa.a)(ge.current);if(a.length||s||y)if(a.length&&s&&s.length>1024){const e=s.length-1024;V({error:{message:"CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""}}})}else{if(a.length||s){if(ct&&!nt){const e=Math.floor(Date.now()/1e3),t=le.current&&Math.floor(e-le.current),a=ct.nextSendDate&&ct.nextSendDate>e;if(t&&t{e={...e,isPreloadedGlobally:!0},t?(je({sticker:e}),ue()):(H({sticker:e}),requestAnimationFrame(Ot))},[t,ue,H,Ot]),Ct=Object(c.m)(e=>{t?(je({gif:e}),ue()):(H({gif:e}),requestAnimationFrame(Ot))},[t,ue,H,Ot]),wt=Object(c.m)(e=>{t?(je({poll:e}),Q(),ue()):(H({poll:e}),Q())},[Q,ue,H,t]),Mt=Object(c.m)(()=>{t?(je({isSilent:!0}),ue()):vt(!0)},[vt,ue,t]),St=Object(c.m)(e=>{const{isSilent:t,...a}=Oe||{},s=Math.round(Math.max(e.getTime(),Date.now()+6e4)/1e3);Oe&&0!==Object.keys(a).length?(H({...Oe,scheduledAt:s}),requestAnimationFrame(Ot)):vt(!!t,s),he()},[he,vt,Ot,Oe,H]),kt=Object(c.m)(()=>{St(new Date(1e3*n.lb))},[St]),Nt=Object(c.m)(()=>{he(),je(void 0)},[he]),Pt=Object(c.m)(e=>{"stickers"===e?($({query:""}),z({query:void 0})):(z({query:""}),$({query:void 0}))},[$,z]),Tt=Object(c.m)(()=>{const e=document.getElementById(n.v);h.g&&e===document.activeElement?(e.blur(),setTimeout(()=>{Se()},100)):Se()},[Se]),At=Object(c.m)(()=>{Z({id:l,threadId:d,type:"scheduled"})},[Z,l,d]);Object(c.n)(()=>{I&&h.g&&ke()},[I,ke]),Object(c.n)(()=>{v?Le():setTimeout(()=>{Fe()},200)},[v,Fe,Le]);const xt=Object(c.m)(()=>{switch($e){case Rs.Send:t?(Ge&&He(),ue()):(vt(),requestAnimationFrame(Ot));break;case Rs.Record:De();break;case Rs.Edit:gt()}},[$e,Ot,t,De,gt,Ge,ue,He,vt]),Rt=Object(ne.a)(),Lt=$e===Rs.Record&&!st.canAttachMedia,Ft=Object(na.a)(o,!0),Dt=o||Ft,Bt=new Date;Bt.setSeconds(0),Bt.setMilliseconds(0);const Ut=new Date;Ut.setFullYear(Ut.getFullYear()+1);let Ht="SendMessage";switch($e){case Rs.Edit:Ht="Save edited message";break;case Rs.Record:Ht=Lt?"Conversation.DefaultRestrictedMedia":"AccDescrVoiceMessage"}const Gt=Object(J.a)("Composer",!v&&"shown",Re&&"hover-disabled"),qt=Object(J.a)("mobile-symbol-menu-button",Ae?Me&&"menu-opened":Me&&"is-loading");return c.a.createElement("div",{className:Gt},st.canAttachMedia&&c.a.createElement(Ts.a,{containerId:"#middle-column-portals"},c.a.createElement(ks,{isOpen:e!==Ue.a.None,withQuick:[e,de].includes(Ue.a.QuickFile),onHide:r,onFileSelect:ft})),c.a.createElement(Ms,{attachments:fe,caption:fe.length?re:"",canSuggestMembers:C,groupChatMembers:P,currentUserId:T,usersById:A,recentEmojis:U,onCaptionUpdate:ie,language:D,addRecentEmoji:ae,loadEmojiKeywords:se,onSend:t?ue:vt,onFileAppend:pt,onClear:It}),c.a.createElement(Ss,{isOpen:Boolean(E),onClear:Q,onSend:wt}),c.a.createElement(xs,{isOpen:Boolean(w),onClose:X}),c.a.createElement(Ls,{isOpen:Boolean(M),onClose:ee}),Dt&&c.a.createElement(bs,{isOpen:Ne,isSchedule:"scheduled"===b,onClose:Te,message:Dt}),c.a.createElement(fs,{isOpen:We,filter:Ke,onClose:Qe,onInsertUserName:Ye,filteredChatMembers:Xe,usersById:A}),c.a.createElement("div",{id:"message-compose"},c.a.createElement("div",{className:"svg-appendix",ref:ce}),c.a.createElement(ws,null),c.a.createElement(Ps,{chatId:l,threadId:d,messageText:fe.length?"":re,disabled:!st.canAttachEmbedLinks}),c.a.createElement("div",{className:"message-input-wrapper"},h.g?c.a.createElement(oe.a,{className:qt,round:!0,color:"translucent",onClick:Me?ke:Tt,ariaLabel:"Choose emoji, sticker or GIF"},c.a.createElement("i",{className:"icon-smile"}),c.a.createElement("i",{className:"icon-keyboard"}),c.a.createElement(me.a,{color:"gray"})):c.a.createElement(Os,{className:""+(Me?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:Se,ariaLabel:"Choose emoji, sticker or GIF"},c.a.createElement("i",{className:"icon-smile"})),c.a.createElement(Cs.a,{id:"message-input-text",html:fe.length?"":re,placeholder:Ge&&window.innerWidth<=600?"":Rt("Message"),shouldSetFocus:Me,shouldSupressFocus:h.g&&Me,shouldSupressTextFormatter:lt||We,onUpdate:ie,onSend:$e===Rs.Edit?gt:t?ue:vt,onSupressedFocus:ke}),k&&c.a.createElement(oe.a,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:At,ariaLabel:"Open scheduled messages"},c.a.createElement("i",{className:"icon-schedule"})),S&&!Ge&&!o&&c.a.createElement(Os,{className:""+(Ie?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:ve,ariaLabel:"Open bot command keyboard"},c.a.createElement("i",{className:"icon-bot-command"})),!Ge&&!o&&c.a.createElement(Os,{className:""+(Ce?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:Ee,ariaLabel:"Add an attachment"},c.a.createElement("i",{className:"icon-attach"})),Ge&&qe&&c.a.createElement("span",{className:"recording-state"},Object(x.i)(qe-Ve.current)),c.a.createElement(Is,{isOpen:rt,onStickerSelect:yt}),c.a.createElement(vs.a,{isOpen:lt,emojis:bt,onClose:dt,onEmojiSelect:ut,addRecentEmoji:ae,loadEmojiKeywords:se,language:D}),c.a.createElement(js,{isOpen:Ce,allowedAttachmentOptions:st,onFileSelect:ft,onPollCreate:K,onClose:we}),S&&c.a.createElement(ys,{messageId:S,isOpen:Ie,onClose:ye}),c.a.createElement(gs,{isOpen:Me,allowedAttachmentOptions:st,onLoad:xe,onClose:ke,onEmojiSelect:mt,onStickerSelect:yt,onGifSelect:Ct,onRemoveSymbol:ht,onSearchOpen:Pt,addRecentEmoji:ae}))),Ge&&c.a.createElement(oe.a,{round:!0,color:"danger",className:"cancel",onClick:Be,ariaLabel:"Cancel voice recording"},c.a.createElement("i",{className:"icon-delete"})),c.a.createElement(oe.a,{ref:_e,round:!0,color:"secondary",className:`${$e} ${Ge?"recording":""}`,disabled:Lt,ariaLabel:Rt(Ht),onClick:xt,onContextMenu:$e===Rs.Send&&ze?Ze:void 0},c.a.createElement("i",{className:"icon-send"}),c.a.createElement("i",{className:"icon-microphone-alt"}),c.a.createElement("i",{className:"icon-check"})),ze&&c.a.createElement(ps,{isOpen:Je,onSilentSend:p?void 0:Mt,onScheduleSend:t?void 0:ue,onClose:et,onCloseAnimationEnd:at}),c.a.createElement(As,{isOpen:be,withTimePicker:!0,selectedAt:Bt.getTime(),maxAt:Object(x.k)(Ut),isFutureMode:!0,secondButtonLabel:a?"Send When Online":void 0,onClose:Nt,onSubmit:St,onSecondButtonClick:a?kt:void 0}))}));var Ds=Object(c.h)(e=>{const{isActive:t}=e,a=Object(Ce.a)(ye.a.Extra,"MobileSearch",!t,!0);return a?c.a.createElement(a,e):void 0});var Bs=Object(c.h)(e=>{const{isActive:t}=e,a=Object(Ce.a)(ye.a.Extra,"MessageSelectToolbar",!t);return a?c.a.createElement(a,e):void 0});var Us=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"UnpinAllMessagesModal",!t);return a?c.a.createElement(a,e):void 0});a(242);const Hs=h.g?450+n.c:void 0;function Gs(e){return"file"===e.kind&&e.type&&n.l.includes(e.type)}var qs=Object(c.h)(Object(s.h)(e=>{const{theme:t}=e.settings.byKey,{isBlurred:a,background:s,backgroundColor:n,patternColor:c}=e.settings.themes[t]||{},r=Object(o.y)(e),{chats:{listIds:l}}=e,d={theme:t,customBackground:s,backgroundColor:n,patternColor:c,isRightColumnShown:Object(o.W)(e),isBackgroundBlurred:a,isMobileSearchActive:Boolean(h.g&&Object(o.A)(e)),isSelectModeActive:Object(o.S)(e),animationLevel:e.settings.byKey.animationLevel};if(!r||!l.active)return d;const{chatId:b,threadId:u,type:O}=r,j=Object(o.f)(e,b),g=Object(o.jb)(e,b),{chatId:f,messageId:p}=e.audioPlayer,I=j&&Object(m.e)(j,u),v=Object(o.L)(e,b),y="pinned"===O;return{...d,chatId:b,threadId:u,messageListType:O,isPrivate:Object(m.lb)(b),canPost:!y&&(!j||I)&&(!v||h.g),isPinnedMessageList:y,messageSendingRestrictionReason:j&&Object(m.K)(j),hasPinnedOrAudioMessage:u!==i.MAIN_THREAD_ID||Boolean(g&&g.length)||Boolean(f&&p),pinnedMessagesCount:g?g.length:0}},(e,t)=>Object(d.l)(t,["openChat","unpinAllMessages","loadUser"]))(({chatId:e,threadId:t,messageListType:a,isPrivate:s,isPinnedMessageList:r,canPost:o,messageSendingRestrictionReason:l,hasPinnedOrAudioMessage:d,pinnedMessagesCount:b,customBackground:u,theme:m,backgroundColor:O,patternColor:j,isRightColumnShown:g,isBackgroundBlurred:f,isMobileSearchActive:p,isSelectModeActive:I,animationLevel:v,openChat:y,unpinAllMessages:C,loadUser:E})=>{const{width:w}=_e(),[M,S]=Object(c.r)(Ue.a.None),[k,N]=Object(c.r)(),[P,T]=Object(c.r)(),[A,x]=Object(c.r)(!1),R=d&&(wn.ab&&w=n.Z&&we?Object(te.a)(()=>{y({id:void 0})}):void 0,[e,y]),Object(c.n)(()=>{S(Ue.a.None),N(void 0),T(void 0)},[e]),Object(c.n)(()=>{s&&E({userId:e})},[e,s,E]);const G=Object(c.m)(e=>{if(h.l)return;const{items:t}=e.dataTransfer||{},a=t&&Array.from(t).every(Gs);S(a?Ue.a.QuickFile:Ue.a.Document)},[]),q=Object(c.m)(()=>{S(Ue.a.None)},[]),_=Object(c.m)(()=>{x(!0)},[]),V=Object(c.m)(()=>{x(!1)},[]),$=Object(c.m)(()=>{C({chatId:e}),V(),y({id:e})},[C,y,V,e]),z=((e,t)=>{const[a,s]=Object(c.r)(t);return Object(c.n)(()=>{t&&(t.startsWith("#")?s(t):He.c(n.m,e,He.a.Blob).then(e=>{const t=URL.createObjectURL(e);Object(Ge.g)(t).then(()=>{s(`url(${t})`)})}))},[t,e]),t?a:void 0})(m,u),W=Object(J.a)(U&&"has-header-tools",u&&"custom-bg-image",O&&"custom-bg-color",u&&f&&"blurred",h.n?"mask-image-disabled":"mask-image-enabled"),K=Object(J.a)("messaging-disabled",!I&&"shown"),{composerHiddenScale:Q,toolbarHiddenScale:Y,composerTranslateX:X,toolbarTranslateX:Z,unpinHiddenScale:ee,toolbarForUnpinHiddenScale:se}=Object(c.p)(()=>$e(w,B),[B,w]),ce=Object(ne.a)(),re=Object(J.a)("middle-column-footer",!B&&"no-composer",B&&P&&!I&&"with-notch");return c.a.createElement("div",{id:"MiddleColumn",className:W,style:`\n --composer-hidden-scale: ${Q};\n --toolbar-hidden-scale: ${Y};\n --unpin-hidden-scale: ${ee};\n --toolbar-unpin-hidden-scale: ${se};\n --composer-translate-x: ${X}px;\n --toolbar-translate-x: ${Z}px;\n --pattern-color: ${j};\n --theme-background-color:\n ${O||("dark"===m?n.n:n.I)};\n `},c.a.createElement("div",{id:"middle-column-bg",style:z?"--custom-background: "+z:void 0}),c.a.createElement("div",{id:"middle-column-portals"}),L&&F&&c.a.createElement(c.a.Fragment,null,c.a.createElement("div",{className:"messages-layout",onDragEnter:B?G:void 0},c.a.createElement(ht,{chatId:L,threadId:F,messageListType:D}),c.a.createElement(ae.a,{name:v===n.e?"slide":"fade",activeKey:"thread"===D&&F===i.MAIN_THREAD_ID?1:2,shouldCleanup:!0},()=>c.a.createElement(c.a.Fragment,null,c.a.createElement(Va,{key:`${L}-${F}-${D}`,chatId:L,threadId:F,type:D,canPost:B,hasTools:U,onFabToggle:N,onNotchToggle:T}),c.a.createElement("div",{className:re},B&&c.a.createElement(Fs,{chatId:L,threadId:F,messageListType:D,dropAreaState:M,onDropHide:q}),r&&c.a.createElement("div",{className:"unpin-button-container",dir:ce.isRtl?"rtl":void 0},c.a.createElement(oe.a,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:_},c.a.createElement("i",{className:"icon-unpin"}),c.a.createElement("span",null,ce("Chat.Pinned.UnpinAll",b,"i")))),!r&&!B&&l&&c.a.createElement("div",{className:K},c.a.createElement("div",{className:"messaging-disabled-inner"},c.a.createElement("span",null,l))),c.a.createElement(Bs,{messageListType:D,isActive:I,canPost:B})))),c.a.createElement($a,{isShown:H,canPost:B})),h.g&&c.a.createElement(Ds,{isActive:Boolean(p)})),e&&c.a.createElement(Us,{isOpen:A,chatId:e,pinnedMessagesCount:b,onClose:V,onUnpin:$}))}));a(243);const _s=Object(g.a)(e=>e(),200,!1);var Vs;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Management=4]="Management",e[e.ManageInitial=5]="ManageInitial",e[e.ManageChannelSubscribers=6]="ManageChannelSubscribers",e[e.ManageChatAdministrators=7]="ManageChatAdministrators",e[e.ManageChatPrivacyType=8]="ManageChatPrivacyType",e[e.ManageDiscussion=9]="ManageDiscussion",e[e.ManageGroupPermissions=10]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=11]="ManageGroupRemovedUsers",e[e.ManageGroupUserPermissionsCreate=12]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=13]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=14]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=15]="ManageGroupAdminRights",e[e.ManageGroupMembers=16]="ManageGroupMembers",e[e.StickerSearch=17]="StickerSearch",e[e.GifSearch=18]="GifSearch",e[e.PollResults=19]="PollResults"}(Vs||(Vs={}));var $s=Object(c.h)(Object(s.h)((e,{chatId:t,isProfile:a,isManagement:s})=>{const{query:n}=Object(o.A)(e)||{},{query:c}=Object(o.z)(e)||{},{query:r}=Object(o.s)(e)||{},i=t?Object(o.f)(e,t):void 0,l=i&&Object(m.jb)(i);return{canManage:Boolean(!s&&a&&i&&!Object(o.P)(e,i.id)&&(Object(m.lb)(i.id)||(Object(m.gb)(i)||i.isCreator)&&!i.isNotJoined)),isChannel:l,messageSearchQuery:n,stickerSearchQuery:c,gifSearchQuery:r}},(e,t)=>Object(d.l)(t,["setLocalTextSearchQuery","setStickerSearchQuery","setGifSearchQuery","searchTextMessagesLocal","toggleManagement","openHistoryCalendar"]))(({isColumnOpen:e,isProfile:t,isSearch:a,isManagement:s,isStickerSearch:n,isGifSearch:r,isPollResults:o,profileState:i,managementScreen:d,canManage:b,isChannel:u,onClose:m,messageSearchQuery:O,stickerSearchQuery:j,gifSearchQuery:g,setLocalTextSearchQuery:f,setStickerSearchQuery:p,setGifSearchQuery:I,searchTextMessagesLocal:v,toggleManagement:y,openHistoryCalendar:C})=>{var E;const w=Object(c.q)(null),M=Object(c.m)(e=>{f({query:e}),e.length&&_s(v)},[v,f]),S=Object(c.m)(e=>{p({query:e})},[p]),k=Object(c.m)(e=>{I({query:e})},[I]),[N,P]=Object(c.r)(!e);Object(c.n)(()=>{setTimeout(()=>{P(!e)},300)},[e]);const T=Object(ne.a)(),A=t?i===l.k.Profile?Vs.Profile:i===l.k.SharedMedia?Vs.SharedMedia:i===l.k.MemberList?Vs.MemberList:-1:a?Vs.Search:o?Vs.PollResults:n?Vs.StickerSearch:r?Vs.GifSearch:s?d===l.g.Initial?Vs.ManageInitial:d===l.g.ChatPrivacyType?Vs.ManageChatPrivacyType:d===l.g.Discussion?Vs.ManageDiscussion:d===l.g.ChannelSubscribers?Vs.ManageChannelSubscribers:d===l.g.GroupPermissions?Vs.ManageGroupPermissions:d===l.g.ChatAdministrators?Vs.ManageChatAdministrators:d===l.g.GroupRemovedUsers?Vs.ManageGroupRemovedUsers:d===l.g.GroupUserPermissionsCreate?Vs.ManageGroupUserPermissionsCreate:d===l.g.GroupUserPermissions?Vs.ManageGroupUserPermissions:d===l.g.GroupRecentActions?Vs.ManageGroupRecentActions:d===l.g.ChatAdminRights?Vs.ManageGroupAdminRights:d===l.g.GroupMembers?Vs.ManageGroupMembers:void 0:void 0,R=null!==(E=Object(Ke.a)(A,!0))&&void 0!==E?E:-1;function L(){if(-1!==R)switch(R){case Vs.PollResults:return c.a.createElement("h3",null,T("PollResults"));case Vs.Search:return c.a.createElement(c.a.Fragment,null,c.a.createElement(ie.a,{parentContainerClassName:"RightSearch",value:O,onChange:M}),c.a.createElement(oe.a,{round:!0,size:"smaller",color:"translucent",onClick:()=>C({selectedAt:Object(x.k)(Date.now())}),ariaLabel:"Search messages by date"},c.a.createElement("i",{className:"icon-calendar"})));case Vs.ManageInitial:return c.a.createElement("h3",null,T("Edit"));case Vs.ManageChatPrivacyType:return c.a.createElement("h3",null,T(u?"ChannelTypeHeader":"GroupTypeHeader"));case Vs.ManageDiscussion:return c.a.createElement("h3",null,T("Discussion"));case Vs.ManageChatAdministrators:return c.a.createElement("h3",null,T("ChannelAdministrators"));case Vs.ManageGroupRecentActions:return c.a.createElement("h3",null,T("Group.Info.AdminLog"));case Vs.ManageGroupAdminRights:return c.a.createElement("h3",null,T("EditAdminRights"));case Vs.ManageGroupPermissions:return c.a.createElement("h3",null,T("ChannelPermissions"));case Vs.ManageGroupRemovedUsers:return c.a.createElement("h3",null,T("ChannelBlockedUsers"));case Vs.ManageGroupUserPermissionsCreate:return c.a.createElement("h3",null,T("ChannelAddException"));case Vs.ManageGroupUserPermissions:return c.a.createElement("h3",null,T("UserRestrictions"));case Vs.StickerSearch:return c.a.createElement(ie.a,{value:j,placeholder:T("SearchStickersHint"),onChange:S});case Vs.GifSearch:return c.a.createElement(ie.a,{value:g,placeholder:T("SearchGifsTitle"),onChange:k});case Vs.SharedMedia:return c.a.createElement("h3",null,T("SharedMedia"));case Vs.ManageChannelSubscribers:return c.a.createElement("h3",null,T("ChannelSubscribers"));case Vs.MemberList:case Vs.ManageGroupMembers:return c.a.createElement("h3",null,T("GroupMembers"));default:return c.a.createElement(c.a.Fragment,null,c.a.createElement("h3",null,"Profile"),c.a.createElement("section",{className:"tools"},b&&c.a.createElement(oe.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:T("Edit"),onClick:y},c.a.createElement("i",{className:"icon-edit"}))))}}const F=h.g||A===Vs.SharedMedia||A===Vs.MemberList||s,D=Object(J.a)("animated-close-icon",N&&"no-transition");return Object(c.n)(()=>{w.current.classList.toggle("state-back",F)},[F]),c.a.createElement("div",{className:"RightHeader"},c.a.createElement(oe.a,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:m,ariaLabel:T(F?"Common.Back":"Common.Close")},c.a.createElement("div",{ref:w,className:D})),c.a.createElement(ae.a,{name:N?"none":"slide-fade",activeKey:R},L))})),zs=a(127);function Ws(e,t,a,s,r,o,i,l,d,b,u){const h="members"!==s&&r?r:s,O=Object(c.p)(()=>{if(o&&i)return Object(m.Eb)(o.map(({userId:e})=>e),i)},[o,i]),[j,g,f]=function(e,t,a,s){const[c,r]=Object(zs.a)(a?t:void 0,s,void 0,n.R),o=!c||!s||c[0]===s[0];return[c,r,!o]}(0,t,u,O),[p,I,v]=Ks("media",h,a,u,l,d),[y,C,E]=Ks("documents",h,a,u,l,d),[w,M,S]=Ks("links",h,a,u,l,d),[k,N,P]=Ks("audio",h,a,u,l,d);let T,A,x=!1;switch(h){case"members":T=j,A=g,x=f;break;case"media":T=p,A=I,x=v;break;case"documents":T=y,A=C,x=E;break;case"links":T=w,A=M,x=S;break;case"audio":T=k,A=N,x=P}return[h,T,A,x]}function Ks(e,t,a,s,r,o){const i=Object(c.q)();Object(je.a)(()=>{t===e&&r&&o&&(i.current=Object(m.w)(r,o,e).reverse())},[r,o,t,e]);const[l,d]=Object(zs.a)(s?a:void 0,i.current,void 0,"media"===e?n.ob:n.X);return[l,d,!(!l||!i.current||l[0]===i.current[0])]}var Qs=a(58);const Ys=Object(g.g)(e=>e(),250,!1);let Xs=!1;var Js=a(113),Zs=a(106);var en=a(133),tn=a(191);a(244);var an=Object(c.h)(({chat:e,user:t,photo:a,isFirstPhoto:s,isSavedMessages:n,lastSyncTime:r,onClick:o})=>{const l=Object(ne.a)(),d=t&&Object(m.pb)(t);function b(s="big",c){if(a&&!c)return`photo${a.id}?size=c`;let r;return n||d||(t?r=Object(m.f)(t,s):e&&(r=Object(m.f)(e,s))),r}const u=b(),h=Object(at.a)(u,!1,i.ApiMediaFormat.BlobUrl,r),O=Object(at.a)(!h&&s?b("normal",!0):void 0,!1,i.ApiMediaFormat.BlobUrl,r),j=Object(tn.a)(!h&&a&&a.thumbnail&&a.thumbnail.dataUri),g=h||O||j,f=Object(na.a)(g);let p="";if(n)p=c.a.createElement("i",{className:"icon-avatar-saved-messages"});else if(d)p=c.a.createElement("i",{className:"icon-avatar-deleted-account"});else if(g)p=c.a.createElement("img",{src:g,className:"avatar-media",alt:"",decoding:"async"});else if(!g&&t){const e=Object(m.Z)(t);p=e?Object(Qe.c)(e,2):void 0}else if(!g&&e){const t=Object(m.l)(l,e);p=t&&Object(Qe.c)(t,Object(m.lb)(e.id)?2:1)}else p=c.a.createElement("div",{className:"spinner-wrapper"},c.a.createElement(me.a,{color:"white"}));const I=Object(J.a)("ProfilePhoto","color-bg-"+Object(m.X)(t||e),n&&"saved-messages",d&&"deleted-account",!n&&!g&&"no-photo");return c.a.createElement("div",{className:I,onClick:g?o:void 0},f&&g&&f!==g&&c.a.createElement("img",{src:f,className:"prev-avatar-media",alt:"",decoding:"async"}),"string"==typeof p?Object(tt.a)(p,["hq_emoji"]):p)});a(245);var sn=Object(c.h)(Object(s.h)((e,{userId:t,forceShowSelf:a})=>{const{lastSyncTime:s}=e,n=Object(o.Gb)(e,t),c=Object(o.f)(e,t),r=!a&&n&&n.isSelf,{animationLevel:i}=e.settings.byKey;return{lastSyncTime:s,user:n,chat:c,isSavedMessages:r,animationLevel:i}},(e,t)=>Object(d.l)(t,["loadFullUser","openMediaViewer"]))(({user:e,chat:t,isSavedMessages:a,lastSyncTime:s,animationLevel:n,loadFullUser:r,openMediaViewer:o})=>{const{id:d}=e||{},{id:b}=t||{},u=e?Object(m.Z)(e):t?t.title:"",O=(e?e.photos:t?t.photos:void 0)||[],j=n>=1?"slide":"none",[g,f]=Object(c.r)(0),p=a||O.length<=1||0===g,I=a||O.length<=1||g===O.length-1;Object(c.n)(()=>{g>O.length&&f(Math.max(0,O.length-1))},[g,O.length]);const v=Object(ne.a)();Object(c.n)(()=>{s&&d&&r({userId:d})},[d,r,s]),function(e,t,a){Object(c.n)(()=>{t.slice(a,a+4).forEach(e=>{bt.c(`photo${e.id}?size=c`)||bt.b(`photo${e.id}?size=c`,i.ApiMediaFormat.BlobUrl)})},[a,t])}(0,O,g);const y=Object(c.m)(()=>{o({avatarOwnerId:d||b,profilePhotoIndex:g,origin:l.h.ProfileAvatar})},[o,d,b,g]),C=Object(c.m)(()=>{p||f(g-1)},[g,p]),E=Object(c.m)(()=>{I||f(g+1)},[g,I]);if(Object(c.n)(()=>{const e=document.querySelector(".profile-slide-container > .active, .profile-slide-container > .to");if(e)return Object(Oe.b)(e,{excludedClosestSelector:".navigation",onSwipe:h.l?(e,t)=>{t===Oe.a.Right?C():t===Oe.a.Left&&E()}:void 0})},[E,C]),!e&&!t)return;function w(){const s=!a&&O&&O.length>0?O[g]:void 0;return c.a.createElement(an,{key:g,user:e,chat:t,photo:s,isSavedMessages:a,isFirstPhoto:p,onClick:y})}const M=e&&e.isVerified||t&&t.isVerified;return c.a.createElement("div",{className:"ProfileInfo",dir:v.isRtl?"rtl":void 0},c.a.createElement("div",{className:"photo-wrapper"},function(){if(!(a||!O||O.length<=1))return c.a.createElement("div",{className:"photo-dashes"},O.map((e,t)=>c.a.createElement("span",{className:"photo-dash "+(t===g?"current":"")})))}(),c.a.createElement(ae.a,{activeKey:g,name:j,className:"profile-slide-container"},w),!p&&c.a.createElement("button",{type:"button",className:"navigation prev","aria-label":v("AccDescrPrevious"),onClick:C}),!I&&c.a.createElement("button",{type:"button",className:"navigation next","aria-label":v("Next"),onClick:E})),c.a.createElement("div",{className:"info",dir:v.isRtl?"rtl":"auto"},a?c.a.createElement("div",{className:"title"},c.a.createElement("h3",{dir:"auto"},v("SavedMessages"))):c.a.createElement("div",{className:"title"},c.a.createElement("h3",{dir:"auto"},u&&Object(tt.a)(u)),M&&c.a.createElement(en.a,null)),!a&&(e?c.a.createElement("div",{className:"status "+(Object(m.xb)(e)?"online":"")},c.a.createElement("span",{className:"user-status",dir:"auto"},Object(m.ab)(v,e))):c.a.createElement("span",{className:"status",dir:"auto"},Object(m.jb)(t)?v("Subscribers",t.membersCount,"i"):v("Members",t.membersCount,"i")))))}));var nn=Object(c.h)(Object(s.h)((e,{chatOrUserId:t})=>{const{lastSyncTime:a}=e,s=t?Object(o.f)(e,t):void 0;return{lastSyncTime:a,chat:s,user:Object(m.lb)(t)?Object(o.Gb)(e,t):void 0,canInviteUsers:s&&(!Object(m.jb)(s)&&!Object(m.yb)(s,"inviteUsers")||Object(m.q)(s,"inviteUsers"))}},(e,t)=>Object(d.l)(t,["loadFullUser","updateChatMutedState","showNotification"]))(({lastSyncTime:e,user:t,chat:a,forceShowSelf:s,canInviteUsers:n,loadFullUser:r,showNotification:o,updateChatMutedState:i})=>{const{id:l,fullInfo:d,username:b,phoneNumber:u,isSelf:h}=t||{},{id:O,isMuted:j,username:g}=a||{},f=Object(ne.a)();Object(c.n)(()=>{e&&l&&r({userId:l})},[r,l,e]);const p=Object(c.m)(()=>{i({chatId:O,isMuted:!j})},[O,j,i]);if(!a||a.isRestricted||h&&!s)return;function I(e,t){Object(E.c)(e),o({message:t+" was copied"})}const v=u&&Object(Oa.c)(u),y=Object(m.h)(a),C=0===y.indexOf("http")?y:"http://"+y,w=b||g,M=d&&d.bio||Object(m.g)(a);return c.a.createElement("div",{className:"ChatExtra"},v&&!!v.length&&c.a.createElement(Zs.a,{icon:"phone",multiline:!0,narrow:!0,ripple:!0,onClick:()=>I(v,f("Phone"))},c.a.createElement("span",{className:"title",dir:"auto"},v),c.a.createElement("span",{className:"subtitle"},f("Phone"))),w&&c.a.createElement(Zs.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>I("@"+w,f("Username"))},c.a.createElement("span",{className:"title",dir:"auto"},Object(tt.a)(w)),c.a.createElement("span",{className:"subtitle"},f("Username"))),M&&!!M.length&&c.a.createElement(Zs.a,{icon:"info",multiline:!0,narrow:!0,isStatic:!0},c.a.createElement("span",{className:"title",dir:"auto"},Object(tt.a)(M,["br","links","emoji"])),c.a.createElement("span",{className:"subtitle"},f(l?"UserBio":"Info"))),n&&!w&&!!y.length&&c.a.createElement(Zs.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>I(y,f("SetUrlPlaceholder"))},c.a.createElement("div",{className:"title"},c.a.createElement(wa.a,{url:C,className:"title",text:y})),c.a.createElement("span",{className:"subtitle"},f("SetUrlPlaceholder"))),c.a.createElement(Zs.a,{icon:"unmute",ripple:!0,onClick:p},c.a.createElement("span",null,f("Notifications")),c.a.createElement(de,{id:"group-notifications",label:l?"Toggle User Notifications":"Toggle Chat Notifications",checked:!j,inactive:!0})))})),cn=a(165),rn=a(185),on=a(118);a(249);const ln=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"}];function dn(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > div.active > .${e}-list > .scroll-item`].join(", ")}var bn=Object(c.h)(Object(s.h)((e,{chatId:t,userId:a})=>{const s=Object(o.f)(e,t),n=Object(o.m)(e,a||t),{currentType:c,resultsByType:r}=Object(o.v)(e)||{},{foundIds:i}=r&&c&&r[c]||{},{byId:l}=e.users,d=s&&Object(m.kb)(s),b=s&&Object(m.jb)(s),u=d||b&&Object(m.gb)(s),h=s&&s.fullInfo&&s.fullInfo.members,O=u&&s&&s.fullInfo&&!s.fullInfo.canViewMembers;let j;return a?j=a:Object(m.lb)(t)&&(j=t),{isChannel:b,resolvedUserId:j,chatMessages:n,foundIds:i,mediaSearchType:c,hasMembersTab:u,areMembersHidden:O,...u&&h&&{members:h,usersById:l},isRightColumnShown:Object(o.W)(e),isRestricted:s&&s.isRestricted,lastSyncTime:e.lastSyncTime}},(e,t)=>Object(d.l)(t,["setLocalMediaSearchType","loadMoreMembers","searchMediaMessagesLocal","openMediaViewer","openAudioPlayer","openUserInfo","focusMessage","loadProfilePhotos"]))(({chatId:e,profileState:t,onProfileStateChange:a,isChannel:s,resolvedUserId:r,chatMessages:o,foundIds:d,mediaSearchType:b,hasMembersTab:u,areMembersHidden:m,members:O,usersById:j,isRightColumnShown:g,isRestricted:f,lastSyncTime:p,setLocalMediaSearchType:I,loadMoreMembers:v,searchMediaMessagesLocal:y,openMediaViewer:C,openAudioPlayer:E,openUserInfo:w,focusMessage:M,loadProfilePhotos:S})=>{const k=Object(c.q)(null),N=Object(c.q)(null),P=Object(ne.a)(),[T,A]=Object(c.r)(0),x=Object(c.p)(()=>[...u?[{type:"members",title:s?"ChannelSubscribers":"GroupMembers"}]:[],...ln],[u,s]),R=x[T].type,[L,F,D,B]=Ws(0,v,y,R,b,O,j,o,d,0,p),U=x.findIndex(({type:e})=>e===L),{handleScroll:H}=function(e,t,a,s){Object(Qs.a)(([a])=>{if(a&&a!==t){const a=e.current,n=a.querySelector(".TabList");a.scrollTop{Xs=!1},350))}},[t,s]),Object(Qs.a)(([t])=>{if(a!==l.k.Profile||a===t)return;const n=e.current;if(!n)return;const c=n.querySelector(".TabList");!c||c.offsetTop>n.scrollTop||(Xs=!0,Object(vt.a)(n,n.firstElementChild,"start",void 0,2*n.offsetHeight),setTimeout(()=>{Xs=!1},350),s(a))},[a]);const n=Object(c.m)(()=>{const a=e.current;if(!a)return;const n=a.querySelector(".TabList");if(!n)return;let c=l.k.Profile;a.scrollTop>=n.offsetTop&&(c="members"===t?l.k.MemberList:l.k.SharedMedia),s(c)},[e,s,t]);return Object(c.n)(()=>{Xs||n()},[n,t]),{handleScroll:Object(c.m)(()=>{Xs||Ys(n)},[n])}}(k,R,t,a),{applyTransitionFix:G,releaseTransitionFix:q}=function(e,t=".Transition.shared-media-transition"){return Object(c.n)(()=>{function a(){const a=e.current,s=a.querySelector(t),n=a.querySelector(".TabList");s&&n&&(s.style.minHeight=a.offsetHeight-n.offsetHeight+"px")}return a(),window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[e,t]),{applyTransitionFix:Object(c.m)(()=>{const t=e.current;if("hidden"!==t.style.overflowY){const e=t.offsetWidth-t.clientWidth;t.style.overflowY="hidden",t.style.marginRight=e+"px"}},[e]),releaseTransitionFix:Object(c.m)(()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"},[e])}}(k),[_,V]=(()=>{const[e,t]=Object(c.r)(!1);return[e,Object(c.m)(()=>{t(e=>!e)},[])]})(),$=Object(c.m)(()=>{q(),V()},[q,V]);Object(c.n)(()=>{I({mediaType:R})},[I,R]);const z=r||e;Object(c.n)(()=>{p&&S({profileId:z})},[S,z,p]);const W=Object(c.m)(e=>{C({chatId:z,threadId:i.MAIN_THREAD_ID,messageId:e,origin:l.h.SharedMedia})},[z,C]),K=Object(c.m)(e=>{E({chatId:z,messageId:e})},[z,E]),Q=Object(c.m)(e=>{w({id:e})},[w]),Y=Object(c.m)(e=>{M({chatId:z,messageId:e})},[z,M]);let X;Object(c.n)(()=>{if(N.current&&h.l)return Object(Oe.b)(N.current,{onSwipe:(e,t)=>{t===Oe.a.Left?A(Math.min(T+1,x.length-1)):t===Oe.a.Right&&A(Math.max(0,T-1))}})},[T,x.length]);const J="members"===L||!u&&"media"===L;J?X=g?0:1e3:F||(X=n.pb);const Z=Object(Es.a)([e,L],X);function ee(){if(!F||!Z||!o){const e=J&&F&&!Z;return c.a.createElement("div",{className:"content empty-list"},!e&&c.a.createElement(me.a,null))}if(!F.length){let e;switch(L){case"members":e=m?"You have no access to group members list.":"No members found";break;case"documents":e=P("lng_media_file_empty_search");break;case"links":e=P("lng_media_link_empty_search");break;case"audio":e=P("lng_media_song_empty_search");break;default:e=P("SharedMedia.EmptyTitle")}return c.a.createElement("div",{className:"content empty-list"},c.a.createElement(on.a,{text:e}))}return c.a.createElement("div",{className:`content ${L}-list`,dir:P.isRtl&&"media"===L?"rtl":void 0,teactFastList:!0},"media"===L?F.map(e=>o[e]&&c.a.createElement(cn.a,{key:e,message:o[e],onClick:W})):"documents"===L?F.map(e=>o[e]&&c.a.createElement(zt.a,{key:e,message:o[e],withDate:!0,smaller:!0,className:"scroll-item",onDateClick:Y})):"links"===L?F.map(e=>o[e]&&c.a.createElement(rn.a,{key:e,message:o[e],onMessageClick:Y})):"audio"===L?F.map(e=>o[e]&&c.a.createElement(Wt.a,{key:e,renderingFor:"sharedMedia",message:o[e],date:o[e].date,lastSyncTime:p,className:"scroll-item",onPlay:K,onDateClick:Y})):"members"===L?F.map((e,t)=>c.a.createElement(Zs.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>Q(e)},c.a.createElement(Ye.a,{userId:e,forceShowSelf:!0}))):void 0)}return c.a.createElement(Js.a,{ref:k,className:"Profile custom-scroll",itemSelector:dn(L),items:Z?F:void 0,cacheBuster:_,sensitiveArea:n.fb,preloadBackwards:Z?"members"===L?n.R:n.ob:0,noScrollRestoreOnTop:!0,noFastList:!0,onLoadMore:D,onScroll:H},!B&&function(e,t){return c.a.createElement("div",{className:"profile-info"},c.a.createElement(sn,{userId:t||e,forceShowSelf:t!==e}),c.a.createElement(nn,{chatOrUserId:t||e,forceShowSelf:t!==e}))}(e,r),!f&&c.a.createElement("div",{className:"shared-media"},c.a.createElement(ae.a,{ref:N,name:P.isRtl?"slide-reversed":"slide",activeKey:U,renderCount:x.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:G,onStop:$},ee),c.a.createElement(pe.a,{big:!0,activeTab:T,tabs:x,onSwitchTab:A})))}));var un=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"RightSearch");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)});var mn=Object(c.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"Management");return t?c.a.createElement(t,e):c.a.createElement(Ee.a,null)});var hn=Object(c.h)(()=>{const e=Object(Ce.a)(ye.a.Extra,"StickerSearch");return e?c.a.createElement(e,null):c.a.createElement(Ee.a,null)});var On=Object(c.h)(()=>{const e=Object(Ce.a)(ye.a.Extra,"GifSearch");return e?c.a.createElement(e,null):c.a.createElement(Ee.a,null)});var jn=Object(c.h)(()=>{const e=Object(Ce.a)(ye.a.Extra,"PollResults");return e?c.a.createElement(e,null):c.a.createElement(Ee.a,null)});a(250);const gn=Object.keys(l.l).length/2,fn=Object.keys(l.g).length/2;function pn(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}var In=Object(c.h)(Object(s.h)(e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},s=Object(o.d)(e);return{contentKey:Object(o.nb)(e),chatId:t,threadId:a,currentProfileUserId:e.users.selectedId,isChatSelected:Boolean(t&&s)}},(e,t)=>Object(d.l)(t,["openUserInfo","toggleChatInfo","toggleManagement","closeLocalTextSearch","setStickerSearchQuery","setGifSearchQuery","closePollResults"]))(({contentKey:e,chatId:t,threadId:a,currentProfileUserId:s,isChatSelected:r,toggleChatInfo:o,toggleManagement:i,openUserInfo:d,closeLocalTextSearch:b,setStickerSearchQuery:u,setGifSearchQuery:m,closePollResults:h})=>{var O;const{width:j}=_e(),[g,f]=Object(c.r)(l.k.Profile),[p,I]=Object(c.r)(l.g.Initial),[v,y]=Object(c.r)(),[C,E]=Object(c.r)(),w=g!==l.k.Profile,M=void 0!==e,S=e===l.l.ChatInfo||e===l.l.UserInfo,k=e===l.l.Search,N=e===l.l.Management,P=e===l.l.StickerSearch,T=e===l.l.GifSearch,A=e===l.l.PollResults,x=j<=n.ab,[R,L]=Object(c.r)(!M),F=null!==(O=Object(Ke.a)(e,!0,!r))&&void 0!==O?O:-1,D=Object(c.m)(()=>{switch(e){case l.l.ChatInfo:if(w){f(l.k.Profile);break}o();break;case l.l.UserInfo:if(w){f(l.k.Profile);break}d({id:void 0});break;case l.l.Management:switch(p){case l.g.Initial:i();break;case l.g.ChatPrivacyType:case l.g.Discussion:case l.g.GroupPermissions:case l.g.GroupType:case l.g.ChatAdministrators:case l.g.ChannelSubscribers:case l.g.GroupMembers:I(l.g.Initial);break;case l.g.GroupUserPermissionsCreate:case l.g.GroupRemovedUsers:case l.g.GroupUserPermissions:I(l.g.GroupPermissions),y(void 0),E(void 0);break;case l.g.ChatAdminRights:case l.g.GroupRecentActions:I(l.g.ChatAdministrators)}break;case l.l.Search:pn(),b();break;case l.l.StickerSearch:case l.l.GifSearch:pn(),u({query:void 0}),m({query:void 0});break;case l.l.PollResults:h()}},[e,w,o,d,h,p,i,b,u,m]),B=Object(c.m)((e,t)=>{y(e),E(t)},[]);function U(){if(-1!==F)switch(F){case l.l.ChatInfo:case l.l.UserInfo:return c.a.createElement(bn,{key:s||t,chatId:t,userId:s,profileState:g,onProfileStateChange:f});case l.l.Search:return c.a.createElement(un,{chatId:t,threadId:a});case l.l.Management:return c.a.createElement(mn,{chatId:t,currentScreen:p,isPromotedByCurrentUser:C,selectedChatMemberId:v,onScreenSelect:I,onChatMemberSelect:B});case l.l.StickerSearch:return c.a.createElement(hn,null);case l.l.GifSearch:return c.a.createElement(On,null);case l.l.PollResults:return c.a.createElement(jn,null)}}return Object(c.n)(()=>M?Object(te.a)(D):void 0,[M,D]),Object(c.n)(()=>{setTimeout(()=>{L(!M)},300)},[M]),Object(c.n)(()=>{M&&x&&D()},[x]),Object(Ot.a)(([a,s])=>{(a===l.l.ChatInfo&&e===l.l.UserInfo||a===l.l.UserInfo&&e===l.l.ChatInfo||s!==t)&&(f(l.k.Profile),I(l.g.Initial))},[e,t]),c.a.createElement("div",{id:"RightColumn-wrapper",className:r?void 0:"is-hidden"},x&&c.a.createElement("div",{className:"overlay-backdrop",onClick:D}),c.a.createElement("div",{id:"RightColumn"},c.a.createElement($s,{chatId:t,isColumnOpen:M,isProfile:S,isSearch:k,isManagement:N,isStickerSearch:P,isGifSearch:T,isPollResults:A,profileState:g,managementScreen:p,onClose:D}),c.a.createElement(ae.a,{name:R?"none":"zoom-fade",renderCount:gn+fn,activeKey:N?gn+p:F},U)))}));var vn=Object(c.h)(({isOpen:e})=>{const t=Object(Ce.a)(ye.a.Extra,"MediaViewer",!e);return t?c.a.createElement(t,null):void 0});var yn=Object(c.h)(({isOpen:e})=>{const t=Object(Ce.a)(ye.a.Extra,"Notifications",!e);return t?c.a.createElement(t,null):void 0});var Cn=Object(c.h)(({isOpen:e})=>{const t=Object(Ce.a)(ye.a.Extra,"Errors",!e);return t?c.a.createElement(t,null):void 0});var En=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"ForwardPicker",!t);return a?c.a.createElement(a,e):void 0});var wn=Object(c.h)(e=>{const{url:t}=e,a=Object(Ce.a)(ye.a.Extra,"SafeLinkModal",!t);return a?c.a.createElement(a,e):void 0});var Mn=Object(c.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"HistoryCalendar",!t);return a?c.a.createElement(a,e):void 0});a(251);let Sn,kn,Nn=!1;function Pn(e){document.querySelectorAll('link[rel="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")})}var Tn=Object(c.h)(Object(s.h)(e=>{const{chatId:t,messageId:a}=e.audioPlayer,s=t&&a?Object(o.k)(e,t,a):void 0;return{animationLevel:e.settings.byKey.animationLevel,lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:Object(o.W)(e),isMediaViewerOpen:Object(o.T)(e),isForwardModalOpen:Object(o.R)(e),hasNotifications:Boolean(e.notifications.length),hasErrors:Boolean(e.errors.length),audioMessage:s,safeLinkModalUrl:e.safeLinkModalUrl,isHistoryCalendarOpen:Boolean(e.historyCalendarSelectedAt)}},(e,t)=>Object(d.l)(t,["loadAnimatedEmojis"]))(({lastSyncTime:e,isLeftColumnShown:t,isRightColumnShown:a,isMediaViewerOpen:r,isForwardModalOpen:i,animationLevel:l,hasNotifications:d,hasErrors:b,audioMessage:u,safeLinkModalUrl:m,isHistoryCalendarOpen:h,loadAnimatedEmojis:O})=>{n.p&&!Nn&&(Nn=!0,console.log(">>> RENDER MAIN")),Object(c.n)(()=>{e&&O()},[e,O]);const{transitionClassNames:j}=Object(Z.a)(!t,void 0,!0),{transitionClassNames:g}=Object(Z.a)(a,void 0,!0),f=Object(J.a)(j.replace(/([\w-]+)/g,"middle-column-$1"),g.replace(/([\w-]+)/g,"right-column-$1"));function p(e){e.preventDefault(),e.stopPropagation()}return Object(c.n)(()=>{document.body.classList.toggle("is-middle-column-open",f.includes("middle-column-open")),document.body.classList.toggle("is-right-column-shown",f.includes("right-column-open"))},[f]),Object(c.n)(()=>{l>0&&(document.body.classList.add("animating-right-column"),Object(X.b)(350+n.c),Sn&&(clearTimeout(Sn),Sn=void 0),Sn=window.setTimeout(()=>{document.body.classList.remove("animating-right-column"),Sn=void 0},350+n.c))},[l,a]),Object(ee.a)(()=>{const e=Object(o.q)(Object(s.e)());let t=0;clearInterval(kn),kn=window.setInterval(()=>{if(document.title.includes(n.D))Pn(!1);else{if(t%2==0){const t=Object(o.q)(Object(s.e)())-e;t>0&&(document.title=`${t} notification${t>1?"s":""}`,Pn(!0))}else document.title=n.eb,Pn(!1);t++}},1e3)},()=>{clearInterval(kn),kn=void 0,document.title.includes(n.D)||(document.title=n.eb),Pn(!1)}),c.a.createElement("div",{id:"Main",className:f,onDrop:p,onDragOver:p},c.a.createElement(Be,null),c.a.createElement(qs,null),c.a.createElement(In,null),c.a.createElement(vn,{isOpen:r}),c.a.createElement(En,{isOpen:i}),c.a.createElement(yn,{isOpen:d}),c.a.createElement(Cn,{isOpen:b}),u&&c.a.createElement(mt,{key:u.id,message:u,noUi:!0}),c.a.createElement(wn,{url:m}),c.a.createElement(Mn,{isOpen:h}))}));n.p&&console.log(">>> FINISH LOAD MAIN BUNDLE"),Object(s.e)().connectionState||Object(s.d)().initApi()},197:function(e,t,a){},198:function(e,t,a){},199:function(e,t,a){},210:function(e,t,a){},211:function(e,t,a){},212:function(e,t,a){},215:function(e,t,a){},216:function(e,t,a){},217:function(e,t,a){},221:function(e,t,a){},222:function(e,t,a){},224:function(e,t,a){},227:function(e,t,a){},228:function(e,t,a){},229:function(e,t,a){},230:function(e,t,a){},231:function(e,t,a){},232:function(e,t,a){},233:function(e,t,a){},234:function(e,t,a){},235:function(e,t,a){},236:function(e,t,a){},237:function(e,t,a){},239:function(e,t,a){},240:function(e,t,a){},241:function(e,t,a){},242:function(e,t,a){},243:function(e,t,a){},244:function(e,t,a){},245:function(e,t,a){},249:function(e,t,a){},250:function(e,t,a){},251:function(e,t,a){}}]); +//# sourceMappingURL=4.75225d931a1e76f26855.js.map \ No newline at end of file diff --git a/dist/4.75225d931a1e76f26855.js.map b/dist/4.75225d931a1e76f26855.js.map new file mode 100644 index 00000000..32489b92 --- /dev/null +++ b/dist/4.75225d931a1e76f26855.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///./src/modules/actions/ui/chats.ts","webpack:///./src/modules/actions/ui/messages.ts","webpack:///./src/modules/actions/ui/globalSearch.ts","webpack:///./src/modules/actions/ui/localSearch.ts","webpack:///./src/modules/actions/ui/stickerSearch.ts","webpack:///./src/modules/actions/ui/users.ts","webpack:///./src/modules/actions/ui/settings.ts","webpack:///./src/modules/actions/ui/misc.ts","webpack:///./src/modules/actions/ui/payments.ts","webpack:///./src/modules/actions/api/chats.ts","webpack:///./src/modules/actions/api/messages.ts","webpack:///./src/modules/actions/api/symbols.ts","webpack:///./src/modules/actions/api/globalSearch.ts","webpack:///./src/modules/actions/api/sync.ts","webpack:///./src/modules/actions/api/localSearch.ts","webpack:///./src/modules/actions/api/management.ts","webpack:///./src/modules/actions/api/users.ts","webpack:///./src/modules/actions/api/settings.ts","webpack:///./src/modules/actions/api/bots.ts","webpack:///./src/modules/actions/api/twoFaSettings.ts","webpack:///./src/modules/actions/api/payments.ts","webpack:///./src/util/requestQuery.ts","webpack:///./src/modules/actions/apiUpdaters/chats.ts","webpack:///./src/modules/actions/apiUpdaters/messages.ts","webpack:///./src/modules/actions/apiUpdaters/users.ts","webpack:///./src/modules/actions/apiUpdaters/symbols.ts","webpack:///./src/modules/actions/apiUpdaters/misc.ts","webpack:///./src/modules/actions/apiUpdaters/settings.ts","webpack:///./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack:///./src/components/ui/Switcher.tsx","webpack:///./src/components/left/main/LeftMainHeader.tsx","webpack:///./src/components/left/ConnectionState.tsx","webpack:///./src/hooks/useThrottledMemo.ts","webpack:///./src/hooks/useThrottle.ts","webpack:///./src/components/left/main/ChatFolders.tsx","webpack:///./src/components/left/search/LeftSearch.async.tsx","webpack:///./src/components/left/main/ContactList.async.tsx","webpack:///./src/components/left/NewChatButton.tsx","webpack:///./src/components/left/main/LeftMain.tsx","webpack:///./src/components/left/settings/Settings.async.tsx","webpack:///./src/components/left/newChat/NewChat.async.tsx","webpack:///./src/components/left/ArchivedChats.async.tsx","webpack:///./src/components/left/LeftColumn.tsx","webpack:///./src/hooks/useWindowSize.ts","webpack:///./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack:///./src/components/middle/HeaderMenuContainer.async.tsx","webpack:///./src/components/middle/HeaderActions.tsx","webpack:///./src/hooks/useWebpThumbnail.ts","webpack:///./src/components/middle/PinnedMessageNavigation.tsx","webpack:///./src/components/middle/HeaderPinnedMessage.tsx","webpack:///./src/components/middle/AudioPlayer.tsx","webpack:///./src/components/middle/MiddleHeader.tsx","webpack:///./src/components/middle/helpers/groupMessages.ts","webpack:///./src/components/middle/hooks/useStickyDates.ts","webpack:///./src/hooks/useDebounce.ts","webpack:///./src/components/middle/MessageScroll.tsx","webpack:///./src/components/middle/message/helpers/buildContentClassName.ts","webpack:///./src/components/middle/message/helpers/mediaDimensions.ts","webpack:///./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack:///./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack:///./src/components/middle/message/hooks/useFocusMessage.ts","webpack:///./src/components/middle/message/ContextMenuContainer.async.tsx","webpack:///./src/components/middle/ActionMessage.tsx","webpack:///./src/components/common/EmbeddedMessage.tsx","webpack:///./src/components/middle/message/MessageMeta.tsx","webpack:///./src/components/middle/message/Sticker.tsx","webpack:///./src/components/middle/message/hooks/useBlurredMediaThumbRef.ts","webpack:///./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack:///./src/components/middle/message/Photo.tsx","webpack:///./src/hooks/useHeavyAnimationCheckForVideo.ts","webpack:///./src/components/middle/message/hooks/usePauseOnInactive.ts","webpack:///./src/components/middle/message/Video.tsx","webpack:///./src/components/middle/message/Contact.tsx","webpack:///./src/components/ui/CheckboxGroup.tsx","webpack:///./src/components/middle/message/PollOption.tsx","webpack:///./src/components/middle/message/Poll.tsx","webpack:///./src/components/middle/message/WebPage.tsx","webpack:///./src/components/middle/message/Invoice.tsx","webpack:///./src/components/middle/message/hocs/withSelectControl.tsx","webpack:///./src/components/middle/message/Album.tsx","webpack:///./src/components/middle/message/RoundVideo.tsx","webpack:///./src/components/middle/message/InlineButtons.tsx","webpack:///./src/components/middle/message/CommentButton.tsx","webpack:///./src/components/middle/message/Message.tsx","webpack:///./src/components/middle/MessageList.tsx","webpack:///./src/components/middle/ScrollDownButton.tsx","webpack:///./src/components/middle/composer/helpers/buildAttachment.ts","webpack:///./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack:///./src/util/voiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack:///./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack:///./src/components/middle/composer/hooks/useDraft.ts","webpack:///./src/components/common/DeleteMessageModal.async.tsx","webpack:///./src/components/ui/ResponsiveHoverButton.tsx","webpack:///./src/components/middle/composer/AttachMenu.async.tsx","webpack:///./src/components/middle/composer/SymbolMenu.async.tsx","webpack:///./src/components/middle/composer/MentionTooltip.async.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.async.tsx","webpack:///./src/components/middle/composer/StickerTooltip.async.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.async.tsx","webpack:///./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack:///./src/components/middle/composer/AttachmentModal.async.tsx","webpack:///./src/components/middle/composer/PollModal.async.tsx","webpack:///./src/components/middle/composer/DropArea.async.tsx","webpack:///./src/components/middle/composer/WebPagePreview.tsx","webpack:///./src/components/common/CalendarModal.async.tsx","webpack:///./src/components/payment/PaymentModal.async.tsx","webpack:///./src/components/payment/ReceiptModal.async.tsx","webpack:///./src/components/middle/composer/Composer.tsx","webpack:///./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useStickerTooltip.ts","webpack:///./src/util/insertHtmlInSelection.ts","webpack:///./src/util/deleteLastCharacterOutsideSelection.ts","webpack:///./src/components/middle/composer/hooks/useEditing.ts","webpack:///./src/components/middle/MobileSearch.async.tsx","webpack:///./src/components/middle/MessageSelectToolbar.async.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.async.tsx","webpack:///./src/components/middle/MiddleColumn.tsx","webpack:///./src/hooks/useCustomBackground.ts","webpack:///./src/components/right/RightHeader.tsx","webpack:///./src/components/right/hooks/useProfileViewportIds.ts","webpack:///./src/components/right/hooks/useProfileState.ts","webpack:///./src/components/right/ProfilePhoto.tsx","webpack:///./src/components/right/ProfileInfo.tsx","webpack:///./src/components/right/hooks/usePhotosPreload.ts","webpack:///./src/components/right/ChatExtra.tsx","webpack:///./src/components/right/Profile.tsx","webpack:///./src/components/right/hooks/useTransitionFixes.ts","webpack:///./src/hooks/useCacheBuster.ts","webpack:///./src/components/right/RightSearch.async.tsx","webpack:///./src/components/right/management/Management.async.tsx","webpack:///./src/components/right/StickerSearch.async.tsx","webpack:///./src/components/right/GifSearch.async.tsx","webpack:///./src/components/right/PollResults.async.tsx","webpack:///./src/components/right/RightColumn.tsx","webpack:///./src/components/mediaViewer/MediaViewer.async.tsx","webpack:///./src/components/main/Notifications.async.tsx","webpack:///./src/components/main/Errors.async.tsx","webpack:///./src/components/main/ForwardPicker.async.tsx","webpack:///./src/components/main/SafeLinkModal.async.tsx","webpack:///./src/components/main/HistoryCalendar.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["window","addEventListener","e","state","chatId","id","threadId","messageListType","type","getDispatch","openChat","noPushState","addReducer","global","actions","payload","currentMessageList","selectCurrentMessageList","exitMessageSelectMode","messages","contentToBeScheduled","undefined","forwardMessages","toChatId","setGlobal","history","pushState","updateCurrentMessageList","isChatInfoShown","chatCreation","blurTimeout","scrollOffset","replaceThreadParam","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","targetIndexDelta","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","indexOf","toString","length","Number","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","audioPlayer","selectIsRightColumnShown","pollResults","voters","setTimeout","newGlobal","getGlobal","noHighlight","groupedId","groupedChatId","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","Static","includes","direction","Down","Up","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","isPollModalOpen","query","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","filter","unshift","pop","content","updateGlobalSearchContent","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","replaceSettings","theme","settings","replaceThemeSettings","management","byChatId","isActive","IS_MOBILE_SCREEN","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","n","message","splice","push","error","getReadableErrorText","newErrors","errors","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","draftsById","map","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","showNotification","preloadedChatIds","i","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","find","currentUserId","hasUnreadMark","toggleChatUnread","isChatSummaryOnly","requestChatUpdate","user","selectUser","selectThreadTopMessageId","requestThreadInfoUpdate","selectSupportChat","TIPS_USERNAME","oldestChat","selectIsChatPinned","sort","chat1","chat2","date","force","isMuted","title","about","photo","memberIds","progress","ChatCreationProgress","InProgress","createdChannel","channelId","accessHash","Complete","Error","createChannel","createdChat","createGroupChat","folderId","folder","selectChatFolder","shouldBePinned","pinnedChatIds","includedChatIds","newPinnedIds","pinnedId","newIncludedChatIds","folderUpdate","selectChatListType","isPinned","ARCHIVED_FOLDER_ID","isChatArchived","chatFolders","loadChatFolders","recommendedChatFolders","recommended","loadRecommendedChatFolders","emoticon","orderedIds","maxId","recommendedId","description","newFolder","createChatFolder","Math","max","apply","deleteChatFolder","unreadCount","match","RE_TME_INVITE_LINK","exec","RE_TME_LINK","isEnabled","isChatBasicGroup","bannedRights","userId","chatAfterUpdate","members","kickedMembers","isBanned","viewMessages","isUnblocked","m","adminRights","customTitle","adminMembers","isDismissed","updateManagementProgress","ManagementProgress","Promise","all","groups","addedById","reduce","group","addChats","forDiscussionIds","channel","fullChat","isPreHistoryHidden","linkedChatId","activeChatFolder","offset","uploadProgressCallbacks","Map","runThrottledForMarkRead","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","Backwards","Around","round","MESSAGE_LIST_SLICE","Forwards","selectThreadOriginChat","threadInfos","addChatMessagesById","updateOutlyingIds","updateListedIds","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","findClosestIndex","indexForDirection","from","to","slice","areSomeLocal","areAllLocal","sendMessage","params","localId","progressCallback","attachment","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","rafPromise","delete","isRestricted","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","scheduledAt","clearWebPagePreview","value","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","text","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","apiUpdate","draft","replyToMsgId","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","webPagePreview","loadWebPagePreview","options","option","shouldResetVoters","v","a","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","b","scheduledMessages","historyHash","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","loadPinnedMessages","copyTextToClipboard","link","searchThrottled","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","featured","featuredStickers","loadFeaturedStickers","stickerSetAccessHash","stickerSet","selectStickerSet","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","selectEmojiKeywords","isLoading","emojiKeywords","fromVersion","version","keywords","setsById","searchWords","searchStickers","updateStickersForEmoji","loadStickersForEmoji","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","loadAndReplaceArchivedChats","updateUsers","replaceChatListIds","loadAndUpdateUsers","userIds","contactIds","contactList","updatedUsers","localChats","localUsers","globalChats","globalUsers","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","searchMessagesByDate","updateManagement","isUsernameAvailable","afterSyncCallback","DEBUG","console","log","savedUsers","savedPrivateChatIds","savedChats","selectedChat","isChatPrivate","selectedChatUser","replaceChats","loadAndReplaceChats","areMessagesLoaded","draftsByChatId","acc","lastReadInboxMessageId","newCurrentChatId","currentMessageListInfo","threadsById","Array","prototype","concat","replaceUsers","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","sync","afterSync","runDebouncedForFetchFullUser","buildInputPrivacyRules","visibility","allowedIds","deniedIds","usersById","chatsById","rules","collectUsers","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","lastRequestedAt","topPeers","usersHash","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","updateChatMutedState","phone","phoneNumber","updateUser","updateContact","deleteUser","profileId","isPrivate","photos","button","sendBotCommand","command","openTelegramLink","toggleSafeLinkModal","data","alert","isError","showError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bio","profileEdit","ProfileEditProgress","currentUser","Idle","loadedWallpapers","wallpapers","file","previewBlobUrl","URL","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","document","fileName","size","mimeType","wallpaper","firstWallpaper","withLocalMedia","blocked","blockedIds","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","peerType","shouldShowPreviews","updateNotifySettings","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","Shipping","PaymentInfo","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","ShippingInfo","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","join","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","Checkout","sendStipeCredentials","shippingOptionId","saveCredentials","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","runThrottledForUpdateAppBadge","update","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","selectCountNotMutedUnread","updateAppBadge","isNotJoined","listId","typingStatus","senderId","isFromScheduled","isActiveChat","hasUnreadMention","unreadMentionsCount","showNewMessageNotification","messageUpdate","selectCommonBoxChatId","targetChat","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","updateChatListType","chatFoldersById","newChatFoldersById","pick","newOrderedIds","orderedId","folders","replacedMembers","addedMember","deletedMemberId","shouldUpdate","some","deleteIndex","isOwner","isAdmin","membersCount","updateWithLocalMedia","isScheduled","currentMessage","video","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","updateScheduledMessage","updateListedAndViewportIds","firstUnreadId","selectFirstUnreadId","addViewportId","firstMessageId","selectThreadByMessage","isMessageLocal","updateChatLastMessage","currentLastMessage","findLastMessage","isDeleting","deleteMessages","newLastMessage","threadIdsToUpdate","unique","deleteChatMessages","chatsIdsToUpdate","commonBoxChatId","updateThreadInfo","newMessage","isMessageInCurrentMessageList","isOutgoing","scheduledIds","selectScheduledIds","selectScheduledMessages","deleteChatScheduledMessages","currentPinnedIds","selectPinnedIds","newTheadInfo","messagesById","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","poll","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","newResults","targetOption","targetOptionIndex","updatedOption","votersCount","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","key","addNotifyException","twoFaSettings","memo","name","label","checked","disabled","inactive","noAnimation","onChange","onCheck","handleChange","useCallback","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","animationLevel","byKey","globalSearchChatId","searchDate","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","openTipsChat","setGlobalSearchDate","setSettingOption","lang","useLang","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","switchTheme","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","APP_VERSION","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","localStorage","setItem","JSON","stringify","SearchInput","inputId","parentContainerClassName","focused","placeholder","autoComplete","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","connectionState","dir","isRtl","Spinner","resolverFn","ms","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","setActiveChatFolder","transitionRef","useEffect","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","IS_TOUCH_ENV","captureEvents","onSwipe","SwipeDirection","Left","min","Right","isNotInAllTabRef","captureEscKeyListener","handleKeyDown","metaKey","startsWith","digit","preventDefault","removeEventListener","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","folderType","noChatsText","TabList","tabs","activeTab","onSwitchTab","Transition","ref","activeKey","renderCount","props","LeftSearch","useModuleLoader","Bundles","Extra","Loading","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","useState","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","NewChat","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","lastResetTime","setLastResetTime","contentType","NewChannelStep2","NewChannel","NewGroupStep2","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","EditProfile","Folders","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaCongratulations","PrivacyPhoneNumberAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenAllowedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingAllowedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsAllowedContacts","PrivacyGroupChatsDeniedContacts","TwoFaNewPassword","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaNewPasswordEmail","TwoFaNewPasswordEmailCode","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaChangePasswordHint","TwoFaRecoveryEmail","TwoFaRecoveryEmailCode","FoldersCreateFolder","FoldersEditFolder","handleSearchQuery","currentScreen","onScreenSelect","isChannel","setSize","windowSize","handleResize","calculateMiddleFooterTransforms","windowWidth","canPost","sidePadding","MOBILE_SCREEN_MAX_WIDTH","messageListWidth","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","leftColumnWidth","rightColumnWidth","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","HeaderMenuContainer","isChatChannel","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canMute","canSelect","selectIsInSelectMode","canLeave","joinChannel","openLocalTextSearch","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleSearchClick","querySelector","focus","searchInput","fluid","anchor","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","width","height","radius","count","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","style","transform","svg","div","defs","innerHTML","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","useFlag","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","thumbDataUri","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","sender","selectSender","noUi","senderName","getSenderTitle","mediaData","mediaLoader","playPause","isPlaying","useAudioPlayer","getMessageKey","getMediaDuration","handleClick","handleClose","audio","getMessageAudio","performer","renderAudio","subtitle","renderVoice","audioMessage","originChat","messagesCount","pinnedIds","isSelectModeActive","originChatId","isChatWithBot","selectIsChatWithBot","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","openChatWithInfo","pinMessage","toggleLeftColumn","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","chatTitleLength","getChatTitle","topMessageTitle","useEnsureMessage","useWindowSize","isLeftColumnHideable","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","cycleRestrict","handleAllPinnedClick","handleBackClick","messageInput","EDITABLE_INPUT_ID","currentChat","selectIsChatMuted","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","shouldUseStackedToolsClass","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","useCurrentOrPrev","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessageTitle","canRevealTools","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","asClose","unreadCountInfo","formatIntegerCompact","componentEl","add","remove","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDatetime","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","useStickyDates","isScrolled","markIsScrolled","runDebounced","shouldRunFirst","shouldRunLast","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","areToolsFrozen","MessageScroll","focusingId","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","onNotchToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","toggleScrollTools","scrollHeight","scrollBottom","isAtBottom","observe","observeIntersection","freeze","freezeForLoadMore","unfreeze","unfreezeForLoadMore","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","target","resetScroll","useOnIntersect","observeIntersectionForFab","freezeForFab","unfreezeForFab","observeIntersectionForNotch","teactFastList","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","calculateMediaDimensions","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","AlbumRectPart","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","album","ratios","proportions","ratio","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","REM","getMaxWidth","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","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","createElement","font","whiteSpace","position","left","opacity","appendChild","offsetWidth","useFocusMessage","elementRef","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainer","targetUserId","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isEmbedded","appearanceOrder","isLastInList","noAppearanceAnimation","markShown","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","data-message-id","onMouseDown","onContextMenu","EmbeddedMessage","customText","useIsIntersecting","pictogramId","isRoundVideo","getMessageRoundVideo","senderTitle","outgoingStatus","signature","views","isEdited","formatTime","MessageOutgoingStatus","Sticker","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","shouldRenderFullMedia","useTransitionForMedia","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","inSelectMode","isSelected","img","Image","onload","canvas","ctx","getContext","drawImage","getImageData","getAppendixColorFromImage","Photo","shouldAutoLoad","isInSelectMode","uploadProgress","nonInteractive","shouldAffectAppendix","onCancelUpload","localBlobUrl","isDownloadAllowed","setIsDownloadAllowed","shouldDownload","downloadProgress","useMediaWithDownloadProgress","thumbRef","isUploading","isTransferring","transferProgress","getMediaTransferState","wasDownloadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderThumb","isAllowed","contentEl","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","isPlayAllowed","wasPlaying","isFrozen","freezePlaying","paused","unfreezePlaying","unfreezePlayingOnRaf","hasFocus","useBackgroundMode","Video","shouldAutoPlay","videoRef","canPlayInline","canMessagePlayVideoInline","setIsPlayAllowed","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","usePauseOnInactive","useVideoCleanup","videoClassName","shouldRenderInlineVideo","shouldRenderHqPreview","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","duration","contact","openUserInfo","Avatar","formatPhoneNumberWithCode","selected","loadingOptions","setValues","event","newValues","Checkbox","subLabel","getPercentage","toFixed","PollOption","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","floor","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","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","hasDocument","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrapedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","shiftKey","newProps","PhotoWithSelect","VideoWithSelect","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","currentOnRelease","RoundVideo","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","playerEl","playingProgressEl","stopPlaying","requestAnimationFrame","capturePlaying","onRelease","ROUND_VIDEO_DIMENSIONS","onEnded","InlineButtons","recentReplierIds","recentRepliers","hasUnread","data-cnt","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","forceSenderName","isAnonymousOwnMessage","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","selectOutgoingStatus","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","shouldAutoLoadMedia","selectShouldAutoLoadMedia","shouldAutoPlayMedia","selectShouldAutoPlayMedia","shouldLoopStickers","selectShouldLoopStickers","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","clickInlineButton","bottomMarkerRef","appendixRef","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","voice","getMessageCustomShape","textParts","renderMessageText","containerClassName","contentClassName","hasComments","classNames","isMediaWithNoText","isViaBot","isRound","buildContentClassName","avatarPeer","senderPeer","adminTitle","withCommentButton","withAppendix","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","fromMessageId","calculatedWidth","noMediaCorners","extraPadding","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","markMessageListRead","setScrollOffset","openHistoryCalendar","scrollOffsetRef","selectScrollOffset","anchorIdRef","anchorTopRef","listItemElementsRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","freezeForMedia","unfreezeForMedia","throttleMs","observeIntersectionForReading","freezeForReading","unfreezeForReading","mentionIds","entry","dataset","messageGroups","listedMessages","orderBy","loadMoreAround","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","windowHeight","normalHeight","String","clientHeight","preservedItemElements","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","lastItemElement","lastItemHeight","newScrollTop","hasFirstMessageChanged","hasLastMessageChanged","isAlreadyFocusing","isResized","unreadDivider","isAnimatingScroll","dispatchHeavyAnimationEvent","ANIMATION_END_DELAY","withUsers","onScroll","currentAnchorIdRef","isSchedule","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","originalId","getMessageOriginalId","SCHEDULED_WHEN_ONLINE","formatHumanDate","renderMessages","focusLastMessage","messageElements","lastMessageElement","buildAttachment","filename","blob","isQuick","quick","preloadImage","newBlob","toBlob","squeezeImage","revokeObjectURL","videoWidth","videoHeight","preloadVideo","createPosterForVideo","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","startedAt","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","volume","subscribeToAnalyzer","stop","reject","onstop","Blob","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","formattedText","currentThreadId","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenu","SymbolMenu","MentionTooltip","CustomSend","StickerTooltipAsync","StickerTooltip","BotKeyboardMenu","forwardMessageIds","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","AttachmentModal","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","parseMessageInput","linkEntity","ApiMessageEntityTypes","TextUrl","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModal","PaymentModal","MainButtonState","ReceiptModal","chatUser","selectChatUser","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardMessageId","canSuggestMembers","isChatGroup","stickersForEmoji","groupChatMembers","isReceiptModalOpen","shouldSuggestStickers","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","closePaymentModal","clearReceipt","addRecentEmoji","loadEmojiKeywords","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","IS_IOS","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","insertMention","mentionFilteredMembers","useMentionTooltip","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","canSendStickers","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","selection","getSelection","newHtml","replace","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","execCommand","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","prevChatId","handleEditComplete","editedMessage","hasMessageMedia","useEditing","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","tagName","EDITABLE_INPUT_MODAL_ID","items","media","getAsFile","pastedText","getData","substring","useClipboardPaste","handleFileSelect","files","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleStickerSelect","handleGifSelect","gif","handlePollSend","handleSilentSend","handleMessageSchedule","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","Portal","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onSend","onFileAppend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSupressFocus","shouldSupressTextFormatter","onUpdate","onSupressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","CLOSE_ANIMATION_DURATION","canBeQuicklyUploaded","kind","CONTENT_TYPES_FOR_QUICK_UPLOAD","isBlurred","isBackgroundBlurred","background","customBackground","backgroundColor","patternColor","themes","isMobileSearchActive","getCanPostInChat","isBotNotStarted","isPinnedMessageList","messageSendingRestrictionReason","getMessageSendingRestrictionReason","hasPinnedOrAudioMessage","loadUser","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanPost","renderingHasTools","renderingIsFabShown","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","footerClassName","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","ANIMATION_LEVEL_MAX","shouldCleanup","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","backButtonRef","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","shouldSkipTransition","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","ManagementScreens","Initial","ManageInitial","ChatPrivacyType","ManageChatPrivacyType","Discussion","ManageDiscussion","ChannelSubscribers","ManageChannelSubscribers","GroupPermissions","ManageGroupPermissions","ChatAdministrators","ManageChatAdministrators","GroupRemovedUsers","ManageGroupRemovedUsers","GroupUserPermissionsCreate","ManageGroupUserPermissionsCreate","GroupUserPermissions","ManageGroupUserPermissions","GroupRecentActions","ManageGroupRecentActions","ChatAdminRights","ManageGroupAdminRights","GroupMembers","ManageGroupMembers","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","useProfileViewportIds","loadMoreMembers","searchMessages","tabType","mediaSearchType","resultType","sortUserIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","currentResultType","handleLoadMore","getMore","useInfiniteScroll","MEMBERS_SLICE","isOnTop","useInfiniteScrollForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","useInfiniteScrollForSharedMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","noProfileInfo","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","isFirstPhoto","isSavedMessages","isDeleted","isDeletedUser","getMediaHash","forceAvatar","getChatAvatarHash","imageHash","ApiMediaFormat","BlobUrl","avatarThumbnailData","useBlurSync","dataUri","imageSrc","prevImageSrc","decoding","userFullName","getUserFullName","getFirstLetters","fullClassName","forceShowSelf","loadFullUser","fullName","slideAnimation","currentPhotoIndex","setCurrentPhotoIndex","isFirst","isLast","profile","currentIndex","usePhotosPreload","handleProfilePhotoClick","ProfileAvatar","selectPreviousMedia","selectNextMedia","excludedClosestSelector","renderPhoto","isVerifiedIconShown","isVerified","renderPhotoTabs","aria-label","VerifiedIcon","isUserOnline","getUserStatus","canInviteUsers","isUserRightBanned","getHasAdminRight","currentIsMuted","chatUsername","handleNotificationChange","copy","entity","formattedNumber","getChatLink","printedUsername","getChatDescription","ListItem","multiline","narrow","isStatic","TABS","buildInfiniteScrollItemSelector","isGroup","hasMembersTab","areMembersHidden","canViewMembers","resolvedUserId","onProfileStateChange","setLocalMediaSearchType","searchMediaMessagesLocal","loadProfilePhotos","setActiveTab","useEffectWithPrevDeps","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","renderingFor","teactOrderKey","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","renderProfileInfo","shouldRestoreHeight","onStart","onStop","big","RightSearch","Management","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","onChatMemberSelect","prevContentKey","MediaViewer","Errors","ForwardPicker","SafeLinkModal","HistoryCalendar","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasErrors","isHistoryCalendarOpen","middleColumnTransitionClassNames","rightColumnTransitionClassNames","stopEvent","initialUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","onDrop","onDragOver","initApi"],"mappings":"uLAOAA,OAAOC,iBAAiB,WAAaC,IACnC,IAAKA,EAAEC,MACL,OAGF,MAAQC,OAAQC,EAAV,SAAcC,EAAUC,gBAAiBC,GAASN,EAAEC,MAE1DM,cAAcC,SAAS,CACrBL,KAAIC,WAAUE,OAAMG,aAAa,MAIrCC,YAAW,WAAY,CAACC,EAAQC,EAASC,KACvC,MAAM,GACJV,EADI,SACAC,GAAW,EADX,KACeE,EAAO,SADtB,YACgCG,GAClCI,EAEEC,EAAqBC,YAAyBJ,GA4BpD,OA1BKG,GAEDA,EAAmBZ,SAAWC,GAC3BW,EAAmBV,WAAaA,GAChCU,EAAmBR,OAASA,IAEjCK,EAASK,YAAsBL,GAE/BA,EAAS,IACJA,EACHM,SAAU,IACLN,EAAOM,SACVC,0BAAsBC,MAEpBhB,IAAOQ,EAAOS,gBAAgBC,UAAY,CAC5CD,gBAAiB,KAIrBE,YAAUX,GAELF,GACHX,OAAOyB,QAAQC,UAAU,CAAEtB,OAAQC,EAAIC,WAAUC,gBAAiBC,GAAQ,KAIvEmB,YAAyBd,EAAQR,EAAIC,EAAUE,KAGxDI,YAAW,mBAAoB,CAACC,EAAQC,EAASC,KAC/CS,YAAU,IACLX,EACHe,iBAAiB,IAGnBd,EAAQJ,SAASK,K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D,IACrB,kBAAC,GAAD,CAAezzD,OAAQ2zD,IACvB,kBAAC,GAAD,CAAe3zD,OAAQ6zD,IACvB,kBAAC,GAAD,CAAQ7zD,OAAQ8zD,IACfp8C,GAAgB,kBAAC,GAAD,CAAa3a,IAAK2a,EAAavvC,GAAI6J,QAAS0lC,EAAclB,MAAI,IAC/E,kBAAC,GAAD,CAAe/jC,IAAKC,IACpB,kBAAC,GAAD,CAAiBstB,OAAQ+zD,QC1K3B1pE,KAEFC,QAAQC,IAAI,+BAGT9d,cAAYu2B,iBACfz6B,cAAcosF,W","file":"4.75225d931a1e76f26855.js","sourcesContent":["import { addReducer, getDispatch, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\n\nwindow.addEventListener('popstate', (e) => {\n if (!e.state) {\n return;\n }\n\n const { chatId: id, threadId, messageListType: type } = e.state;\n\n getDispatch().openChat({\n id, threadId, type, noPushState: true,\n });\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', noPushState,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = exitMessageSelectMode(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n\n if (!noPushState) {\n window.history.pushState({ chatId: id, threadId, messageListType: type }, '');\n }\n }\n\n return updateCurrentMessageList(global, id, threadId, type);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\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, selectIsViewportNewest, selectReplyingToId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\n\nconst FOCUS_DURATION = 2000;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('replyToNextMessage', (global, actions, payload) => {\n const { targetIndexDelta } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return;\n }\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const isLatest = selectIsViewportNewest(global, chatId, threadId);\n\n let messageId: number | undefined;\n\n if (!isLatest || !replyingToId) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n messageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n messageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n } else {\n const chatMessageKeys = Object.keys(chatMessages);\n const indexOfCurrent = chatMessageKeys.indexOf(replyingToId.toString());\n const newIndex = indexOfCurrent + targetIndexDelta;\n messageId = newIndex <= chatMessageKeys.length + 1 && newIndex >= 0\n ? Number(chatMessageKeys[newIndex])\n : undefined;\n }\n actions.setReplyingToId({ messageId });\n actions.focusMessage({\n chatId, threadId, messageId,\n });\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {},\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids && 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 }, FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight);\n global = updateFocusDirection(global, undefined);\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n actions.exitMessageSelectMode();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n return toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n});\n\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\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';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n});\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global, actions, payload) => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n const { id } = payload!;\n\n return {\n ...global,\n isLeftColumnShown: id === undefined,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: 0,\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global) => {\n const newNotifications = [...global.notifications];\n\n newNotifications.pop();\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showError', (global, actions, payload) => {\n const { error } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if (!getReadableErrorText(error)) {\n return global;\n }\n\n const newErrors = [...global.errors];\n const existingErrorIndex = newErrors.findIndex((err) => err.message === error.message);\n if (existingErrorIndex !== -1) {\n newErrors.splice(existingErrorIndex, 1);\n }\n\n newErrors.push(error);\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('dismissError', (global) => {\n const newErrors = [...global.errors];\n\n newErrors.pop();\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddReducer('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddReducer('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\nimport {\n clearPayment, closeInvoice,\n} from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiUser, ApiChatFolder, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { ChatCreationProgress, ManagementProgress } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n ARCHIVED_FOLDER_ID,\n TOP_CHAT_MESSAGES_PRELOAD_LIMIT,\n CHAT_LIST_LOAD_SLICE,\n RE_TME_INVITE_LINK,\n RE_TME_LINK,\n TIPS_USERNAME,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n addChats,\n addUsers,\n replaceThreadParam,\n updateChatListIds,\n updateChats,\n updateChat,\n updateChatListSecondaryInfo,\n updateManagementProgress,\n} from '../../reducers';\nimport {\n selectChat,\n selectCurrentChat,\n selectUser,\n selectChatListType,\n selectIsChatPinned,\n selectChatFolder,\n selectSupportChat,\n selectChatByUsername,\n selectThreadTopMessageId,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce, pause, throttle } from '../../../util/schedulers';\nimport {\n isChatSummaryOnly, isChatArchived, prepareChatList, isChatBasicGroup,\n} from '../../helpers';\n\nconst TOP_CHATS_PRELOAD_PAUSE = 100;\n// We expect this ID does not exist\nconst TMP_CHAT_ID = -1;\n\nconst runThrottledForLoadChats = throttle((cb) => cb(), 1000, true);\nconst runThrottledForLoadTopChats = throttle((cb) => cb(), 3000, true);\nconst runDebouncedForLoadFullChat = debounce((cb) => cb(), 500, false, true);\n\naddReducer('preloadTopChatMessages', (global, actions) => {\n (async () => {\n const preloadedChatIds: number[] = [];\n\n for (let i = 0; i < TOP_CHAT_MESSAGES_PRELOAD_LIMIT; i++) {\n await pause(TOP_CHATS_PRELOAD_PAUSE);\n\n const {\n byId,\n listIds: { active: listIds },\n orderedPinnedIds: { active: orderedPinnedIds },\n } = getGlobal().chats;\n if (!listIds) {\n return;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const { pinnedChats, otherChats } = prepareChatList(byId, listIds, orderedPinnedIds);\n const topChats = [...pinnedChats, ...otherChats];\n const chatToPreload = topChats.find(({ id }) => id !== currentChatId && !preloadedChatIds.includes(id));\n if (!chatToPreload) {\n return;\n }\n\n preloadedChatIds.push(chatToPreload.id);\n\n actions.loadViewportMessages({ chatId: chatToPreload.id, threadId: MAIN_THREAD_ID });\n }\n })();\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const { id, threadId } = payload!;\n const { currentUserId } = global;\n const chat = selectChat(global, id);\n\n if (chat && chat.hasUnreadMark) {\n actions.toggleChatUnread({ id });\n }\n\n if (!chat) {\n if (id === currentUserId) {\n void callApi('fetchChat', { type: 'self' });\n } else {\n const user = selectUser(global, id);\n if (user) {\n void callApi('fetchChat', { type: 'user', user });\n }\n }\n } else if (isChatSummaryOnly(chat) && !chat.isMin) {\n actions.requestChatUpdate({ chatId: id });\n }\n\n if (threadId !== MAIN_THREAD_ID) {\n const topMessageId = selectThreadTopMessageId(global, id, threadId);\n if (!topMessageId) {\n actions.requestThreadInfoUpdate({ chatId: id, threadId });\n }\n }\n});\n\naddReducer('openSupportChat', (global, actions) => {\n const chat = selectSupportChat(global);\n\n actions.openChat({ id: chat ? chat.id : TMP_CHAT_ID });\n\n if (chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchChat', { type: 'support' });\n if (result) {\n actions.openChat({ id: result.chatId });\n }\n })();\n});\n\naddReducer('openTipsChat', (global, actions) => {\n actions.openChatByUsername({ username: TIPS_USERNAME });\n});\n\naddReducer('loadMoreChats', (global, actions, payload) => {\n const { listType = 'active' } = payload!;\n const listIds = global.chats.listIds[listType as ('active' | 'archived')];\n const isFullyLoaded = global.chats.isFullyLoaded[listType as ('active' | 'archived')];\n\n if (isFullyLoaded) {\n return;\n }\n\n const oldestChat = listIds\n ? listIds\n .map((id) => global.chats.byId[id])\n .filter((chat) => Boolean(chat && chat.lastMessage) && !selectIsChatPinned(global, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n if (oldestChat) {\n runThrottledForLoadChats(() => loadChats(listType, oldestChat.id, oldestChat.lastMessage!.date));\n } else {\n runThrottledForLoadChats(() => loadChats(listType));\n }\n});\n\naddReducer('loadFullChat', (global, actions, payload) => {\n const { chatId, force } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n if (force) {\n loadFullChat(chat);\n } else {\n runDebouncedForLoadFullChat(() => loadFullChat(chat));\n }\n});\n\naddReducer('loadTopChats', () => {\n runThrottledForLoadTopChats(() => loadChats('active'));\n});\n\naddReducer('requestChatUpdate', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', chat);\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('updateChatMutedState', { chat, isMuted });\n});\n\naddReducer('createChannel', (global, actions, payload) => {\n const {\n title, about, photo, memberIds,\n } = payload!;\n\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createChannel(title, members, about, photo);\n});\n\naddReducer('joinChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('joinChannel', { channelId, accessHash });\n }\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n (async () => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n await callApi('leaveChannel', { channelId, accessHash });\n }\n\n actions.openChat({ id: undefined });\n })();\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n (async () => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n await callApi('deleteChannel', { channelId, accessHash });\n }\n\n actions.openChat({ id: undefined });\n })();\n});\n\naddReducer('createGroupChat', (global, actions, payload) => {\n const { title, memberIds, photo } = payload!;\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createGroupChat(title, members, photo);\n});\n\naddReducer('toggleChatPinned', (global, actions, payload) => {\n const { id, folderId } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n if (folderId) {\n const folder = selectChatFolder(global, folderId);\n if (folder) {\n const shouldBePinned = !selectIsChatPinned(global, id, folderId);\n\n const { pinnedChatIds, includedChatIds } = folder;\n const newPinnedIds = shouldBePinned\n ? [id, ...(pinnedChatIds || [])]\n : (pinnedChatIds || []).filter((pinnedId) => pinnedId !== id);\n\n // With both Pin and Unpin we need to re-add a user to the included group\n const newIncludedChatIds = [id, ...includedChatIds];\n\n void callApi('editChatFolder', {\n id: folderId,\n folderUpdate: {\n ...folder,\n pinnedChatIds: newPinnedIds,\n includedChatIds: newIncludedChatIds,\n },\n });\n }\n } else {\n const listType = selectChatListType(global, id);\n const isPinned = selectIsChatPinned(global, id, listType === 'archived' ? ARCHIVED_FOLDER_ID : undefined);\n void callApi('toggleChatPinned', { chat, shouldBePinned: !isPinned });\n }\n});\n\naddReducer('toggleChatArchived', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n void callApi('toggleChatArchived', {\n chat,\n folderId: isChatArchived(chat) ? 0 : ARCHIVED_FOLDER_ID,\n });\n }\n});\n\naddReducer('loadChatFolders', () => {\n void loadChatFolders();\n});\n\naddReducer('loadRecommendedChatFolders', () => {\n void loadRecommendedChatFolders();\n});\n\naddReducer('editChatFolder', (global, actions, payload) => {\n const { id, folderUpdate } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void callApi('editChatFolder', {\n id,\n folderUpdate: {\n id,\n emoticon: folder.emoticon,\n pinnedChatIds: folder.pinnedChatIds,\n ...folderUpdate,\n },\n });\n }\n});\n\naddReducer('addChatFolder', (global, actions, payload) => {\n const { folder } = payload!;\n const { orderedIds } = global.chatFolders;\n const maxId = orderedIds && orderedIds.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID;\n\n void createChatFolder(folder, maxId);\n});\n\naddReducer('deleteChatFolder', (global, actions, payload) => {\n const { id } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void deleteChatFolder(id);\n }\n});\n\naddReducer('toggleChatUnread', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { chat, threadId: MAIN_THREAD_ID });\n } else {\n void callApi('toggleDialogUnread', {\n chat,\n hasUnreadMark: !chat.hasUnreadMark,\n });\n }\n }\n});\n\naddReducer('openTelegramLink', (global, actions, payload) => {\n const { url } = payload!;\n let match = RE_TME_INVITE_LINK.exec(url);\n\n if (match) {\n const hash = match[1];\n\n (async () => {\n const chat = await callApi('openChatByInvite', hash);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n })();\n } else {\n match = RE_TME_LINK.exec(url)!;\n\n const username = match[1];\n const channelPostId = match[2] ? Number(match[2]) : undefined;\n\n void openChatByUsername(actions, username, channelPostId);\n }\n});\n\naddReducer('openChatByUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n void openChatByUsername(actions, username);\n});\n\naddReducer('togglePreHistoryHidden', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n let chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n void callApi('togglePreHistoryHidden', { chat, isEnabled });\n })();\n});\n\naddReducer('updateChatDefaultBannedRights', (global, actions, payload) => {\n const { chatId, bannedRights } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('updateChatDefaultBannedRights', { chat, bannedRights });\n});\n\naddReducer('updateChatMemberBannedRights', (global, actions, payload) => {\n const { chatId, userId, bannedRights } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatMemberBannedRights', { chat, user, bannedRights });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { members, kickedMembers } = chatAfterUpdate.fullInfo;\n\n const isBanned = !!bannedRights.viewMessages;\n const isUnblocked = !Object.keys(bannedRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(members && isBanned && {\n members: members.filter((m) => m.userId !== userId),\n }),\n ...(members && !isBanned && {\n members: members.map((m) => (\n m.userId === userId\n ? { ...m, bannedRights }\n : m\n )),\n }),\n ...(isUnblocked && kickedMembers && {\n kickedMembers: kickedMembers.filter((m) => m.userId !== userId),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChatAdmin', (global, actions, payload) => {\n const {\n chatId, userId, adminRights, customTitle,\n } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatAdmin', {\n chat, user, adminRights, customTitle,\n });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { adminMembers } = chatAfterUpdate.fullInfo;\n\n const isDismissed = !Object.keys(adminRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(adminMembers && isDismissed && {\n adminMembers: adminMembers.filter((m) => m.userId !== userId),\n }),\n ...(adminMembers && !isDismissed && {\n adminMembers: adminMembers.map((m) => (\n m.userId === userId\n ? { ...m, adminRights, customTitle }\n : m\n )),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChat', (global, actions, payload) => {\n const {\n chatId, title, about, photo,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n await Promise.all([\n chat.title !== title\n ? callApi('updateChatTitle', chat, title)\n : undefined,\n chat.fullInfo && chat.fullInfo.about !== about\n ? callApi('updateChatAbout', chat, about)\n : undefined,\n photo\n ? callApi('editChatPhoto', { chatId, accessHash: chat.accessHash, photo })\n : undefined,\n ]);\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n })();\n});\n\naddReducer('toggleSignatures', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('toggleSignatures', { chat, isEnabled });\n});\n\naddReducer('loadGroupsForDiscussion', () => {\n (async () => {\n const groups = await callApi('fetchGroupsForDiscussion');\n if (!groups) {\n return;\n }\n\n const addedById = groups.reduce((result, group) => {\n if (group) {\n result[group.id] = group;\n }\n\n return result;\n }, {} as Record);\n\n const global = addChats(getGlobal(), addedById);\n setGlobal({\n ...global,\n chats: {\n ...global.chats,\n forDiscussionIds: Object.keys(addedById).map(Number),\n },\n });\n })();\n});\n\naddReducer('linkDiscussionGroup', (global, actions, payload) => {\n const { channelId, chatId } = payload!;\n\n const channel = selectChat(global, channelId);\n let chat = selectChat(global, chatId);\n if (!channel || !chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n let { fullInfo } = chat;\n if (!fullInfo) {\n const fullChat = await callApi('fetchFullChat', chat);\n if (!fullChat) {\n return;\n }\n\n fullInfo = fullChat.fullInfo;\n }\n\n if (fullInfo.isPreHistoryHidden) {\n await callApi('togglePreHistoryHidden', { chat, isEnabled: false });\n }\n\n void callApi('setDiscussionGroup', { channel, chat });\n })();\n});\n\naddReducer('unlinkDiscussionGroup', (global, actions, payload) => {\n const { channelId } = payload!;\n\n const channel = selectChat(global, channelId);\n if (!channel) {\n return;\n }\n\n let chat: ApiChat | undefined;\n if (channel.fullInfo && channel.fullInfo.linkedChatId) {\n chat = selectChat(global, channel.fullInfo.linkedChatId);\n }\n\n (async () => {\n await callApi('setDiscussionGroup', { channel });\n if (chat) {\n loadFullChat(chat);\n }\n })();\n});\n\n\naddReducer('setActiveChatFolder', (global, actions, payload) => {\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n activeChatFolder: payload,\n },\n };\n});\n\naddReducer('loadMoreMembers', (global) => {\n (async () => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n if (!chat || isChatBasicGroup(chat)) {\n return;\n }\n\n const offset = (chat.fullInfo && chat.fullInfo.members && chat.fullInfo.members.length) || undefined;\n const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset);\n if (!result) {\n return;\n }\n\n const { members, users } = result;\n if (!members || !members.length) {\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: [\n ...((chat.fullInfo || {}).members || []),\n ...(members || []),\n ],\n },\n });\n setGlobal(global);\n })();\n});\n\nasync function loadChats(listType: 'active' | 'archived', offsetId?: number, offsetDate?: number) {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n offsetDate,\n archived: listType === 'archived',\n withPinned: getGlobal().chats.orderedPinnedIds[listType] === undefined,\n });\n\n if (!result) {\n return;\n }\n\n const { chatIds } = result;\n\n if (chatIds.length > 0 && chatIds[0] === offsetId) {\n chatIds.shift();\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChatListIds(global, listType, chatIds);\n global = updateChatListSecondaryInfo(global, listType, result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n\n if (chatIds.length === 0 && !global.chats.isFullyLoaded[listType]) {\n global = {\n ...global,\n chats: {\n ...global.chats,\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [listType]: true,\n },\n },\n };\n }\n\n setGlobal(global);\n}\n\nasync function loadFullChat(chat: ApiChat) {\n const result = await callApi('fetchFullChat', chat);\n if (!result) {\n return;\n }\n\n const { users, fullInfo } = result;\n\n let global = getGlobal();\n if (users) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n global = updateChat(global, chat.id, { fullInfo });\n\n setGlobal(global);\n}\n\nasync function createChannel(title: string, users: ApiUser[], about?: string, photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChannel = await callApi('createChannel', { title, about, users });\n if (!createdChannel) {\n return;\n }\n\n const { id: channelId, accessHash } = createdChannel;\n\n let global = getGlobal();\n global = updateChat(global, channelId, createdChannel);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChannel ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: channelId });\n\n if (channelId && accessHash && photo) {\n await callApi('editChatPhoto', { chatId: channelId, accessHash, photo });\n }\n}\n\nasync function createGroupChat(title: string, users: ApiUser[], photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChat = await callApi('createGroupChat', { title, users });\n if (!createdChat) {\n return;\n }\n\n const { id: chatId } = createdChat;\n\n let global = getGlobal();\n global = updateChat(global, chatId, createdChat);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChat ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: chatId });\n\n if (chatId && photo) {\n await callApi('editChatPhoto', { chatId, photo });\n }\n}\n\nasync function loadChatFolders() {\n const chatFolders = await callApi('fetchChatFolders');\n\n if (chatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n ...chatFolders,\n },\n });\n }\n}\n\nasync function loadRecommendedChatFolders() {\n const recommendedChatFolders = await callApi('fetchRecommendedChatFolders');\n\n if (recommendedChatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommendedChatFolders,\n },\n });\n }\n}\n\nasync function createChatFolder(folder: ApiChatFolder, maxId: number) {\n // Clear fields from recommended folders\n const { id: recommendedId, description, ...newFolder } = folder;\n\n await callApi('editChatFolder', {\n id: maxId + 1,\n folderUpdate: {\n id: maxId + 1,\n ...newFolder,\n },\n });\n\n if (!description) {\n return;\n }\n\n const global = getGlobal();\n const { recommended } = global.chatFolders;\n\n if (recommended) {\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommended.filter(({ id }) => id !== recommendedId),\n },\n });\n }\n}\n\nasync function deleteChatFolder(id: number) {\n await callApi('deleteChatFolder', id);\n}\n\nasync function openChatByUsername(\n actions: GlobalActions,\n username: string,\n channelPostId?: number,\n) {\n const global = getGlobal();\n const localChat = selectChatByUsername(global, username);\n if (localChat && !localChat.isMin) {\n if (channelPostId) {\n actions.focusMessage({ chatId: localChat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: localChat.id });\n }\n return;\n }\n\n const previousChat = selectCurrentChat(global);\n // Open temporary empty chat to make the click response feel faster\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await callApi('getChatByUsername', username);\n if (!chat) {\n if (previousChat) {\n actions.openChat({ id: previousChat.id });\n }\n\n actions.showNotification({ message: 'User does not exist' });\n\n return;\n }\n\n setGlobal(updateChat(getGlobal(), chat.id, chat));\n\n if (channelPostId) {\n actions.focusMessage({ chatId: chat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: chat.id });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE } from '../../../config';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport { areSortedArraysIntersecting, buildCollectionByKey, split } 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} 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} from '../../selectors';\nimport { rafPromise, throttle } from '../../../util/schedulers';\nimport { copyTextToClipboard } from '../../../util/clipboard';\n\nconst uploadProgressCallbacks = new Map();\n\nconst runThrottledForMarkRead = throttle((cb) => cb(), 1000, true);\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const { chatId, messageId, replyOriginForId } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void loadMessage(chat, messageId, replyOriginForId);\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n };\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { 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),\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', draft);\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n (async () => {\n const { chatId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const maxId = chat.lastMessage && chat.lastMessage.id;\n\n await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n\n actions.openChat({ id: undefined });\n })();\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n const { maxId } = payload!;\n\n runThrottledForMarkRead(() => {\n void callApi('markMessageListRead', { chat, threadId, maxId });\n });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global) => {\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 && messages.length) {\n void forwardMessages(fromChat, toChat, messages);\n }\n});\n\naddReducer('loadScheduledHistory', (global) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { hash } = global.scheduledMessages.byChatId[chat.id] || {};\n\n void loadScheduledHistory(chat, hash);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\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 (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;\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;\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\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}) {\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) {\n await rafPromise();\n }\n\n const global = getGlobal();\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\nfunction forwardMessages(\n fromChat: ApiChat,\n toChat: ApiChat,\n messages: ApiMessage[],\n) {\n callApi('forwardMessages', {\n fromChat,\n toChat,\n messages,\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\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 const isUnique = (v: number, i: number, a: number[]) => a.indexOf(v) === i;\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]: [\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ].filter(isUnique),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadMessageLink', (global, actions, payload) => {\n const { messageId, chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchMessageLink', { chat, message });\n\n if (result) {\n copyTextToClipboard(result.link);\n }\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat, historyHash?: number) {\n const result = await callApi('fetchScheduledHistory', { chat, hash: historyHash });\n if (!result) {\n return;\n }\n\n const { hash, 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, hash);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { LangCode } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectEmojiKeywords, selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 500;\nconst ADDED_SETS_THROTTLE_CHUNK = 50;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\naddReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n let currentEmojiKeywords = selectEmojiKeywords(global, language);\n\n if (currentEmojiKeywords && currentEmojiKeywords.isLoading) {\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\n (async () => {\n const emojiKeywords = await callApi('fetchEmojiKeywords', {\n language,\n fromVersion: currentEmojiKeywords ? currentEmojiKeywords.version : 0,\n });\n\n global = getGlobal();\n currentEmojiKeywords = selectEmojiKeywords(global, language);\n\n if (!emojiKeywords) {\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n });\n\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n isLoading: false,\n version: emojiKeywords.version,\n keywords: {\n ...(currentEmojiKeywords && currentEmojiKeywords.keywords),\n ...emojiKeywords.keywords,\n },\n },\n },\n });\n })();\n});\n\nasync function loadStickerSets(hash = 0) {\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 = 0) {\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 = 0) {\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 = 0) {\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) {\n const stickerSet = await callApi('fetchStickers', { stickerSetId, accessHash });\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\nasync function searchStickers(query: string, hash = 0) {\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 = 0) {\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 = 0) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const { nextOffsetId } = (resultsByType && resultsByType[type as ApiGlobalMessageSearchType]) || {};\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: globalUsers.map(({ id }) => id),\n userIds: globalChats.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n updateUsers,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n} from '../../reducers';\nimport {\n selectUser, selectChat, selectCurrentMessageList, selectDraft, selectChatMessage,\n} from '../../selectors';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', (global, actions) => {\n void afterSync(actions);\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync(actions: GlobalActions) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n actions.loadFavoriteStickers();\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n });\n if (!result) {\n return undefined;\n }\n\n let global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isChatPrivate(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n },\n };\n\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n });\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId).map(Number);\n const draftsByChatId = draftChatIds.reduce>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n return draft ? { ...acc, [chatId]: draft } : acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const byId = buildCollectionByKey(result.messages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n [currentChatId]: {\n byId,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfo && currentMessageListInfo.threadsById[MAIN_THREAD_ID]),\n listedIds,\n viewportIds: listedIds,\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).map(Number).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getDispatch().closeAudioPlayer();\n }\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter(Boolean as any);\n\n const updatedUsers = await callApi('fetchUsers', { users });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results ? results.nextOffsetId : undefined;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo ? threadInfo.topMessageId : undefined;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults ? currentResults.nextOffsetId : undefined;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce } from '../../../util/schedulers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateChat, updateManagementProgress, updateUser, updateUsers,\n} from '../../reducers';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60000; // 1 min\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const updatedUsers = await callApi('fetchUsers', { users: [user] });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { hash, lastRequestedAt } = global.topPeers;\n\n if (!lastRequestedAt || Date.now() - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers(hash);\n }\n});\n\naddReducer('loadContactList', (global) => {\n const { hash } = global.contactList || {};\n void loadContactList(hash);\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteUser', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteUser(userId);\n});\n\nasync function loadTopUsers(usersHash?: number) {\n const result = await callApi('fetchTopUsers', { hash: usersHash });\n if (!result) {\n return;\n }\n\n const { hash, 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 hash,\n userIds: ids,\n lastRequestedAt: Date.now(),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList(hash?: number) {\n const contactList = await callApi('fetchContactList', { hash });\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 hash: contactList.hash,\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: number,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n const result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteUser(userId: number) {\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('deleteUser', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isChatPrivate(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, IInputPrivacyRules, IInputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n} from '../../reducers';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers', 0);\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users && result.users.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats && result.chats.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isChatPrivate(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationExceptions', () => {\n callApi('fetchNotificationExceptions');\n});\n\naddReducer('loadNotificationSettings', () => {\n (async () => {\n const result = await callApi('fetchNotificationSettings');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: number[];\n deniedIds: number[];\n}): IInputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: IInputPrivacyRules = {\n visibility,\n };\n let users: IInputPrivacyContact[];\n let chats: IInputPrivacyContact[];\n\n const collectUsers = (userId: number) => {\n if (!isChatPrivate(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: number) => {\n if (isChatPrivate(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 IInputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\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 IInputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\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","import { addReducer, getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { RE_TME_INVITE_LINK, RE_TME_LINK } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChatMessage, selectCurrentChat } from '../../selectors';\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_INVITE_LINK) || button.value.match(RE_TME_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 '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({ messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n if (!currentUserId || !chat) {\n return;\n }\n\n void sendBotCommand(chat, currentUserId, command);\n});\n\nasync function sendBotCommand(chat: ApiChat, currentUserId: number, command: string) {\n await callApi('sendMessage', {\n chat,\n text: command,\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 || !result.message) {\n return;\n }\n\n const { message, alert: isError } = result;\n\n if (isError) {\n getDispatch().showError({ error: { message } });\n } else {\n getDispatch().showNotification({ message });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types/index';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n} from '../../selectors';\n\nimport { getStripeError } from '../../helpers/payments';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const messageId = selectPaymentMessageId(global);\n if (!messageId) {\n return;\n }\n validateRequestedInfo(messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', { messageId, requestInfo, shouldSave });\n if (!result) {\n return;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { messageId } = payload;\n if (!messageId) {\n return;\n }\n getPaymentForm(messageId);\n});\n\n\nasync function getPaymentForm(messageId: number) {\n const result = await callApi('getPaymentForm', { messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n if (!messageId || !receiptMessageId || !chatId) {\n return;\n }\n getReceipt(messageId, receiptMessageId, chatId);\n});\n\nasync function getReceipt(messageId: number, receiptMessageId: number, chatId: number) {\n const result = await callApi('getReceipt', receiptMessageId);\n if (!result) {\n return;\n }\n let global = getGlobal();\n const message = selectChatMessage(global, chatId, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n sendStipeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const messageId = selectPaymentMessageId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!messageId || !publishableKey) {\n return;\n }\n sendPaymentForm(messageId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStipeCredentials(data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n},\npublishableKey: string) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n messageId: number,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n messageId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { showNewMessageNotification } from '../../../util/notifications';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n updateChat,\n replaceChatListIds,\n updateChatListIds,\n updateChatListType,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n selectCountNotMutedUnread,\n} from '../../selectors';\nimport { throttle } from '../../../util/schedulers';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1000;\nconst runThrottledForUpdateAppBadge = throttle((cb) => cb(), CURRENT_CHAT_UNREAD_DELAY, true);\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!update.noTopChatsRequest && !selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n const newGlobal = updateChat(global, update.id, update.chat, update.newProfilePhoto);\n setGlobal(newGlobal);\n\n const unreadCount = selectCountNotMutedUnread(newGlobal);\n runThrottledForUpdateAppBadge(() => updateAppBadge(unreadCount));\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== update.id));\n }\n\n global = updateChat(global, update.id, { isNotJoined: true });\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n const isActiveChat = (\n messageListType === 'thread'\n && threadId === MAIN_THREAD_ID\n && update.chatId === currentChatId\n );\n\n if (isActiveChat) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n const unreadCount = selectCountNotMutedUnread(getGlobal());\n updateAppBadge(unreadCount);\n showNewMessageNotification({ chat, message, isActiveChat });\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = 'channelId' in update ? update.channelId : selectCommonBoxChatId(global, id);\n const chat = selectChat(global, chatId);\n if (chat && chat.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo && targetChat.fullInfo.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat && chat.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n} from '../../selectors';\nimport { getMessageContent, isChatPrivate, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const { chatId, id, message } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content && 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 });\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 (!message.isOutgoing) {\n setTimeout(() => {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n 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, 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 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 && !isChatPrivate(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 ids = Object.keys(global.messages.byChatId[chatId].byId).map(Number);\n\n deleteMessages(chatId, ids, actions, global);\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 && 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});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: number, 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 updateListedAndViewportIds(global: GlobalState, message: ApiMessage) {\n const { id, chatId } = message;\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n // Always keep the first uread message in the viewport list\n const firstUnreadId = selectFirstUnreadId(global, chatId, MAIN_THREAD_ID);\n const newGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(newGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = newGlobal;\n }\n }\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!firstMessageId && isMessageLocal(message)) {\n return global;\n }\n\n if (threadInfo) {\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 if (!threadInfo.lastMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n });\n }\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: number,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId] && 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: number) {\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: number | 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 const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: number[] = [];\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: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteUser, 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: [number, ApiUserStatus][] = [];\n\nfunction scheduleStatusUpdate(userId: number, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates.push([userId, statusUpdate]);\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n let global = getGlobal();\n pendingStatusUpdates.forEach(([userId, statusUpdate]) => {\n global = updateUser(global, userId, {\n status: statusUpdate,\n });\n });\n setGlobal(global);\n\n pendingStatusUpdates = [];\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteUser': {\n return deleteUser(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n hash: 0,\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.shouldShowPreviews);\n }\n\n case 'updateNotifyExceptions': {\n const {\n id, isMuted, isSilent, shouldShowPreviews,\n } = update;\n const chat = global.chats.byId[id];\n\n if (chat) {\n global = updateChat(global, id, { isMuted });\n }\n\n setGlobal(addNotifyException(global, id, { isMuted, isSilent, shouldShowPreviews }));\n break;\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Switcher.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n checked?: boolean;\n disabled?: boolean;\n inactive?: boolean;\n noAnimation?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Switcher: FC = ({\n id,\n name,\n value,\n label,\n checked = false,\n disabled,\n inactive,\n noAnimation,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((e: ChangeEvent) => {\n if (onChange) {\n onChange(e);\n }\n\n if (onCheck) {\n onCheck(e.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Switcher',\n disabled && 'disabled',\n inactive && 'inactive',\n noAnimation && 'no-animation',\n );\n\n return (\n \n );\n};\n\nexport default memo(Switcher);\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport { APP_NAME, APP_VERSION, FEEDBACK_URL } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: number;\n globalSearchChatId?: number;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst LEGACY_VERSION_URL = 'https://web.telegram.org/?legacy=1';\nconst WEBK_VERSION_URL = 'https://web.telegram.org/k/';\nconst PERMANENT_VERSION_KEY = 'kz_version';\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\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 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]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId });\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 switchTheme(newTheme, animationLevel > 0);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const handleSwitchToWebK = () => {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify('K'));\n };\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 \n Switch to K Version\n \n \n Switch to Old Version\n \n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { theme, 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,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'openTipsChat',\n 'setGlobalSearchDate',\n 'setGlobalSearchChatId',\n 'setSettingOption',\n ]),\n)(LeftMainHeader));\n","import React, { FC } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = ({ connectionState }) => {\n const lang = useLang();\n\n const isConnecting = connectionState === 'connectionStateConnecting';\n\n return isConnecting && (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(ConnectionState);\n","import { useRef } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const valueRef = useRef();\n const runThrottled = useThrottle(ms);\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n let isSync = true;\n runThrottled(() => {\n valueRef.current = resolverFn();\n\n if (!isSync) {\n forceUpdate();\n }\n });\n isSync = false;\n }, dependencies);\n\n return valueRef.current;\n};\n","import { useMemo } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (ms: number) => {\n return useMemo(() => {\n return throttle((cb) => cb(), ms);\n }, [ms]);\n};\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { NotifyException, NotifySettings } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { buildCollectionByKey, pick } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../modules/selectors';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n chatFoldersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\n chatsById,\n usersById,\n chatFoldersById,\n notifySettings,\n notifyExceptions,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(chatsById, usersById, folder, chatIds, notifySettings, notifyExceptions) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, chatsById, usersById, notifySettings, notifyExceptions]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: lang('FilterAllChats') },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById && folderCountersById[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById, lang]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveChatFolder(index);\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 onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveChatFolder(Math.min(activeChatFolder + 1, folderTabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveChatFolder(Math.max(0, activeChatFolder - 1));\n }\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 useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.metaKey && 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 });\n return;\n }\n\n const folder = Number(digit) - 1;\n if (folder > folderTabs.length - 1) return;\n\n setActiveChatFolder(folder);\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(({ title }) => title === folderTabs![activeChatFolder].title);\n\n if (!activeFolder || activeChatFolder === 0) {\n return ;\n }\n\n return (\n \n );\n }\n\n return (\n
\n {folderTabs && folderTabs.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n activeChatFolder,\n currentUserId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadChatFolders',\n 'setActiveChatFolder',\n 'openChat',\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, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n {lang('NewMessageTitle')}\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, memo, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\ntype StateProps = {};\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n onSearchQuery,\n onContentChange,\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 return (\n \n \n \n \n {(isActive) => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n \n
\n );\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, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\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};\n\ntype DispatchProps = Pick;\n\nenum ContentType {\n Main,\n // eslint-disable-next-line 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 setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n}) => {\n const [content, setContent] = useState(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\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 (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\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.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n 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, setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId, resetChatCreation,\n settingsScreen,\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, setGlobalSearchQuery, searchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || activeChatFolder === 0\n ? captureEscKeyListener(() => handleReset())\n : undefined),\n [activeChatFolder, content, handleReset],\n );\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n return (\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\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n globalSearch: {\n query,\n date,\n },\n chatFolders: {\n activeChatFolder,\n },\n } = global;\n return { searchQuery: query, searchDate: date, activeChatFolder };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setGlobalSearchQuery', 'setGlobalSearchChatId', 'resetChatCreation', 'setGlobalSearchDate',\n 'loadPasswordInfo', 'clearTwoFaError',\n ]),\n)(LeftColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { IDimensions } from '../modules/helpers';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\n\nconst THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, THROTTLE, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return size;\n};\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? : undefined;\n};\n\nexport default memo(HeaderMenuContainerAsync);\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\nimport { isChatChannel, isChatSuperGroup } from '../../modules/helpers';\nimport {\n selectChat,\n selectIsChatBotNotStarted, selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n}\n\ntype DispatchProps = Pick;\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 canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n isRightColumnShown,\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\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 handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_MOBILE_SCREEN) {\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 const lang = useLang();\n\n return (\n
\n {!IS_MOBILE_SCREEN && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {!IS_MOBILE_SCREEN && canStartBot && (\n \n {lang('Start')}\n \n )}\n {!IS_MOBILE_SCREEN && canSearch && (\n \n \n \n )}\n {(IS_MOBILE_SCREEN || !canSubscribe) && (\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) {\n return {\n noMenu: true,\n };\n }\n\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 canStartBot = Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && chat && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canSelect = !selectIsInSelectMode(global);\n const canLeave = isMainThread && !canSubscribe;\n\n const noMenu = !(\n (IS_MOBILE_SCREEN && canSubscribe)\n || (IS_MOBILE_SCREEN && canSearch)\n || canMute\n || canSelect\n || canLeave\n );\n\n return {\n noMenu,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'joinChannel', 'sendBotCommand', 'openLocalTextSearch',\n ]),\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbnail = message && getMessageMediaThumbDataUri(message);\n const { sticker } = (message && message.content) || {};\n const shouldDecodeThumbnail = thumbnail && sticker && !isWebpSupported() && thumbnail.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message && message.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbnail!)\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, thumbnail]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbnail;\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 && containerRef.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = ` ${clipPath} `;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n \n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `\n \n `\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const lang = useLang();\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(lang, message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n return (\n
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser,\n} from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageAudio, getMessageKey, getMessageMediaHash, getSenderTitle,\n} from '../../modules/helpers';\nimport { selectSender } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiChat | ApiUser;\n};\n\ntype DispatchProps = Pick;\n\nconst AudioPlayer: FC = ({\n message, className, noUi, sender, focusMessage, closeAudioPlayer,\n}) => {\n const lang = useLang();\n\n const senderName = sender ? getSenderTitle(lang, sender) : undefined;\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const { playPause, isPlaying } = useAudioPlayer(\n getMessageKey(message), getMediaDuration(message)!, mediaData, undefined, undefined, true,\n );\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 }, [closeAudioPlayer, isPlaying, playPause]);\n\n if (noUi) {\n return undefined;\n }\n\n const audio = getMessageAudio(message);\n\n return (\n
\n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\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\n return { sender };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage', 'closeAudioPlayer']),\n)(AudioPlayer);\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiTypingStatus,\n MAIN_THREAD_ID, ApiUser,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n isChatPrivate,\n isChatArchived,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n selectIsChatMuted,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadOriginChat,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n selectNotifySettings,\n selectNotifyExceptions,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { pick } from '../../util/iteratees';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n pinnedMessageIds?: number[] | number;\n messagesById?: Record;\n canUnpin?: boolean;\n topMessageSender?: ApiChat | ApiUser;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatsById?: Record;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst MiddleHeader: FC = ({\n chatId,\n threadId,\n messageListType,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageSender,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chat,\n chatsById,\n originChatId,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n notifySettings,\n notifyExceptions,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const lang = useLang();\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) ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : 0);\n const chatTitleLength = chat && getChatTitle(lang, chat).length;\n const topMessageTitle = topMessageSender ? getSenderTitle(lang, topMessageSender) : undefined;\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId]);\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 = windowWidth >= MOBILE_SCREEN_MAX_WIDTH && 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, 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 handleBackClick = useCallback(() => {\n if (IS_MOBILE_SCREEN) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread') {\n if (IS_MOBILE_SCREEN) {\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n return;\n }\n\n if (messageListType === 'scheduled' && isSelectModeActive) {\n exitMessageSelectMode();\n }\n openChat({ id: originChatId, threadId: MAIN_THREAD_ID });\n }, [openChat, originChatId, threadId, messageListType, toggleLeftColumn, isSelectModeActive, exitMessageSelectMode]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n let isActive = false;\n\n const totalCount = Object.values(chatsById).reduce((total, currentChat) => {\n if (isChatArchived(currentChat)) {\n return total;\n }\n\n const count = currentChat.unreadCount || 0;\n if (\n count && (!selectIsChatMuted(currentChat, notifySettings, notifyExceptions) || currentChat.unreadMentionsCount)\n ) {\n isActive = true;\n }\n\n return total + count;\n }, 0);\n\n if (!totalCount) {\n return undefined;\n }\n\n return {\n isActive,\n totalCount,\n };\n }, [isLeftColumnHideable, chatsById, notifySettings, notifyExceptions]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(pinnedMessage && !shouldRenderAudioPlayer);\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage);\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 function renderInfo() {\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n

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

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

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

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

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

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {isLeftColumnHideable && renderBackButton(shouldShowCloseButton, unreadCount)}\n
\n {isChatPrivate(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, unreadCountInfo?: typeof unreadCount) {\n return (\n
\n \n
\n \n {unreadCountInfo && (\n
\n {formatIntegerCompact(unreadCountInfo.totalCount)}\n
\n )}\n
\n );\n }\n\n return (\n
\n \n {renderInfo}\n \n\n
\n {shouldRenderPinnedMessage && renderingPinnedMessage && !shouldRenderAudioPlayer && (\n \n )}\n {shouldRenderAudioPlayer && renderingAudioMessage && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n const originChat = selectThreadOriginChat(global, chatId, threadId);\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds && pinnedIds.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds && scheduledIds.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (threadInfo) {\n messagesCount = threadInfo.messagesCount;\n }\n }\n\n const state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chat,\n chatsById,\n originChatId: originChat ? originChat.id : chatId,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\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 && 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 (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChatWithInfo',\n 'pinMessage',\n 'focusMessage',\n 'openChat',\n 'loadPinnedMessages',\n 'toggleLeftColumn',\n 'exitMessageSelectMode',\n ]),\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDatetime = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDatetime) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDatetime,\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 ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport { debounce } from '../util/schedulers';\n\nexport default function useDebounce(ms: number, shouldRunFirst?: boolean, shouldRunLast?: boolean) {\n return useMemo(() => {\n return debounce((cb) => cb(), ms, shouldRunFirst, shouldRunLast);\n }, [ms, shouldRunFirst, shouldRunLast]);\n}\n","import { MutableRefObject } from 'react';\nimport React, {\n FC, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { MESSAGE_LIST_SENSITIVE_AREA } from '../../config';\nimport resetScroll from '../../util/resetScroll';\nimport { useIntersectionObserver, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\n\ntype OwnProps = {\n containerRef: MutableRefObject;\n className: string;\n messageIds: number[];\n focusingId?: number;\n loadMoreForwards?: NoneToVoidFunction;\n loadMoreBackwards?: NoneToVoidFunction;\n isViewportNewest?: boolean;\n firstUnreadId?: number;\n onFabToggle: AnyToVoidFunction;\n onNotchToggle: AnyToVoidFunction;\n children: any;\n};\n\nconst FAB_THRESHOLD = 50;\nconst TOOLS_FREEZE_TIMEOUT = 100;\n\n// Local flag is used because `freeze/unfreeze` methods are controlled by heavy animation\nlet areToolsFrozen = false;\n\nconst MessageScroll: FC = ({\n containerRef,\n className,\n messageIds,\n focusingId,\n loadMoreForwards,\n loadMoreBackwards,\n isViewportNewest,\n firstUnreadId,\n onFabToggle,\n onNotchToggle,\n children,\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 const toggleScrollTools = useCallback(() => {\n if (areToolsFrozen) {\n return;\n }\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n onNotchToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n onNotchToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = scrollHeight - scrollTop - offsetHeight;\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom <= 0;\n\n onFabToggle(firstUnreadId ? !isAtBottom : !isNearBottom);\n onNotchToggle(!isAtBottom);\n }, [messageIds, isViewportNewest, containerRef, onFabToggle, firstUnreadId, onNotchToggle]);\n\n const {\n observe: observeIntersection,\n freeze: freezeForLoadMore,\n unfreeze: unfreezeForLoadMore,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\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 resetScroll(containerRef.current!);\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger') {\n resetScroll(containerRef.current!);\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,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n const {\n observe: observeIntersectionForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\n\n // Do not load more and show FAB when focusing\n useOnChange(() => {\n if (focusingId) {\n freezeForLoadMore();\n freezeForFab();\n } else {\n unfreezeForFab();\n unfreezeForLoadMore();\n }\n }, [focusingId]);\n\n // Workaround for FAB and notch flickering with tall incoming message\n useOnChange(() => {\n areToolsFrozen = true;\n\n setTimeout(() => {\n areToolsFrozen = false;\n }, TOOLS_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n // Workaround for stuck FAB when many unread messages\n useEffect(toggleScrollTools, [firstUnreadId]);\n\n return (\n
\n
\n {children}\n \n \n
\n );\n};\n\nexport default MessageScroll;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMediaWithNoText = (photo || video) && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video && video.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo) {\n classNames.push('media');\n }\n }\n\n if (asForwarded && !customShape) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_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 : MIN_MEDIA_WIDTH;\n}\n\nexport function calculateMediaDimensions(message: ApiMessage) {\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)\n : calculateVideoDimensions(video!, isOwn, isForwarded);\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 } from '../../../../api/types';\nimport { IDimensions } from '../../../../modules/helpers';\n\nimport { MOBILE_SCREEN_MAX_WIDTH } from '../../../../config';\nimport { REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nconst MAX_WIDTH_MOBILE_VW = 69;\nconst MAX_WIDTH_DESK_OWN_REM = 30;\nconst MAX_WIDTH_DESK_REM = 29;\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: IDimensions;\n};\n\nfunction getMaxWidth(isOwn: boolean, isForwarded: boolean, windowWidth: number) {\n if (windowWidth <= MOBILE_SCREEN_MAX_WIDTH) {\n return (windowWidth / 100) * MAX_WIDTH_MOBILE_VW - (isForwarded ? 1.625 : 0) * REM;\n }\n\n const maxWidth = isOwn ? MAX_WIDTH_DESK_OWN_REM : MAX_WIDTH_DESK_REM;\n\n return (maxWidth - (isForwarded ? 1.625 : 0)) * REM;\n}\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as IDimensions;\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: IDimensions = { 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 album: IAlbum,\n windowWidth: number,\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 = getMaxWidth(isOwn, isForwarded, windowWidth);\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\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","let element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n element.style.font = '400 12px Roboto, \"Helvetica Neue\", \"Apple Color Emoji\", 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 { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\nimport { FocusDirection } from '../../../../types';\n\n// This is the max scroll offset within existing viewport.\nconst FOCUS_MAX_OFFSET = 1500;\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: number,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: 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' : 'center',\n FOCUS_MARGIN,\n focusDirection === undefined ? FOCUS_MAX_OFFSET : RELOCATED_FOCUS_OFFSET,\n focusDirection,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight]);\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, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n isLastInList?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n targetUser?: ApiUser;\n targetMessage?: ApiMessage;\n targetChatId?: number;\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 sender,\n targetUser,\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 content = renderActionMessageText(\n lang,\n message,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n if (isEmbedded) {\n return {renderText(content as string)};\n }\n\n const className = buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n isLastInList && 'last-in-list',\n transitionClassNames,\n );\n\n return (\n \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message }): StateProps => {\n const userId = message.senderId;\n const { targetUserId, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n sender,\n ...(targetUserId && { targetUser: selectUser(global, targetUserId) }),\n targetChatId,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n getMessageRoundVideo,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC = ({\n className,\n message,\n sender,\n title,\n customText,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n const isRoundVideo = Boolean(message && getMessageRoundVideo(message));\n\n const lang = useLang();\n\n const senderTitle = sender && getSenderTitle(lang, sender);\n\n return (\n \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl, isRoundVideo)}\n
\n

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

\n
{renderText(senderTitle || title || NBSP)}
\n
\n
\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n isRoundVideo?: boolean,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: () => void;\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n \n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(isMediaReady, 'slow');\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n
\n {!isMediaReady && (\n \n )}\n {!isAnimated && shouldRenderFullMedia && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { IS_CANVAS_FILTER_SUPPORTED, IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useCanvasBlur from '../../../../hooks/useCanvasBlur';\n\nexport default function useBlurredMediaThumbRef(message: ApiMessage, fullMediaData?: string) {\n return useCanvasBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_MOBILE_SCREEN && !IS_CANVAS_FILTER_SUPPORTED,\n );\n}\n","const SELECTED_APPENDIX_BACKGROUND = 'rgba(255,255,255,1)';\n\nexport default async (src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean) => {\n return isSelected ? SELECTED_APPENDIX_BACKGROUND : 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 { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport usePrevious from '../../../hooks/usePrevious';\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 shouldAutoLoad?: 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 onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n nonInteractive,\n shouldAffectAppendix,\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 [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = isDownloadAllowed && isIntersecting;\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, size), !shouldDownload);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbRef = useBlurredMediaThumbRef(message, fullMediaData);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, shouldDownload && !fullMediaData);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled, 'slow');\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(fullMediaData, 'slow');\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsDownloadAllowed((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).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]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message);\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 {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!fullMediaData && !isDownloadAllowed && (\n \n )}\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n \n );\n};\n\nexport default Photo;\n","import { RefObject } from 'react';\nimport { useCallback, useRef } from '../lib/teact/teact';\n\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport safePlay from '../util/safePlay';\n\nexport default function useHeavyAnimationCheckForVideo(playerRef: RefObject, shouldPlay: boolean) {\n const shouldPlayRef = useRef();\n shouldPlayRef.current = shouldPlay;\n\n const pause = useCallback(() => {\n if (playerRef.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const play = useCallback(() => {\n if (playerRef.current && shouldPlayRef.current) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n useHeavyAnimationCheck(pause, play);\n}\n","import { useCallback, useRef } from '../../../../lib/teact/teact';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport safePlay from '../../../../util/safePlay';\n\nexport default (playerRef: { current: HTMLVideoElement | null }, isPlayAllowed = false) => {\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const freezePlaying = useCallback(() => {\n isFrozen.current = true;\n\n if (!isPlayAllowed || !playerRef.current) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = !playerRef.current.paused;\n }\n\n playerRef.current.pause();\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n // At this point HTMLVideoElement can be unmounted from the DOM\n if (isPlayAllowed && playerRef.current && wasPlaying.current && document.body.contains(playerRef.current)) {\n safePlay(playerRef.current);\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n if (!document.hasFocus()) {\n freezePlaying();\n }\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\n};\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { 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 canMessagePlayVideoInline,\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\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 shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\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 = message.content.video!;\n const localBlobUrl = video.blobUrl;\n const canPlayInline = Boolean(localBlobUrl) || canMessagePlayVideoInline(video);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(shouldAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(canPlayInline && isIntersecting && fullMediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering(!shouldAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || downloadProgress,\n shouldDownload && (canPlayInline && !isBuffered),\n );\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(fullMediaData, 'slow');\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 isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded);\n\n useHeavyAnimationCheckForVideo(videoRef, Boolean(isInline && shouldAutoPlay));\n\n usePauseOnInactive(videoRef, isPlayAllowed);\n\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (canPlayInline && !fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (canPlayInline && fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, canPlayInline, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n const shouldRenderInlineVideo = isInline;\n const shouldRenderHqPreview = !canPlayInline && mediaData;\n const shouldRenderPlayButton = !canPlayInline || (isDownloadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n const shouldRenderDownloadButton = canPlayInline && !isDownloadAllowed;\n\n return (\n \n {(!isInline || shouldRenderThumb)\n && (\n \n )}\n {previewBlobUrl && (\n \n )}\n\n {shouldRenderInlineVideo && (\n \n \n \n )}\n {shouldRenderHqPreview && (\n \n )}\n {shouldRenderPlayButton && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && (\n \n )}\n {isTransferring && !canPlayInline ? (\n {Math.round(transferProgress * 100)}%\n ) : isTransferring && canPlayInline ? (\n ...\n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(video.duration - playProgress)}\n
\n )}\n \n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser, ApiContact } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n};\n\ntype DispatchProps = Pick;\n\nconst Contact: FC = ({\n contact, user, openUserInfo,\n}) => {\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\n (global, { contact }): StateProps => {\n return {\n user: selectUser(global, contact.userId),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(Contact);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, memo, useState,\n} from '../../lib/teact/teact';\n\nimport Checkbox from './Checkbox';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n};\n\ntype OwnProps = {\n id?: string;\n options: IRadioOption[];\n selected?: string[];\n disabled?: boolean;\n round?: boolean;\n loadingOptions?: string[];\n onChange: (value: string[]) => void;\n};\n\nconst CheckboxGroup: FC = ({\n id,\n options,\n selected = [],\n disabled,\n round,\n loadingOptions,\n onChange,\n}) => {\n const [values, setValues] = useState([]);\n\n const handleChange = useCallback((event: ChangeEvent) => {\n const { value, checked } = event.currentTarget;\n let newValues: string[];\n if (checked) {\n newValues = [...values, value];\n } else {\n newValues = values.filter((v) => v !== value);\n }\n\n setValues(newValues);\n onChange(newValues);\n }, [onChange, values]);\n\n return (\n
\n {options.map((option) => (\n \n ))}\n
\n );\n};\n\nexport default memo(CheckboxGroup);\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 && 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 { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record;\n};\n\ntype DispatchProps = Pick;\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 loadMessage,\n onSendVote,\n openPollResults,\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), 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)}
\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 { byId: usersById } = global.users;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMessage', 'openPollResults']),\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n inPreview?: boolean;\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n inPreview,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage && webPage.photo) {\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 } = webPage;\n\n const isMediaInteractive = photo && onMediaClick && !isSquarePhoto && !webPage.hasDocument;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n photo\n ? (isSquarePhoto && 'with-square-photo')\n : (!inPreview && 'without-photo'),\n );\n\n return (\n \n {photo && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

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

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

\n )}\n
\n
\n );\n};\n\nexport default memo(WebPage);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageInvoice } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\n\nimport './Invoice.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n};\n\nconst Invoice: FC = ({\n message,\n}) => {\n const invoice = getMessageInvoice(message);\n\n const {\n title,\n text,\n description,\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 {description && (\n

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

\n )}\n
\n
\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport { GlobalActions } from '../../../../global/types';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\nimport { pick } from '../../../../util/iteratees';\n\ntype OwnProps = PhotoProps & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nexport default function withSelectControl(WrapedComponent: FC) {\n const Component: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e && e.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'toggleMessageSelection',\n ]),\n )(Component));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { withGlobal } from '../../../lib/teact/teactn';\nimport { pick } from '../../../util/iteratees';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\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 shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n};\n\ntype DispatchProps = Pick;\n\nconst Album: FC = ({\n album,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n albumLayout,\n onMediaClick,\n uploadsById,\n cancelSendingMessage,\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 ? fileUpload.progress : undefined;\n const { dimensions, sides } = albumLayout.layout[index];\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): StateProps => {\n return {\n uploadsById: global.fileUploads.byMessageLocalId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'cancelSendingMessage',\n ]),\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport buildClassName from '../../../util/buildClassName';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport safePlay from '../../../util/safePlay';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n lastSyncTime?: number;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n lastSyncTime,\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 [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad && shouldAutoPlay);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = isDownloadAllowed && !isBuffered;\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\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 circumference = 94 * 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 } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n requestAnimationFrame(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useHeavyAnimationCheckForVideo(playerRef, shouldPlay);\n\n usePauseOnInactive(playerRef, Boolean(mediaData));\n\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n } else {\n playerEl.pause();\n }\n } else {\n capturePlaying();\n playerEl.currentTime = 0;\n setIsActivated(true);\n }\n }, [capturePlaying, isActivated, mediaData]);\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 {shouldRenderThumb && (\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 && !isDownloadAllowed && (\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 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 return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {button.text}\n {button.type === 'url' && }\n \n ))}\n
\n ))}\n
\n );\n};\n\nexport default InlineButtons;\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiMessage, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../../modules/helpers';\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n disabled?: boolean;\n};\n\ntype StateProps = {\n threadInfo: ApiThreadInfo;\n usersById?: Record;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst CommentButton: FC = ({\n disabled, threadInfo, usersById, chatsById, openChat,\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 if (messagesCount === undefined) {\n return undefined;\n }\n\n const recentRepliers = recentReplierIds && recentReplierIds.map((peerId) => {\n return isChatPrivate(peerId) ? usersById![peerId] : chatsById![peerId];\n }).filter(Boolean);\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(withGlobal(\n (global, { message }) => {\n const { threadId, chatId } = message.threadInfo!;\n\n const threadInfo = selectThreadInfo(global, chatId, threadId) || message.threadInfo!;\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n return {\n threadInfo,\n usersById,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n ]),\n)(CommentButton));\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { FocusDirection, IAlbum, MediaViewerOrigin } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\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 selectShouldAutoLoadMedia,\n selectShouldAutoPlayMedia, selectShouldLoopStickers,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isChatPrivate,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji, getSenderTitle, getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS } 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 useFocusMessage from './hooks/useFocusMessage';\nimport useWindowSize from '../../../hooks/useWindowSize';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n} & MessagePositionProperties;\n\ntype StateProps = {\n forceSenderName?: boolean;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isChannel?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n shouldAutoLoadMedia?: boolean;\n shouldAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '';\nconst APPEARANCE_DELAY = 10;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\n\nconst Message: FC = ({\n message,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n shouldAutoLoadMedia,\n shouldAutoPlayMedia,\n shouldLoopStickers,\n focusMessage,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n openChat,\n cancelSendingMessage,\n markMessagesRead,\n sendPollVote,\n toggleMessageSelection,\n setReplyingToId,\n openForwardMenu,\n clickInlineButton,\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 appendixRef = useRef(null);\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const { width: windowWidth } = useWindowSize();\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref, false, true);\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 { chatId, id: messageId, threadInfo } = message;\n\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 { forwardInfo, viaBotId } = message;\n const asForwarded = forwardInfo && !isChatWithSelf && !forwardInfo.isLinkedChannelPost;\n const isInDocumentGroup = !!message.groupedId && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const customShape = getMessageCustomShape(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\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 transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: message.threadInfo && message.threadInfo.messagesCount > 0,\n });\n const avatarPeer = forwardInfo && (isChatWithSelf || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n const signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n const withCommentButton = message.threadInfo && (!isInDocumentGroup || isLastInDocumentGroup)\n && messageListType === 'thread' && !noComments;\n const withAppendix = contentClassName.includes('has-appendix');\n\n useEnsureMessage(chatId, hasReply ? message.replyToMessageId : undefined, replyMessage, message.id);\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight);\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = isOwn ? APPENDIX_OWN : APPENDIX_NOT_OWN;\n }, [isOwn, withAppendix]);\n\n const handleGroupDocumentMessagesSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n\n toggleMessageSelection({\n messageId,\n groupedId: message.groupedId,\n });\n }, [messageId, message.groupedId, toggleMessageSelection]);\n\n const handleMessageSelect = useCallback((e?: ReactMouseEvent) => {\n const params = isAlbum && album && album.messages\n ? {\n messageId,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: e && e.shiftKey,\n }\n : { messageId, withShift: e && e.shiftKey };\n toggleMessageSelection(params);\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const handleContainerDoubleClick = useCallback(() => {\n setReplyingToId({ messageId });\n }, [setReplyingToId, messageId]);\n\n const handleContentDoubleClick = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n }, []);\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isChatPrivate(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n return;\n }\n\n if (isChatPrivate(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [senderPeer, openUserInfo, openChat]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({ chatId, threadId, messageId: message.replyToMessageId });\n }, [focusMessage, chatId, threadId, message.replyToMessageId]);\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: message.groupedId });\n }, [openForwardMenu, chatId, message.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: message.groupedId, groupedChatId: chatId,\n });\n return;\n }\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }, [focusMessage, forwardInfo, message, chatId, isInDocumentGroup]);\n\n const lang = useLang();\n\n let style = '';\n let calculatedWidth;\n let noMediaCorners = false;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), album!, windowWidth) : undefined;\n }, [isAlbum, windowWidth, isOwn, asForwarded, 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).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS;\n } else {\n width = calculateMediaDimensions(message).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), width);\n if (calculatedWidth - width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), albumLayout.containerStyle.width);\n if (calculatedWidth - albumLayout.containerStyle.width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isChatPrivate(avatarPeer.id);\n const avatarUser = avatarPeer && isAvatarPeerUser ? avatarPeer as ApiUser : undefined;\n const avatarChat = avatarPeer && !isAvatarPeerUser ? avatarPeer as ApiChat : undefined;\n const hiddenName = !avatarPeer && forwardInfo ? forwardInfo.hiddenUserName : undefined;\n\n return (\n \n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && !customShape && 'forwarded-message',\n hasReply && 'reply-message',\n noMediaCorners && 'no-media-corners',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n const shouldInlineMeta = !webPage && !animatedEmoji && textParts;\n\n return (\n
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts && (\n

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

\n )}\n {webPage && (\n \n )}\n {invoice && (\n \n )}\n
\n );\n }\n\n function renderSenderName() {\n const shouldRender = !customShape && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer) {\n senderTitle = getSenderTitle(lang, senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo && 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 && forwardInfo.isLinkedChannelPost ? (\n {lang('DiscussChannel')}\n ) : message.adminTitle && !isChannel ? (\n {message.adminTitle}\n ) : undefined}\n
\n );\n }\n\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = canShowActionButton && isChannel && !isScheduled;\n const canFocus = canShowActionButton && (\n (forwardInfo && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn)) && forwardInfo.fromMessageId)\n || isPinnedList\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 {withAppendix && (
)}\n {asForwarded && !customShape && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && !(!webPage && !animatedEmoji && textParts) && (\n \n )}\n {canForward ? (\n \n \n \n ) : canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {contentClassName.includes('has-appendix') &&
}\n
\n {message.inlineButtons && (\n \n )}\n
\n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToMessageId, isOutgoing,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isChannel = chat && isChatChannel(chat);\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = canShowSender ? selectSender(global, message) : undefined;\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, 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 { direction: focusDirection, noHighlight: noFocusHighlight } = (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 && album.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n return {\n forceSenderName,\n sender,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isPinnedList: messageListType === 'pinned',\n shouldAutoLoadMedia: chat ? selectShouldAutoLoadMedia(global, message, chat, sender) : undefined,\n shouldAutoPlayMedia: selectShouldAutoPlayMedia(global, message),\n shouldLoopStickers: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'cancelSendingMessage',\n 'openUserInfo',\n 'openChat',\n 'markMessagesRead',\n 'sendPollVote',\n 'toggleMessageSelection',\n 'setReplyingToId',\n 'openForwardMenu',\n 'clickInlineButton',\n ]),\n)(Message));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, MESSAGE_LIST_SLICE, SCHEDULED_WHEN_ONLINE } from '../../config';\nimport { IS_ANDROID, IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n selectChatMessages,\n selectIsViewportNewest,\n selectFirstUnreadId,\n selectFocusedMessageId,\n selectChat,\n selectIsInSelectMode,\n selectIsChatWithSelf,\n selectChatBot,\n selectIsChatBotNotStarted,\n selectScrollOffset,\n selectThreadTopMessageId,\n selectFirstMessageId,\n selectScheduledMessages,\n selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n getMessageOriginalId,\n isActionMessage,\n isChatChannel,\n isChatPrivate,\n isOwnMessage,\n} from '../../modules/helpers';\nimport {\n compact,\n flatten,\n orderBy,\n pick,\n} from '../../util/iteratees';\nimport {\n fastRaf, debounce, onTickEnd,\n} from '../../util/schedulers';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages, MessageDateGroup, isAlbum } from './helpers/groupMessages';\nimport { ObserveFn, useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll from '../../util/resetScroll';\nimport fastSmoothScroll, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang, { LangFn } from '../../hooks/useLang';\nimport useWindowSize from '../../hooks/useWindowSize';\n\nimport Loading from '../ui/Loading';\nimport MessageScroll from './MessageScroll';\nimport Message from './message/Message';\nimport ActionMessage from './ActionMessage';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n type: MessageListType;\n canPost: boolean;\n onFabToggle: (shouldShow: boolean) => void;\n onNotchToggle: (shouldShow: boolean) => void;\n hasTools?: boolean;\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n isChatWithSelf?: 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};\n\ntype DispatchProps = Pick;\n\nconst BOTTOM_THRESHOLD = 100;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_MOBILE_SCREEN ? 300 : 500;\nconst FOCUSING_DURATION = 1000;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst FOCUSING_FADE_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 canPost,\n isChatWithSelf,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n animationLevel,\n loadViewportMessages,\n markMessageListRead,\n markMessagesRead,\n setScrollOffset,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\n openHistoryCalendar,\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 memoUnreadDividerBeforeIdRef = useRef();\n // Updated every time (to be used from intersection callback closure)\n const memoFirstUnreadIdRef = useRef();\n const memoFocusingIdRef = useRef();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(!messageIds);\n\n const [containerHeight, setContainerHeight] = useState();\n const [hasFocusing, setHasFocusing] = useState(Boolean(focusingId));\n\n const areMessagesLoaded = Boolean(messageIds);\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 useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n\n // Updated only once (to preserve divider even after messages are read)\n if (!memoUnreadDividerBeforeIdRef.current) {\n memoUnreadDividerBeforeIdRef.current = firstUnreadId;\n }\n }, [firstUnreadId]);\n\n const {\n observe: observeIntersectionForMedia, freeze: freezeForMedia, unfreeze: unfreezeForMedia,\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 }, (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 useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n\n if (focusingId) {\n freezeForMedia();\n freezeForReading();\n } else {\n unfreezeForReading();\n unfreezeForMedia();\n }\n }, [focusingId]);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n useEffect(() => {\n if (focusingId) {\n setHasFocusing(true);\n } else {\n setTimeout(() => {\n setHasFocusing(false);\n }, FOCUSING_FADE_ANIMATION_DURATION);\n }\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const [loadMoreBackwards, loadMoreForwards, loadMoreAround] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\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 useEffect(() => {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }, [windowHeight]);\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Remember scroll position before repositioning it\n useOnChange(() => {\n if (!messageIds || !listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n // This should match deps for `useLayoutEffectWithPrevDeps` below\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll('.message-list-item'));\n\n // During animation\n if (!container.offsetParent) {\n return;\n }\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 && (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 }, FOCUSING_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 // If two messages come at once (e.g. via Quiz Bot) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes.\n // To workaround that, we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n const isAtBottom = isViewportNewest && prevIsViewportNewest && (\n scrollOffset - (prevContainerHeight || offsetHeight) - lastItemHeight <= BOTTOM_THRESHOLD\n );\n\n let newScrollTop!: number;\n\n const hasFirstMessageChanged = messageIds && prevMessageIds && messageIds[0] !== prevMessageIds[0];\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n const isAlreadyFocusing = messageIds && memoFocusingIdRef.current === messageIds[messageIds.length - 1];\n\n if (isAtBottom && hasLastMessageChanged && !hasFirstMessageChanged && !isAlreadyFocusing) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n undefined,\n undefined,\n undefined,\n true,\n );\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(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 const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP);\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, newScrollTop);\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(scrollHeight - newScrollTop, offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n // This should match deps for `useOnChange` above\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffect(() => {\n if (!animationLevel || animationLevel > 0) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isChatPrivate(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf);\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n !withUsers && 'no-avatars',\n isChannelChat && 'no-avatars',\n !canPost && 'no-composer',\n type === 'pinned' && 'type-pinned',\n isSelectModeActive && 'select-mode-active',\n hasFocusing && 'has-focusing',\n isScrolled && 'scrolled',\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 ) : messageIds && !messageGroups ? (\n
{lang('NoMessages')}
\n ) : ((messageIds && messageGroups) || lastMessage) ? (\n \n {renderMessages(\n lang,\n messageGroups || groupMessages([lastMessage!]),\n observeIntersectionForReading,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n withUsers,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n threadId,\n type,\n threadTopMessageId,\n threadFirstMessageId,\n Boolean(hasLinkedChat),\n messageGroups ? type === 'scheduled' : false,\n !messageGroups || !shouldAnimateAppearanceRef.current,\n openHistoryCalendar,\n )}\n \n ) : (\n \n )}\n
\n );\n};\n\nfunction renderMessages(\n lang: LangFn,\n messageGroups: MessageDateGroup[],\n observeIntersectionForReading: ObserveFn,\n observeIntersectionForMedia: ObserveFn,\n observeIntersectionForAnimatedStickers: ObserveFn,\n withUsers: boolean,\n currentAnchorIdRef: { current: string | undefined },\n memoFirstUnreadIdRef: { current: number | undefined },\n threadId: number,\n type: MessageListType,\n threadTopMessageId: number | undefined,\n threadFirstMessageId: number | undefined,\n hasLinkedChat: boolean,\n isSchedule: boolean,\n noAppearanceAnimation: boolean,\n openHistoryCalendar: Function,\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 === memoFirstUnreadIdRef.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 && currentAnchorIdRef.current === `message${message.previousLocalId}`) {\n currentAnchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n message.id === memoFirstUnreadIdRef.current ? unreadDivider : undefined,\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 flatten(dateGroups);\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 let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n const chatBot = selectChatBot(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 isChatWithSelf: selectIsChatWithSelf(global, chatId),\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 animationLevel: global.settings.byKey.animationLevel,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadViewportMessages',\n 'markMessageListRead',\n 'markMessagesRead',\n 'setScrollOffset',\n 'openHistoryCalendar',\n ]),\n)(MessageList));\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport { pick } from '../../util/iteratees';\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};\n\ntype StateProps = {\n messageListType?: MessageListType;\n unreadCount?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC = ({\n isShown,\n canPost,\n messageListType,\n unreadCount,\n focusLastMessage,\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 focusLastMessage();\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, focusLastMessage]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\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 (setGlobal, actions): DispatchProps => pick(actions, ['focusLastMessage']),\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { preloadImage, preloadVideo, createPosterForVideo } from '../../../../util/files';\n\nconst MAX_QUICK_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\nconst MAX_QUICK_IMG_SIZE = 1280; // px\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 (mimeType.startsWith('image/')) {\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 newBlob = await squeezeImage(img);\n if (newBlob) {\n URL.revokeObjectURL(blobUrl);\n return buildAttachment(filename, newBlob, true, options);\n } else {\n return buildAttachment(filename, blob, false, options);\n }\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (mimeType.startsWith('video/')) {\n // Videos < 10 MB are always sent in quick mode (in other clients).\n // Quick mode for videos > 10 MB is not supported until client-side video squeezing is implemented.\n if (size < MAX_QUICK_VIDEO_SIZE) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n }\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\nfunction squeezeImage(img: HTMLImageElement): Promise {\n return new Promise((resolve) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n let { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE) {\n if (width >= height) {\n height *= MAX_QUICK_IMG_SIZE / width;\n width = MAX_QUICK_IMG_SIZE;\n } else {\n width *= MAX_QUICK_IMG_SIZE / height;\n height = MAX_QUICK_IMG_SIZE;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);\n canvas.toBlob(resolve, 'image/jpeg', 100);\n });\n}\n","export default __webpack_public_path__ + \"8ccc0b555efcec3616377aea078dda16.js\";","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface OpusRecorder extends Omit {\n new(options: AnyLiteral): OpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: OpusRecorder }>;\nlet OpusRecorder: OpusRecorder;\nlet mediaRecorder: OpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: OpusRecorder, 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';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string, inputId?: string) => void,\n setAttachments: StateHookSetter,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && input.tagName === 'INPUT' && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items).find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type));\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n if (!file && !pastedText) {\n return;\n }\n\n e.preventDefault();\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText, input ? input.id : undefined);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\n}\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/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 '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: number | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: number,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n saveDraft: GlobalActions['saveDraft'],\n clearDraft: GlobalActions['clearDraft'],\n) => {\n const updateDraft = useCallback((draftChatId: number, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n // Subscribe and handle `window.blur`\n useEffect(() => {\n function handleBlur() {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }\n\n window.addEventListener('blur', handleBlur);\n\n return () => {\n window.removeEventListener('blur', handleBlur);\n };\n }, [chatId, threadId, updateDraft]);\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? : undefined;\n};\n\nexport default memo(DeleteMessageModalAsync);\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n \n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? : undefined;\n};\n\nexport default memo(AttachMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? : undefined;\n};\n\nexport default memo(SymbolMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const MentionTooltip = useModuleLoader(Bundles.Extra, 'MentionTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionTooltip ? : undefined;\n};\n\nexport default memo(MentionTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? : undefined;\n};\n\nexport default memo(CustomSendMenuAsync);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './StickerTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst StickerTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const StickerTooltip = useModuleLoader(Bundles.Extra, 'StickerTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerTooltip ? : undefined;\n};\n\nexport default StickerTooltipAsync;\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotKeyboardMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotKeyboardMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const BotKeyboardMenu = useModuleLoader(Bundles.Extra, 'BotKeyboardMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotKeyboardMenu ? : undefined;\n};\n\nexport default memo(BotKeyboardMenuAsync);\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isChatPrivate } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n}) => {\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isChatPrivate(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 (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'focusMessage',\n 'exitForwardMode',\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 './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? : undefined;\n};\n\nexport default memo(PollModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? : undefined;\n};\n\nexport default memo(DropAreaAsync);\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../../util/buildClassName';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageText: string;\n disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n};\ntype DispatchProps = Pick;\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC = ({\n chatId,\n threadId,\n messageText,\n disabled,\n webPagePreview,\n noWebPage,\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n}) => {\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = useCurrentOrPrev(webPagePreview);\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 webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWebPagePreview', 'clearWebPagePreview', 'toggleMessageWebPage',\n ]),\n)(WebPagePreview));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? : undefined;\n};\n\nexport default memo(CalendarModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './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, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { LangCode } from '../../../types';\n\nimport { EDITABLE_INPUT_ID, SCHEDULED_WHEN_ONLINE } from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_MOBILE_SCREEN, IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport {\n selectChat,\n selectIsChatWithBot,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatUser,\n selectEmojiKeywords,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatGroup,\n isChatPrivate,\n isChatAdmin,\n} from '../../../modules/helpers';\nimport { formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { isSelectionInsideInput } from './helpers/selection';\n\nimport useFlag from '../../../hooks/useFlag';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useStickerTooltip from './hooks/useStickerTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport MentionTooltip from './MentionTooltip.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport StickerTooltip from './StickerTooltip.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu.async';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\nimport PaymentModal from '../../payment/PaymentModal.async';\nimport ReceiptModal from '../../payment/ReceiptModal.async';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps = {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n canSuggestMembers?: boolean;\n isPollModalOpen?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n botKeyboardMessageId?: number;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: number;\n usersById?: Record;\n recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n language: LangCode;\n emojiKeywords?: Record;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst 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 onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n canSuggestMembers,\n isPollModalOpen,\n isPaymentModalOpen,\n isReceiptModalOpen,\n botKeyboardMessageId,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n language,\n emojiKeywords,\n recentEmojis,\n sendMessage,\n editMessage,\n saveDraft,\n clearDraft,\n showError,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n closePaymentModal,\n openChat,\n clearReceipt,\n addRecentEmoji,\n loadEmojiKeywords,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n const [html, setHtml] = useState('');\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState();\n\n // Cache for frequently updated state\n const htmlRef = useRef(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID) {\n loadScheduledHistory();\n }\n }, [chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = 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 const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, mentionFilter,\n closeMentionTooltip, insertMention,\n mentionFilteredMembers,\n } = useMentionTooltip(\n canSuggestMembers && !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n recentEmojis,\n undefined,\n setHtml,\n emojiKeywords,\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)) {\n if (IS_EMOJI_SUPPORTED) {\n // Insertion will trigger `onChange` in MessageInput, so no need to setHtml in state\n document.execCommand('insertText', false, text);\n } else {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n }\n return;\n }\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n if (!IS_MOBILE_SCREEN) {\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback(() => {\n setHtml('');\n setAttachments([]);\n closeStickerTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionTooltip();\n closeEmojiTooltip();\n\n if (IS_MOBILE_SCREEN) {\n // @perf\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeStickerTooltip, closeCalendar, closeMentionTooltip, closeEmojiTooltip, closeSymbolMenu]);\n\n // Handle chat change\n const prevChatId = usePrevious(chatId);\n useEffect(() => {\n if (!prevChatId || chatId === prevChatId) {\n return;\n }\n\n stopRecordingVoice();\n resetComposer();\n }, [chatId, prevChatId, resetComposer, stopRecordingVoice]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal, editMessage);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage, saveDraft, clearDraft);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleAppendFiles = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments([\n ...attachments,\n ...await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))),\n ]);\n }, [attachments]);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n if (currentAttachments.length && text && text.length > CAPTION_MAX_LENGTH) {\n const extraLength = text.length - CAPTION_MAX_LENGTH;\n showError({\n error: {\n message: 'CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n },\n });\n return;\n }\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = Math.floor(Date.now() / 1000);\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 showError({\n error: {\n message: `A wait of ${secondsRemaining} seconds is required before sending another message in this chat`,\n isSlowMode: true,\n },\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\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 if (isForwarding) {\n forwardMessages();\n }\n\n lastMessageSendTimeSeconds.current = Math.floor(Date.now() / 1000);\n\n clearDraft({ chatId, localOnly: true });\n\n // Wait until message animation starts\n requestAnimationFrame(resetComposer);\n }, [\n activeVoiceRecording, attachments, connectionState, chatId, slowMode, isForwarding, isAdmin,\n sendMessage, stopRecordingVoice, resetComposer, clearDraft, showError, forwardMessages,\n ]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(resetComposer);\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000));\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_MOBILE_SCREEN || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_MOBILE_SCREEN) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n handleSend();\n requestAnimationFrame(resetComposer);\n }\n break;\n case MainButtonState.Record:\n startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, resetComposer, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const lang = useLang();\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'SendMessage';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Conversation.DefaultRestrictedMedia'\n : 'AccDescrVoiceMessage';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n return (\n
\n {allowedAttachmentOptions.canAttachMedia && (\n \n \n \n )}\n \n \n \n \n {renderedEditedMessage && (\n \n )}\n \n
\n
\n \n \n
\n {IS_MOBILE_SCREEN ? (\n \n \n \n \n \n ) : (\n \n \n \n )}\n \n {withScheduledButton && (\n \n \n \n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {activeVoiceRecording && currentRecordTime && (\n \n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n \n )}\n \n \n \n {botKeyboardMessageId && (\n \n )}\n \n
\n
\n {activeVoiceRecording && (\n \n \n \n )}\n \n \n \n \n \n {canShowCustomSendMenu && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n const { language } = global.settings.byKey;\n const emojiKeywords = selectEmojiKeywords(global, language);\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: (\n !isChatWithSelf && !isChatWithBot\n && (chat && chatUser && isChatPrivate(chatId) && chatUser.status && Boolean(chatUser.status.wasOnline))\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds && scheduledIds.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId: messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined,\n isForwarding: chatId === global.forwardMessages.toChatId,\n canSuggestMembers: chat && isChatGroup(chat),\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat && chat.fullInfo && chat.fullInfo.members,\n currentUserId: global.currentUserId,\n usersById: global.users.byId,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n shouldSuggestStickers: global.settings.byKey.shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n language,\n emojiKeywords: emojiKeywords ? emojiKeywords.keywords : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'sendMessage',\n 'editMessage',\n 'saveDraft',\n 'clearDraft',\n 'showError',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'forwardMessages',\n 'openPollModal',\n 'closePollModal',\n 'closePaymentModal',\n 'clearReceipt',\n 'loadScheduledHistory',\n 'openChat',\n 'addRecentEmoji',\n 'loadEmojiKeywords',\n ]),\n)(Composer));\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_IOS } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState();\n const startRecordTimeRef = useRef();\n const [currentRecordTime, setCurrentRecordTime] = useState();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_IOS) {\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\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\n\nexport default function useStickerTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n) {\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(html) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({ emoji: html });\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]);\n\n return {\n isStickerTooltipOpen: hasStickers,\n closeStickerTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection && 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 selection.removeAllRanges();\n selection.addRange(range);\n }\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';\n\nimport { ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n editMessage: GlobalActions['editMessage'],\n) => {\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? : undefined;\n};\n\nexport default memo(MobileSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? : undefined;\n};\n\nexport default memo(MessageSelectToolbarAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? : undefined;\n};\n\nexport default memo(UnpinAllMessagesModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } 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 CONTENT_TYPES_FOR_QUICK_UPLOAD,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n DARK_THEME_BG_COLOR,\n LIGHT_THEME_BG_COLOR,\n} from '../../config';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV, MASK_IMAGE_DISABLED } from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n} from '../../modules/selectors';\nimport { getCanPostInChat, getMessageSendingRestrictionReason, isChatPrivate } from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevDuringAnimation from '../../hooks/usePrevDuringAnimation';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\nimport useLang from '../../hooks/useLang';\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';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n canPost?: boolean;\n messageSendingRestrictionReason?: string;\n hasPinnedOrAudioMessage?: boolean;\n pinnedMessagesCount?: number;\n theme: ThemeKey;\n customBackground?: string;\n backgroundColor?: string;\n patternColor?: string;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst CLOSE_ANIMATION_DURATION = IS_MOBILE_SCREEN ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction canBeQuicklyUploaded(item: DataTransferItem) {\n return item.kind === 'file' && item.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(item.type);\n}\n\nconst MiddleColumn: FC = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n canPost,\n messageSendingRestrictionReason,\n hasPinnedOrAudioMessage,\n pinnedMessagesCount,\n customBackground,\n theme,\n backgroundColor,\n patternColor,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n animationLevel,\n openChat,\n unpinAllMessages,\n loadUser,\n}) => {\n const { width: windowWidth } = useWindowSize();\n\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 = hasPinnedOrAudioMessage && (\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 renderingCanPost = usePrevDuringAnimation(canPost, CLOSE_ANIMATION_DURATION);\n const renderingHasTools = usePrevDuringAnimation(hasTools, CLOSE_ANIMATION_DURATION);\n const renderingIsFabShown = usePrevDuringAnimation(isFabShown, CLOSE_ANIMATION_DURATION);\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useEffect(() => {\n setDropAreaState(DropAreaState.None);\n setIsFabShown(undefined);\n setIsNotchShown(undefined);\n }, [chatId]);\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items).every(canBeQuicklyUploaded);\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 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 // 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 lang = useLang();\n\n const footerClassName = buildClassName(\n 'middle-column-footer',\n !renderingCanPost && 'no-composer',\n renderingCanPost && isNotchShown && !isSelectModeActive && 'with-notch',\n );\n\n return (\n \n \n
\n {renderingChatId && renderingThreadId && (\n <>\n
\n \n \n {() => (\n <>\n \n
\n {renderingCanPost && (\n \n )}\n {isPinnedMessageList && (\n
\n \n \n {lang('Chat.Pinned.UnpinAll', pinnedMessagesCount, 'i')}\n \n
\n )}\n {!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason && (\n
\n
\n \n {messageSendingRestrictionReason}\n \n
\n
\n )}\n \n
\n \n )}\n \n\n \n
\n {IS_MOBILE_SCREEN && }\n \n )}\n {chatId && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const currentMessageList = selectCurrentMessageList(global);\n const { chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_MOBILE_SCREEN && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n animationLevel: global.settings.byKey.animationLevel,\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const 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\n return {\n ...state,\n chatId,\n threadId,\n messageListType,\n isPrivate: isChatPrivate(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && (!isBotNotStarted || IS_MOBILE_SCREEN),\n isPinnedMessageList,\n messageSendingRestrictionReason: chat && getMessageSendingRestrictionReason(chat),\n hasPinnedOrAudioMessage: (\n threadId !== MAIN_THREAD_ID\n || Boolean(pinnedIds && pinnedIds.length)\n || Boolean(audioChatId && audioMessageId)\n ),\n pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat', 'unpinAllMessages', 'loadUser',\n ]),\n)(MiddleColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { ThemeKey } from '../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { preloadImage } from '../util/files';\n\nexport default (theme: ThemeKey, settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, theme, cacheApi.Type.Blob)\n .then((blob) => {\n const url = URL.createObjectURL(blob);\n preloadImage(url)\n .then(() => {\n setValue(`url(${url})`);\n });\n });\n }\n }, [settingValue, theme]);\n\n return settingValue ? value : undefined;\n};\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n} from '../../modules/selectors';\nimport { isChatAdmin, isChatChannel, isChatPrivate } from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useLang from '../../hooks/useLang';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\nimport { getDayStartAt } from '../../util/dateFormat';\n\ntype OwnProps = {\n chatId?: number;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canManage?: boolean;\n isChannel?: boolean;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupMembers,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nconst RightHeader: FC = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n profileState,\n managementScreen,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n openHistoryCalendar,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n\n const handleMessageSearchQueryChange = useCallback((query: string) => {\n setLocalTextSearchQuery({ query });\n\n if (query.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const [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 ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : undefined // Never reached\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n \n \n \n );\n case HeaderContent.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.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

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

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

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

{lang('GroupMembers')}

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

Profile

\n
\n {canManage && (\n \n \n \n )}\n
\n \n );\n }\n }\n\n const isBackButton = (\n IS_MOBILE_SCREEN\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n shouldSkipTransition && 'no-transition',\n );\n\n // Add class in the next AF to synchronize with animation with Transition components\n useEffect(() => {\n backButtonRef.current!.classList.toggle('state-back', isBackButton);\n }, [isBackButton]);\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\n const canManage = Boolean(\n !isManagement\n && isProfile\n && chat\n && !selectIsChatWithSelf(global, chat.id)\n // chat.isCreator is for Basic Groups\n && (isChatPrivate(chat.id) || ((isChatAdmin(chat) || chat.isCreator) && !chat.isNotJoined)),\n );\n\n return {\n canManage,\n isChannel,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'searchTextMessagesLocal',\n 'toggleManagement',\n 'openHistoryCalendar',\n ]),\n)(RightHeader));\n","import { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiChatMember, ApiMessage, ApiUser } from '../../../api/types';\nimport { ProfileTabType, SharedMediaType } from '../../../types';\n\nimport { MEMBERS_SLICE, MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, sortUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n loadMoreMembers: AnyToVoidFunction,\n searchMessages: AnyToVoidFunction,\n tabType: ProfileTabType,\n mediaSearchType?: SharedMediaType,\n groupChatMembers?: ApiChatMember[],\n usersById?: Record,\n chatMessages?: Record,\n foundIds?: number[],\n chatId?: number,\n lastSyncTime?: number,\n) {\n const resultType = tabType === 'members' || !mediaSearchType ? tabType : mediaSearchType;\n\n const memberIds = useMemo(() => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return sortUserIds(groupChatMembers.map(({ userId }) => userId), usersById);\n }, [groupChatMembers, usersById]);\n\n const [memberViewportIds, getMoreMembers, noProfileInfoForMembers] = useInfiniteScrollForMembers(\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 let viewportIds: number[] | 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 '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 }\n\n return [resultType, viewportIds, getMore, noProfileInfo] as const;\n}\n\nfunction useInfiniteScrollForMembers(\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n memberIds?: number[],\n) {\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n memberIds,\n undefined,\n MEMBERS_SLICE,\n );\n\n const isOnTop = !viewportIds || !memberIds || viewportIds[0] === memberIds[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n\nfunction useInfiniteScrollForSharedMedia(\n forSharedMediaType: SharedMediaType,\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n chatMessages?: Record,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef();\n\n useOnChange(() => {\n if (currentResultType === forSharedMediaType && chatMessages && foundIds) {\n messageIdsRef.current = getMessageContentIds(\n chatMessages,\n foundIds,\n forSharedMediaType,\n ).reverse();\n }\n }, [chatMessages, foundIds, currentResultType, forSharedMediaType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n messageIdsRef.current,\n undefined,\n forSharedMediaType === 'media' ? SHARED_MEDIA_SLICE : MESSAGE_SEARCH_SLICE,\n );\n\n const isOnTop = !viewportIds || !messageIdsRef.current || viewportIds[0] === messageIdsRef.current[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ProfileState } from '../../../types';\n\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport { throttle } from '../../../util/schedulers';\nimport useEffectWithPrevDeps from '../../../hooks/useEffectWithPrevDeps';\n\nconst TRANSITION_DURATION = 300;\nconst PROGRAMMATIC_SCROLL_TIMEOUT_MS = 350;\n\nconst runThrottledForScroll = throttle((cb) => cb(), 250, false);\n\nlet isScrollingProgrammatically = false;\n\nexport default function useProfileState(\n containerRef: { current: HTMLDivElement | null },\n tabType: string,\n profileState: ProfileState,\n onProfileStateChange: (state: ProfileState) => void,\n) {\n // Scroll to tabs if needed\n useEffectWithPrevDeps(([prevTabType]) => {\n if (prevTabType && prevTabType !== tabType) {\n const container = containerRef.current!;\n const tabsEl = container.querySelector('.TabList')!;\n if (container.scrollTop < tabsEl.offsetTop) {\n onProfileStateChange(tabType === 'members' ? ProfileState.MemberList : ProfileState.SharedMedia);\n isScrollingProgrammatically = true;\n fastSmoothScroll(container, tabsEl, 'start', undefined, undefined, undefined, TRANSITION_DURATION);\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n }\n }\n }, [tabType, onProfileStateChange]);\n\n // Scroll to top\n useEffectWithPrevDeps(([prevProfileState]) => {\n if (profileState !== ProfileState.Profile || profileState === prevProfileState) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl || tabListEl.offsetTop > container.scrollTop) {\n return;\n }\n\n isScrollingProgrammatically = true;\n fastSmoothScroll(\n container,\n container.firstElementChild as HTMLElement,\n 'start',\n undefined,\n container.offsetHeight * 2,\n );\n\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n\n onProfileStateChange(profileState);\n }, [profileState]);\n\n const determineProfileState = useCallback(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl) {\n return;\n }\n\n let state: ProfileState = ProfileState.Profile;\n if (container.scrollTop >= tabListEl.offsetTop) {\n state = tabType === 'members'\n ? ProfileState.MemberList\n : ProfileState.SharedMedia;\n }\n\n onProfileStateChange(state);\n }, [containerRef, onProfileStateChange, tabType]);\n\n // Determine profile state when switching tabs\n useEffect(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n determineProfileState();\n }, [determineProfileState, tabType]);\n\n // Determine profile state when scrolling\n const handleScroll = useCallback(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n runThrottledForScroll(determineProfileState);\n }, [determineProfileState]);\n\n return { handleScroll };\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport {\n ApiUser, ApiChat, ApiMediaFormat, ApiPhoto,\n} from '../../api/types';\n\nimport {\n getChatAvatarHash, isDeletedUser, getUserColorKey, getChatTitle, isChatPrivate, getUserFullName,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport buildClassName from '../../util/buildClassName';\nimport { getFirstLetters } from '../../util/textFormat';\nimport useMedia from '../../hooks/useMedia';\nimport useBlurSync from '../../hooks/useBlurSync';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ProfilePhoto.scss';\n\ntype OwnProps = {\n chat?: ApiChat;\n user?: ApiUser;\n isFirstPhoto?: boolean;\n isSavedMessages?: boolean;\n photo?: ApiPhoto;\n lastSyncTime?: number;\n onClick: NoneToVoidFunction;\n};\n\nconst ProfilePhoto: FC = ({\n chat,\n user,\n photo,\n isFirstPhoto,\n isSavedMessages,\n lastSyncTime,\n onClick,\n}) => {\n const lang = useLang();\n const isDeleted = user && isDeletedUser(user);\n\n function getMediaHash(size: 'normal' | 'big' = 'big', forceAvatar?: boolean) {\n if (photo && !forceAvatar) {\n return `photo${photo.id}?size=c`;\n }\n\n let hash: string | undefined;\n if (!isSavedMessages && !isDeleted) {\n if (user) {\n hash = getChatAvatarHash(user, size);\n } else if (chat) {\n hash = getChatAvatarHash(chat, size);\n }\n }\n\n return hash;\n }\n\n const imageHash = getMediaHash();\n const fullMediaData = useMedia(imageHash, false, ApiMediaFormat.BlobUrl, lastSyncTime);\n const avatarThumbnailData = useMedia(\n !fullMediaData && isFirstPhoto ? getMediaHash('normal', true) : undefined,\n false,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n const thumbDataUri = useBlurSync(!fullMediaData && photo && photo.thumbnail && photo.thumbnail.dataUri);\n const imageSrc = fullMediaData || avatarThumbnailData || thumbDataUri;\n const prevImageSrc = usePrevious(imageSrc);\n\n let content: string | undefined = '';\n\n if (isSavedMessages) {\n content = ;\n } else if (isDeleted) {\n content = ;\n } else if (imageSrc) {\n content = \"\";\n } else if (!imageSrc && user) {\n const userFullName = getUserFullName(user);\n content = userFullName ? getFirstLetters(userFullName, 2) : undefined;\n } else if (!imageSrc && chat) {\n const title = getChatTitle(lang, chat);\n content = title && getFirstLetters(title, isChatPrivate(chat.id) ? 2 : 1);\n } else {\n content = (\n
\n \n
\n );\n }\n\n const fullClassName = buildClassName(\n 'ProfilePhoto',\n `color-bg-${getUserColorKey(user || chat)}`,\n isSavedMessages && 'saved-messages',\n isDeleted && 'deleted-account',\n (!isSavedMessages && !(imageSrc)) && 'no-photo',\n );\n\n return (\n
\n {prevImageSrc && imageSrc && prevImageSrc !== imageSrc && (\n \"\"\n )}\n {typeof content === 'string' ? renderText(content, ['hq_emoji']) : content}\n
\n );\n};\n\nexport default memo(ProfilePhoto);\n","import React, {\n FC, useEffect, useCallback, memo, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiChat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getUserFullName, getUserStatus, isChatChannel, isUserOnline,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport usePhotosPreload from './hooks/usePhotosPreload';\nimport useLang from '../../hooks/useLang';\n\nimport VerifiedIcon from '../common/VerifiedIcon';\nimport ProfilePhoto from './ProfilePhoto';\nimport Transition from '../ui/Transition';\n\nimport './ProfileInfo.scss';\n\ntype OwnProps = {\n userId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n isSavedMessages?: boolean;\n animationLevel: 0 | 1 | 2;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst PrivateChatInfo: FC = ({\n user,\n chat,\n isSavedMessages,\n lastSyncTime,\n animationLevel,\n loadFullUser,\n openMediaViewer,\n}) => {\n const { id: userId } = user || {};\n const { id: chatId } = chat || {};\n const fullName = user ? getUserFullName(user) : (chat ? chat.title : '');\n const photos = (user ? user.photos : (chat ? chat.photos : undefined)) || [];\n const slideAnimation = animationLevel >= 1 ? 'slide' : 'none';\n\n const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);\n const isFirst = isSavedMessages || photos.length <= 1 || currentPhotoIndex === 0;\n const isLast = isSavedMessages || photos.length <= 1 || currentPhotoIndex === photos.length - 1;\n\n // Deleting the last profile photo may result in an error\n useEffect(() => {\n if (currentPhotoIndex > photos.length) {\n setCurrentPhotoIndex(Math.max(0, photos.length - 1));\n }\n }, [currentPhotoIndex, photos.length]);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [userId, loadFullUser, lastSyncTime]);\n\n usePhotosPreload(user || chat, photos, currentPhotoIndex);\n\n const handleProfilePhotoClick = useCallback(() => {\n openMediaViewer({\n avatarOwnerId: userId || chatId,\n profilePhotoIndex: currentPhotoIndex,\n origin: MediaViewerOrigin.ProfileAvatar,\n });\n }, [openMediaViewer, userId, chatId, currentPhotoIndex]);\n\n const selectPreviousMedia = useCallback(() => {\n if (isFirst) {\n return;\n }\n\n setCurrentPhotoIndex(currentPhotoIndex - 1);\n }, [currentPhotoIndex, isFirst]);\n\n const selectNextMedia = useCallback(() => {\n if (isLast) {\n return;\n }\n\n setCurrentPhotoIndex(currentPhotoIndex + 1);\n }, [currentPhotoIndex, isLast]);\n\n // Support for swipe gestures and closing on click\n useEffect(() => {\n const element = document.querySelector(\n '.profile-slide-container > .active, .profile-slide-container > .to',\n );\n if (!element) {\n return undefined;\n }\n\n return captureEvents(element, {\n excludedClosestSelector: '.navigation',\n onSwipe: IS_TOUCH_ENV ? (e, direction) => {\n if (direction === SwipeDirection.Right) {\n selectPreviousMedia();\n } else if (direction === SwipeDirection.Left) {\n selectNextMedia();\n }\n } : undefined,\n });\n }, [selectNextMedia, selectPreviousMedia]);\n\n if (!user && !chat) {\n return undefined;\n }\n\n function renderPhotoTabs() {\n if (isSavedMessages || !photos || photos.length <= 1) {\n return undefined;\n }\n\n return (\n
\n {photos.map((_, i) => (\n \n ))}\n
\n );\n }\n\n function renderPhoto() {\n const photo = !isSavedMessages && photos && photos.length > 0 ? photos[currentPhotoIndex] : undefined;\n\n return (\n \n );\n }\n\n function renderStatus() {\n if (user) {\n return (\n
\n {getUserStatus(lang, user)}\n
\n );\n }\n\n return (\n {\n isChatChannel(chat!)\n ? lang('Subscribers', chat!.membersCount, 'i')\n : lang('Members', chat!.membersCount, 'i')\n }\n \n );\n }\n\n const isVerifiedIconShown = (user && user.isVerified) || (chat && chat.isVerified);\n\n return (\n
\n
\n {renderPhotoTabs()}\n \n {renderPhoto}\n \n\n {!isFirst && (\n \n )}\n {!isLast && (\n \n )}\n
\n\n
\n {isSavedMessages ? (\n
\n

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {isVerifiedIconShown && }\n
\n )}\n {!isSavedMessages && renderStatus()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const { animationLevel } = global.settings.byKey;\n\n return {\n lastSyncTime, user, chat, isSavedMessages, animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import {\n ApiChat, ApiMediaFormat, ApiPhoto, ApiUser,\n} from '../../../api/types';\nimport { useEffect } from '../../../lib/teact/teact';\nimport * as mediaLoader from '../../../util/mediaLoader';\n\nconst PHOTOS_TO_PRELOAD = 4;\n\nexport default function usePhotosPreload(\n profile: ApiUser | ApiChat | undefined,\n photos: ApiPhoto[],\n currentIndex: number,\n) {\n useEffect(() => {\n photos.slice(currentIndex, currentIndex + PHOTOS_TO_PRELOAD).forEach((photo) => {\n const mediaData = mediaLoader.getFromMemory(`photo${photo.id}?size=c`);\n if (!mediaData) {\n mediaLoader.fetch(`photo${photo.id}?size=c`, ApiMediaFormat.BlobUrl);\n }\n });\n }, [currentIndex, photos]);\n}\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isChatPrivate, isUserRightBanned,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { copyTextToClipboard } from '../../util/clipboard';\nimport { formatPhoneNumberWithCode } from '../../util/phoneNumber';\nimport useLang from '../../hooks/useLang';\n\nimport SafeLink from '../common/SafeLink';\nimport ListItem from '../ui/ListItem';\nimport Switcher from '../ui/Switcher';\n\ntype OwnProps = {\n chatOrUserId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n canInviteUsers?: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst ChatExtra: FC = ({\n lastSyncTime,\n user,\n chat,\n forceShowSelf,\n canInviteUsers,\n loadFullUser,\n showNotification,\n updateChatMutedState,\n}) => {\n const {\n id: userId,\n fullInfo,\n username,\n phoneNumber,\n isSelf,\n } = user || {};\n const {\n id: chatId,\n isMuted: currentIsMuted,\n username: chatUsername,\n } = chat || {};\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [loadFullUser, userId, lastSyncTime]);\n\n const handleNotificationChange = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !currentIsMuted });\n }, [chatId, currentIsMuted, updateChatMutedState]);\n\n if (!chat || chat.isRestricted || (isSelf && !forceShowSelf)) {\n return undefined;\n }\n\n function copy(text: string, entity: string) {\n copyTextToClipboard(text);\n showNotification({ message: `${entity} was copied` });\n }\n\n const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber);\n const link = getChatLink(chat);\n const url = link.indexOf('http') === 0 ? link : `http://${link}`;\n const printedUsername = username || chatUsername;\n const description = (fullInfo && fullInfo.bio) || getChatDescription(chat);\n\n return (\n
\n {formattedNumber && !!formattedNumber.length && (\n copy(formattedNumber, lang('Phone'))}>\n {formattedNumber}\n {lang('Phone')}\n \n )}\n {printedUsername && (\n copy(`@${printedUsername}`, lang('Username'))}\n >\n {renderText(printedUsername)}\n {lang('Username')}\n \n )}\n {description && !!description.length && (\n \n \n {renderText(description, ['br', 'links', 'emoji'])}\n \n {lang(userId ? 'UserBio' : 'Info')}\n \n )}\n {canInviteUsers && !printedUsername && !!link.length && (\n copy(link, lang('SetUrlPlaceholder'))}>\n
\n \n
\n {lang('SetUrlPlaceholder')}\n
\n )}\n \n {lang('Notifications')}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatOrUserId }): StateProps => {\n const { lastSyncTime } = global;\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return {\n lastSyncTime, chat, user, canInviteUsers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadFullUser', 'updateChatMutedState', 'showNotification',\n ]),\n)(ChatExtra));\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport {\n MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType,\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 isChatAdmin, isChatChannel, isChatGroup, isChatPrivate,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\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 './ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from './ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: number;\n userId?: number;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n isChannel?: boolean;\n resolvedUserId?: number;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n members?: ApiChatMember[];\n usersById?: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC = ({\n chatId,\n profileState,\n onProfileStateChange,\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n members,\n usersById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n setLocalMediaSearchType,\n loadMoreMembers,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\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\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ]), [hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n usersById, chatMessages, foundIds, chatId, lastSyncTime,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n // 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: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n
\n {!noSpinner && }\n
\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'documents':\n text = lang('lng_media_file_empty_search');\n break;\n case 'links':\n text = lang('lng_media_link_empty_search');\n break;\n case 'audio':\n text = lang('lng_media_song_empty_search');\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!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n viewportIds!.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n
\n \n {renderSharedMedia}\n \n \n
\n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: number, resolvedUserId?: number) {\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 > div.active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById } = global.users;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n\n let resolvedUserId;\n if (userId) {\n resolvedUserId = userId;\n } else if (isChatPrivate(chatId)) {\n resolvedUserId = chatId;\n }\n\n return {\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n ...(hasMembersTab && members && {\n members,\n usersById,\n }),\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat && chat.isRestricted,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalMediaSearchType',\n 'loadMoreMembers',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n 'loadProfilePhotos',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector(transitionElSelector);\n const tabsEl = container.querySelector('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\n};\n\nexport default memo(RightSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\n};\n\nexport default memo(ManagementAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? : ;\n};\n\nexport default memo(StickerSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? : ;\n};\n\nexport default memo(GifSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? : ;\n};\n\nexport default memo(PollResultsAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState, RightColumnContent } from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: number;\n threadId?: number;\n currentProfileUserId?: number;\n isChatSelected: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n}) => {\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const 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(() => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo();\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n // eslint-disable-next-line consistent-return\n function renderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n 'toggleChatInfo',\n 'toggleManagement',\n 'closeLocalTextSearch',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'closePollResults',\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","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 ErrorsAsync: FC = ({ isOpen }) => {\n const Errors = useModuleLoader(Bundles.Extra, 'Errors', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Errors ? : undefined;\n};\n\nexport default memo(ErrorsAsync);\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, useEffect, memo } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n ANIMATION_END_DELAY, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport { pick } from '../../util/iteratees';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport Notifications from './Notifications.async';\nimport Errors from './Errors.async';\nimport ForwardPicker from './ForwardPicker.async';\nimport SafeLinkModal from './SafeLinkModal.async';\nimport HistoryCalendar from './HistoryCalendar.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n animationLevel: number;\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasErrors: boolean;\n audioMessage?: ApiMessage;\n safeLinkModalUrl?: string;\n isHistoryCalendarOpen: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 350;\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet rightColumnAnimationTimeout: number | undefined;\nlet notificationInterval: number | undefined;\n\nlet DEBUG_isLogged = false;\n\nconst Main: FC = ({\n lastSyncTime,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasErrors,\n audioMessage,\n safeLinkModalUrl,\n isHistoryCalendarOpen,\n loadAnimatedEmojis,\n}) => {\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n loadAnimatedEmojis();\n }\n }, [lastSyncTime, loadAnimatedEmojis]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n );\n\n useEffect(() => {\n // For animating Symbol Menu on mobile\n document.body.classList.toggle('is-middle-column-open', className.includes('middle-column-open'));\n // For animating components in portals (i.e. Notification)\n document.body.classList.toggle('is-right-column-shown', className.includes('right-column-open'));\n }, [className]);\n\n // Add `body` classes when toggling right column\n useEffect(() => {\n if (animationLevel > 0) {\n document.body.classList.add('animating-right-column');\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n\n if (rightColumnAnimationTimeout) {\n clearTimeout(rightColumnAnimationTimeout);\n rightColumnAnimationTimeout = undefined;\n }\n\n rightColumnAnimationTimeout = window.setTimeout(() => {\n document.body.classList.remove('animating-right-column');\n rightColumnAnimationTimeout = undefined;\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isRightColumnShown]);\n\n useBackgroundMode(() => {\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n document.title = `${newUnread} notification${newUnread > 1 ? 's' : ''}`;\n updateIcon(true);\n }\n } else {\n document.title = PAGE_TITLE;\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, () => {\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n document.title = PAGE_TITLE;\n }\n\n updateIcon(false);\n });\n\n function stopEvent(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n \n \n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('link[rel=\"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\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n animationLevel: global.settings.byKey.animationLevel,\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 hasErrors: Boolean(global.errors.length),\n audioMessage,\n safeLinkModalUrl: global.safeLinkModalUrl,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadAnimatedEmojis']),\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/4.92917cccdb4999ea7d20.js b/dist/4.92917cccdb4999ea7d20.js deleted file mode 100644 index d6c80ef3..00000000 --- a/dist/4.92917cccdb4999ea7d20.js +++ /dev/null @@ -1,2 +0,0 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{104:function(e,t,a){"use strict";a.r(t),a.d(t,"Main",(function(){return Nc}));var s=a(2),c=a(1),n=a(0),r=(a(84),a(37)),o=a(6);window.addEventListener("popstate",e=>{if(!e.state)return;const{chatId:t,threadId:a,messageListType:c}=e.state;Object(s.d)().openChat({id:t,threadId:a,type:c,noPushState:!0})}),Object(s.b)("openChat",(e,t,a)=>{const{id:c,threadId:n=-1,type:i="thread",noPushState:l}=a,d=Object(o.y)(e);return d&&d.chatId===c&&d.threadId===n&&d.type===i||(e=Object(r.n)(e),e={...e,messages:{...e.messages,contentToBeScheduled:void 0},...c!==e.forwardMessages.toChatId&&{forwardMessages:{}}},Object(s.g)(e),l||window.history.pushState({chatId:c,threadId:n,messageListType:i},"")),Object(r.N)(e,c,n,i)}),Object(s.b)("openChatWithInfo",(e,t,a)=>{Object(s.g)({...e,isChatInfoShown:!0}),t.openChat(a)}),Object(s.b)("resetChatCreation",e=>({...e,chatCreation:void 0}));var i=a(5),l=a(20),d=a(3);let b;Object(s.b)("setScrollOffset",(e,t,a)=>{const{chatId:s,threadId:c,scrollOffset:n}=a;return Object(r.x)(e,s,c,"scrollOffset",n)}),Object(s.b)("setReplyingToId",(e,t,a)=>{const{messageId:s}=a,c=Object(o.y)(e);if(!c)return;const{chatId:n,threadId:i}=c;return Object(r.x)(e,n,i,"replyingToId",s)}),Object(s.b)("setEditingId",(e,t,a)=>{const{messageId:s}=a,c=Object(o.y)(e);if(!c)return;const{chatId:n,threadId:i,type:l}=c,d="scheduled"===l?"editingScheduledId":"editingId";return Object(r.x)(e,n,i,d,s)}),Object(s.b)("editLastMessage",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(!t||!a)return;const s=Object(o.m)(e,t),c=Object(o.Hb)(e,t,a);if(!s||!c)return;const n=Object(d.g)(c,t=>Boolean(s[t]&&Object(o.b)(e,s[t],a).canEdit));return n?Object(r.x)(e,t,a,"editingId",n):void 0}),Object(s.b)("replyToNextMessage",(e,t,a)=>{const{targetIndexDelta:s}=a,{chatId:c,threadId:n}=Object(o.y)(e)||{};if(!c||!n)return;const r=Object(o.m)(e,c),l=Object(o.Hb)(e,c,n);if(!r||!l)return;const d=Object(o.mb)(e,c,n);let b;if(Object(o.X)(e,c,n)&&d){const e=Object.keys(r),t=e.indexOf(d.toString())+s;b=t<=e.length+1&&t>=0?Number(e[t]):void 0}else if(n===i.MAIN_THREAD_ID){const t=Object(o.f)(e,c);b=t&&t.lastMessage?t.lastMessage.id:void 0}else{const t=Object(o.Cb)(e,c,n);b=t?t.lastMessageId:void 0}t.setReplyingToId({messageId:b}),t.focusMessage({chatId:c,threadId:n,messageId:b})}),Object(s.b)("openMediaViewer",(e,t,a)=>{const{chatId:s,threadId:c,messageId:n,avatarOwnerId:r,profilePhotoIndex:o,origin:i}=a;return{...e,mediaViewer:{chatId:s,threadId:c,messageId:n,avatarOwnerId:r,profilePhotoIndex:o,origin:i},forwardMessages:{}}}),Object(s.b)("closeMediaViewer",e=>({...e,mediaViewer:{}})),Object(s.b)("openAudioPlayer",(e,t,a)=>{const{chatId:s,threadId:c,messageId:n}=a;return{...e,audioPlayer:{chatId:s,threadId:c,messageId:n}}}),Object(s.b)("closeAudioPlayer",e=>({...e,audioPlayer:{}})),Object(s.b)("openPollResults",(e,t,a)=>{const{chatId:c,messageId:n}=a;Object(o.W)(e)?c===e.pollResults.chatId&&n===e.pollResults.messageId||Object(s.g)({...e,pollResults:{chatId:c,messageId:n,voters:{}}}):window.setTimeout(()=>{const e=Object(s.e)();Object(s.g)({...e,pollResults:{chatId:c,messageId:n,voters:{}}})},450)}),Object(s.b)("closePollResults",e=>{Object(s.g)({...e,pollResults:{}})}),Object(s.b)("focusLastMessage",(e,t)=>{const a=Object(o.y)(e);if(!a)return;const{chatId:s,threadId:c}=a;let n;if(c===i.MAIN_THREAD_ID){const t=Object(o.f)(e,s);n=t&&t.lastMessage?t.lastMessage.id:void 0}else{const t=Object(o.Cb)(e,s,c);n=t?t.lastMessageId:void 0}n&&t.focusMessage({chatId:s,threadId:c,messageId:n,noHighlight:!0})}),Object(s.b)("focusMessage",(e,t,a)=>{const{chatId:c,threadId:n=i.MAIN_THREAD_ID,messageListType:d="thread",noHighlight:u,groupedId:m,groupedChatId:h}=a;let{messageId:O}=a;if(void 0!==m){const t=Object(o.J)(e,h,m);t&&t.length&&([O]=t)}const j=Object(o.y)(e),g=!j||c!==j.chatId||n!==j.threadId||d!==j.type;b&&(clearTimeout(b),b=void 0),b=window.setTimeout(()=>{let e=Object(s.e)();e=Object(r.P)(e),e=Object(r.O)(e),Object(s.g)(e)},2e3),e=Object(r.P)(e,c,O,u),e=Object(r.O)(e,void 0),g&&(e=Object(r.O)(e,l.b.Static));const f=Object(o.Hb)(e,c,n);if(f&&f.includes(O))return Object(s.g)(e),void t.openChat({id:c,threadId:n});if(g&&(e=Object(r.x)(e,c,n,"viewportIds",void 0)),e=Object(r.x)(e,c,n,"outlyingIds",void 0),f&&!g){const t=O>f[0]?l.b.Down:l.b.Up;e=Object(r.O)(e,t)}Object(s.g)(e),t.openChat({id:c,threadId:n}),t.loadViewportMessages()}),Object(s.b)("openForwardMenu",(e,t,a)=>{const{fromChatId:s,messageIds:c,groupedId:n}=a;let r;return n&&(r=Object(o.ab)(e,s,n)),{...e,forwardMessages:{fromChatId:s,messageIds:r||c,isModalShown:!0}}}),Object(s.b)("exitForwardMode",e=>{Object(s.g)({...e,forwardMessages:{}})}),Object(s.b)("setForwardChatId",(e,t,a)=>{const{id:c}=a;Object(s.g)({...e,forwardMessages:{...e.forwardMessages,toChatId:c,isModalShown:!1}}),t.openChat({id:c}),t.closeMediaViewer(),t.exitMessageSelectMode()}),Object(s.b)("openForwardMenuForSelectedMessages",(e,t)=>{if(!e.selectedMessages)return;const{chatId:a,messageIds:s}=e.selectedMessages;t.openForwardMenu({fromChatId:a,messageIds:s})}),Object(s.b)("enterMessageSelectMode",(e,t,a)=>{const{messageId:s}=a||{},c=Object(o.r)(e);return c?Object(r.m)(e,c.id,s):e}),Object(s.b)("toggleMessageSelection",(e,t,a)=>{const{messageId:s,groupedId:c,childMessageIds:n,withShift:i}=a,l=Object(o.y)(e);if(!l)return;const{chatId:d,threadId:b,type:u}=l;return Object(r.G)(e,d,b,u,s,c,n,i)}),Object(s.b)("exitMessageSelectMode",r.n),Object(s.b)("openPollModal",e=>({...e,isPollModalOpen:!0})),Object(s.b)("closePollModal",e=>({...e,isPollModalOpen:!1}));Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{query:s}=a,{chatId:c}=e.globalSearch;return Object(r.R)(e,{globalResults:{},localResults:{},resultsByType:void 0,...s?{fetchingStatus:{chats:!c,messages:!0}}:{fetchingStatus:void 0},query:s})}),Object(s.b)("addRecentlyFoundChatId",(e,t,a)=>{const{id:s}=a,{recentlyFoundChatIds:c}=e.globalSearch;if(!c)return Object(r.R)(e,{recentlyFoundChatIds:[s]});const n=c.filter(e=>e!==s);return n.unshift(s),n.length>10&&n.pop(),Object(r.R)(e,{recentlyFoundChatIds:n})}),Object(s.b)("clearRecentlyFoundChats",e=>Object(r.R)(e,{recentlyFoundChatIds:void 0})),Object(s.b)("setGlobalSearchContent",(e,t,a)=>{const{content:s}=a;return Object(r.S)(e,s)}),Object(s.b)("setGlobalSearchChatId",(e,t,a)=>{const{id:s}=a;return Object(r.R)(e,{chatId:s,query:void 0,resultsByType:void 0})});var u=a(50),m=a(4);Object(s.b)("openLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return Object(r.Y)(e,t,a,!0)}),Object(s.b)("closeLocalTextSearch",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{};if(t&&a)return e=Object(r.Y)(e,t,a,!1),e=Object(r.t)(e,t,a,void 0)}),Object(s.b)("setLocalTextSearchQuery",(e,t,a)=>{const{chatId:s,threadId:c}=Object(o.y)(e)||{};if(!s||!c)return;const{query:n}=a,i=Object(m.a)(s,c),{query:l}=e.localTextSearch.byChatThreadKey[i]||{};return n!==l&&(e=Object(r.t)(e,s,c,u.a)),e=Object(r.Y)(e,s,c,!0,n)}),Object(s.b)("setLocalMediaSearchType",(e,t,a)=>{const{chatId:s}=Object(o.y)(e)||{};if(!s)return;const{mediaType:c}=a;return Object(r.X)(e,s,c)}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,stickers:{...e.stickers,search:{query:s,resultIds:void 0}}}}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;return{...e,gifs:{...e.gifs,search:{query:s,offsetId:void 0,results:void 0}}}}),Object(s.b)("openUserInfo",(e,t,a)=>{const{id:s}=a;t.openChat({id:s})});Object(s.b)("openChat",e=>Object(r.fb)(e,void 0)),Object(s.b)("setSettingOption",(e,t,a)=>Object(r.v)(e,a)),Object(s.b)("setThemeSettings",(e,t,a)=>{const{theme:s,...c}=a;return Object(r.w)(e,s,c)});var h=a(7),O=a(169);Object(s.b)("toggleChatInfo",e=>({...e,isChatInfoShown:!e.isChatInfoShown})),Object(s.b)("toggleManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}}),Object(s.b)("closeManagement",e=>{const{chatId:t}=Object(o.y)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}}),Object(s.b)("openChat",(e,t,a)=>{if(!h.g)return;const{id:s}=a;return{...e,isLeftColumnShown:void 0===s}}),Object(s.b)("toggleLeftColumn",e=>({...e,isLeftColumnShown:!e.isLeftColumnShown})),Object(s.b)("addRecentEmoji",(e,t,a)=>{const{emoji:s}=a,{recentEmojis:c}=e;if(!c)return{...e,recentEmojis:[s]};const n=c.filter(e=>e!==s);return n.unshift(s),n.length>18&&n.pop(),{...e,recentEmojis:n}}),Object(s.b)("addRecentSticker",(e,t,a)=>{const{sticker:s}=a,{recent:c}=e.stickers;if(!c)return{...e,stickers:{...e.stickers,recent:{hash:0,stickers:[s]}}};const n=c.stickers.filter(e=>e.id!==s.id);return n.unshift(s),{...e,stickers:{...e.stickers,recent:{...c,stickers:n}}}}),Object(s.b)("showNotification",(e,t,a)=>{const s=a,c=[...e.notifications],n=c.findIndex(e=>e.message===s.message);return-1!==n&&c.splice(n,1),c.push(s),{...e,notifications:c}}),Object(s.b)("dismissNotification",e=>{const t=[...e.notifications];return t.pop(),{...e,notifications:t}}),Object(s.b)("showError",(e,t,a)=>{const{error:s}=a;if(!Object(O.a)(s))return e;const c=[...e.errors],n=c.findIndex(e=>e.message===s.message);return-1!==n&&c.splice(n,1),c.push(s),{...e,errors:c}}),Object(s.b)("dismissError",e=>{const t=[...e.errors];return t.pop(),{...e,errors:t}}),Object(s.b)("toggleSafeLinkModal",(e,t,a)=>{const{url:s}=a;return{...e,safeLinkModalUrl:s}}),Object(s.b)("openPaymentModal",(e,t,a)=>{const{messageId:s}=a;return{...e,payment:{...e.payment,messageId:s,isPaymentModalOpen:!0}}}),Object(s.b)("closePaymentModal",e=>{const t=Object(r.h)(e);return Object(r.i)(t)});a(85);var j=a(10),g=a(9);const f=Object(g.g)(e=>e(),1e3,!0),p=Object(g.g)(e=>e(),3e3,!0),I=Object(g.a)(e=>e(),500,!1,!0);async function v(e,t,a){const n=await Object(j.a)("fetchChats",{limit:c.j,offsetDate:a,archived:"archived"===e,withPinned:void 0===Object(s.e)().chats.orderedPinnedIds[e]});if(!n)return;const{chatIds:o}=n;o.length>0&&o[0]===t&&o.shift();let l=Object(s.e)();l=Object(r.f)(l,Object(d.c)(n.users,"id")),l=Object(r.M)(l,Object(d.c)(n.chats,"id")),l=Object(r.I)(l,e,o),l=Object(r.J)(l,e,n),Object.keys(n.draftsById).map(Number).forEach(e=>{l=Object(r.x)(l,e,i.MAIN_THREAD_ID,"draft",n.draftsById[e])}),Object.keys(n.replyingToById).map(Number).forEach(e=>{l=Object(r.x)(l,e,i.MAIN_THREAD_ID,"replyingToId",n.replyingToById[e])}),0!==o.length||l.chats.isFullyLoaded[e]||(l={...l,chats:{...l.chats,isFullyLoaded:{...l.chats.isFullyLoaded,[e]:!0}}}),Object(s.g)(l)}async function y(e){const t=await Object(j.a)("fetchFullChat",e);if(!t)return;const{users:a,fullInfo:c}=t;let n=Object(s.e)();a&&(n=Object(r.f)(n,Object(d.c)(a,"id"))),n=Object(r.H)(n,e.id,{fullInfo:c}),Object(s.g)(n)}async function C(e,t,a){const c=Object(s.e)(),n=Object(o.h)(c,t);if(n&&!n.isMin)return void(a?e.focusMessage({chatId:n.id,messageId:a}):e.openChat({id:n.id}));const i=Object(o.r)(c);e.openChat({id:-1});const l=await Object(j.a)("getChatByUsername",t);if(!l)return i&&e.openChat({id:i.id}),void e.showNotification({message:"User does not exist"});Object(s.g)(Object(r.H)(Object(s.e)(),l.id,l)),a?e.focusMessage({chatId:l.id,messageId:a}):e.openChat({id:l.id})}Object(s.b)("preloadTopChatMessages",(e,t)=>{(async()=>{const a=[];for(let n=0;ne!==l&&!a.includes(e));if(!u)return;a.push(u.id),t.loadViewportMessages({chatId:u.id,threadId:i.MAIN_THREAD_ID})}})()}),Object(s.b)("openChat",(e,t,a)=>{const{id:s,threadId:c}=a,{currentUserId:n}=e,r=Object(o.f)(e,s);if(r&&r.hasUnreadMark&&t.toggleChatUnread({id:s}),r)Object(m.mb)(r)&&!r.isMin&&t.requestChatUpdate({chatId:s});else if(s===n)Object(j.a)("fetchChat",{type:"self"});else{const t=Object(o.Gb)(e,s);t&&Object(j.a)("fetchChat",{type:"user",user:t})}if(c!==i.MAIN_THREAD_ID){Object(o.Eb)(e,s,c)||t.requestThreadInfoUpdate({chatId:s,threadId:c})}}),Object(s.b)("openSupportChat",(e,t)=>{const a=Object(o.Ab)(e);t.openChat({id:a?a.id:-1}),a||(async()=>{const e=await Object(j.a)("fetchChat",{type:"support"});e&&t.openChat({id:e.chatId})})()}),Object(s.b)("openTipsChat",(e,t)=>{t.openChatByUsername({username:c.Cb})}),Object(s.b)("loadMoreChats",(e,t,a)=>{const{listType:s="active"}=a,c=e.chats.listIds[s];if(e.chats.isFullyLoaded[s])return;const n=c?c.map(t=>e.chats.byId[t]).filter(t=>Boolean(t&&t.lastMessage)&&!Object(o.N)(e,t.id)).sort((e,t)=>e.lastMessage.date-t.lastMessage.date)[0]:void 0;f(n?()=>v(s,n.id,n.lastMessage.date):()=>v(s))}),Object(s.b)("loadFullChat",(e,t,a)=>{const{chatId:s,force:c}=a,n=Object(o.f)(e,s);n&&(c?y(n):I(()=>y(n)))}),Object(s.b)("loadTopChats",()=>{p(()=>v("active"))}),Object(s.b)("requestChatUpdate",(e,t,a)=>{const{chatId:s}=a,c=Object(o.f)(e,s);c&&Object(j.a)("requestChatUpdate",c)}),Object(s.b)("updateChatMutedState",(e,t,a)=>{const{chatId:s,isMuted:c}=a,n=Object(o.f)(e,s);n&&Object(j.a)("updateChatMutedState",{chat:n,isMuted:c})}),Object(s.b)("createChannel",(e,t,a)=>{const{title:c,about:n,photo:i,memberIds:d}=a;!async function(e,t,a,c){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const n=await Object(j.a)("createChannel",{title:e,about:a,users:t});if(!n)return;const{id:o,accessHash:i}=n;let d=Object(s.e)();d=Object(r.H)(d,o,n),d={...d,chatCreation:{...d.chatCreation,progress:n?l.a.Complete:l.a.Error}},Object(s.g)(d),Object(s.d)().openChat({id:o}),o&&i&&c&&await Object(j.a)("editChatPhoto",{chatId:o,accessHash:i,photo:c})}(c,d.map(t=>Object(o.Gb)(e,t)).filter(Boolean),n,i)}),Object(s.b)("joinChannel",(e,t,a)=>{const{chatId:s}=a,c=Object(o.f)(e,s);if(!c)return;const{id:n,accessHash:r}=c;n&&r&&Object(j.a)("joinChannel",{channelId:n,accessHash:r})}),Object(s.b)("leaveChannel",(e,t,a)=>{(async()=>{const{chatId:s}=a,c=Object(o.f)(e,s);if(!c)return;const{id:n,accessHash:r}=c;n&&r&&await Object(j.a)("leaveChannel",{channelId:n,accessHash:r}),t.openChat({id:void 0})})()}),Object(s.b)("deleteChannel",(e,t,a)=>{(async()=>{const{chatId:s}=a,c=Object(o.f)(e,s);if(!c)return;const{id:n,accessHash:r}=c;n&&r&&await Object(j.a)("deleteChannel",{channelId:n,accessHash:r}),t.openChat({id:void 0})})()}),Object(s.b)("createGroupChat",(e,t,a)=>{const{title:c,memberIds:n,photo:i}=a;!async function(e,t,a){Object(s.g)({...Object(s.e)(),chatCreation:{progress:l.a.InProgress}});const c=await Object(j.a)("createGroupChat",{title:e,users:t});if(!c)return;const{id:n}=c;let o=Object(s.e)();o=Object(r.H)(o,n,c),o={...o,chatCreation:{...o.chatCreation,progress:c?l.a.Complete:l.a.Error}},Object(s.g)(o),Object(s.d)().openChat({id:n}),n&&a&&await Object(j.a)("editChatPhoto",{chatId:n,photo:a})}(c,n.map(t=>Object(o.Gb)(e,t)).filter(Boolean),i)}),Object(s.b)("toggleChatPinned",(e,t,a)=>{const{id:s,folderId:n}=a,r=Object(o.f)(e,s);if(r)if(n){const t=Object(o.i)(e,n);if(t){const a=!Object(o.N)(e,s,n),{pinnedChatIds:c,includedChatIds:r}=t,i=a?[s,...c||[]]:(c||[]).filter(e=>e!==s),l=[s,...r];Object(j.a)("editChatFolder",{id:n,folderUpdate:{...t,pinnedChatIds:i,includedChatIds:l}})}}else{const t=Object(o.j)(e,s),a=Object(o.N)(e,s,"archived"===t?c.h:void 0);Object(j.a)("toggleChatPinned",{chat:r,shouldBePinned:!a})}}),Object(s.b)("toggleChatArchived",(e,t,a)=>{const{id:s}=a,n=Object(o.f)(e,s);n&&Object(j.a)("toggleChatArchived",{chat:n,folderId:Object(m.hb)(n)?0:c.h})}),Object(s.b)("loadChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,...e}})}}()}),Object(s.b)("loadRecommendedChatFolders",()=>{!async function(){const e=await Object(j.a)("fetchRecommendedChatFolders");if(e){const t=Object(s.e)();Object(s.g)({...t,chatFolders:{...t.chatFolders,recommended:e}})}}()}),Object(s.b)("editChatFolder",(e,t,a)=>{const{id:s,folderUpdate:c}=a,n=Object(o.i)(e,s);n&&Object(j.a)("editChatFolder",{id:s,folderUpdate:{id:s,emoticon:n.emoticon,pinnedChatIds:n.pinnedChatIds,...c}})}),Object(s.b)("addChatFolder",(e,t,a)=>{const{folder:n}=a,{orderedIds:r}=e.chatFolders;!async function(e,t){const{id:a,description:c,...n}=e;if(await Object(j.a)("editChatFolder",{id:t+1,folderUpdate:{id:t+1,...n}}),!c)return;const r=Object(s.e)(),{recommended:o}=r.chatFolders;o&&Object(s.g)({...r,chatFolders:{...r.chatFolders,recommended:o.filter(({id:e})=>e!==a)}})}(n,r&&r.length?Math.max.apply(Math.max,r):c.h)}),Object(s.b)("deleteChatFolder",(e,t,a)=>{const{id:s}=a;Object(o.i)(e,s)&&async function(e){await Object(j.a)("deleteChatFolder",e)}(s)}),Object(s.b)("toggleChatUnread",(e,t,a)=>{const{id:s}=a,c=Object(o.f)(e,s);c&&(c.unreadCount?Object(j.a)("markMessageListRead",{chat:c,threadId:i.MAIN_THREAD_ID}):Object(j.a)("toggleDialogUnread",{chat:c,hasUnreadMark:!c.hasUnreadMark}))}),Object(s.b)("openTelegramLink",(e,t,a)=>{const{url:s}=a;let n=c.hb.exec(s);if(n){const e=n[1];(async()=>{const a=await Object(j.a)("openChatByInvite",e);a&&t.openChat({id:a.id})})()}else{n=c.ib.exec(s);const e=n[1],a=n[2]?Number(n[2]):void 0;C(t,e,a)}}),Object(s.b)("openChatByUsername",(e,t,a)=>{const{username:s}=a;C(t,s)}),Object(s.b)("togglePreHistoryHidden",(e,t,a)=>{const{chatId:s,isEnabled:c}=a;let n=Object(o.f)(e,s);n&&(async()=>{if(Object(m.ib)(n)){if(n=await Object(j.a)("migrateChat",n),!n)return;t.openChat({id:n.id})}Object(j.a)("togglePreHistoryHidden",{chat:n,isEnabled:c})})()}),Object(s.b)("updateChatDefaultBannedRights",(e,t,a)=>{const{chatId:s,bannedRights:c}=a,n=Object(o.f)(e,s);n&&Object(j.a)("updateChatDefaultBannedRights",{chat:n,bannedRights:c})}),Object(s.b)("updateChatMemberBannedRights",(e,t,a)=>{const{chatId:c,userId:n,bannedRights:i}=a;let l=Object(o.f)(e,c);const d=Object(o.Gb)(e,n);l&&d&&(async()=>{if(Object(m.ib)(l)){if(l=await Object(j.a)("migrateChat",l),!l)return;t.openChat({id:l.id})}await Object(j.a)("updateChatMemberBannedRights",{chat:l,user:d,bannedRights:i});const e=Object(s.e)(),a=Object(o.f)(e,c);if(!a||!a.fullInfo)return;const{members:b,kickedMembers:u}=a.fullInfo,h=!!i.viewMessages,O=!Object.keys(i).length;Object(s.g)(Object(r.H)(e,c,{fullInfo:{...a.fullInfo,...b&&h&&{members:b.filter(e=>e.userId!==n)},...b&&!h&&{members:b.map(e=>e.userId===n?{...e,bannedRights:i}:e)},...O&&u&&{kickedMembers:u.filter(e=>e.userId!==n)}}}))})()}),Object(s.b)("updateChatAdmin",(e,t,a)=>{const{chatId:c,userId:n,adminRights:i,customTitle:l}=a;let d=Object(o.f)(e,c);const b=Object(o.Gb)(e,n);d&&b&&(async()=>{if(Object(m.ib)(d)){if(d=await Object(j.a)("migrateChat",d),!d)return;t.openChat({id:d.id})}await Object(j.a)("updateChatAdmin",{chat:d,user:b,adminRights:i,customTitle:l});const e=Object(s.e)(),a=Object(o.f)(e,c);if(!a||!a.fullInfo)return;const{adminMembers:u}=a.fullInfo,h=!Object.keys(i).length;Object(s.g)(Object(r.H)(e,c,{fullInfo:{...a.fullInfo,...u&&h&&{adminMembers:u.filter(e=>e.userId!==n)},...u&&!h&&{adminMembers:u.map(e=>e.userId===n?{...e,adminRights:i,customTitle:l}:e)}}}))})()}),Object(s.b)("updateChat",(e,t,a)=>{const{chatId:c,title:n,about:i,photo:d}=a,b=Object(o.f)(e,c);b&&(async()=>{Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.InProgress)),await Promise.all([b.title!==n?Object(j.a)("updateChatTitle",b,n):void 0,b.fullInfo&&b.fullInfo.about!==i?Object(j.a)("updateChatAbout",b,i):void 0,d?Object(j.a)("editChatPhoto",{chatId:c,accessHash:b.accessHash,photo:d}):void 0]),Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.Complete))})()}),Object(s.b)("toggleSignatures",(e,t,a)=>{const{chatId:s,isEnabled:c}=a,n=Object(o.f)(e,s);n&&Object(j.a)("toggleSignatures",{chat:n,isEnabled:c})}),Object(s.b)("loadGroupsForDiscussion",()=>{(async()=>{const e=await Object(j.a)("fetchGroupsForDiscussion");if(!e)return;const t=e.reduce((e,t)=>(t&&(e[t.id]=t),e),{}),a=Object(r.c)(Object(s.e)(),t);Object(s.g)({...a,chats:{...a.chats,forDiscussionIds:Object.keys(t).map(Number)}})})()}),Object(s.b)("linkDiscussionGroup",(e,t,a)=>{const{channelId:s,chatId:c}=a,n=Object(o.f)(e,s);let r=Object(o.f)(e,c);n&&r&&(async()=>{if(Object(m.ib)(r)){if(r=await Object(j.a)("migrateChat",r),!r)return;t.openChat({id:r.id})}let{fullInfo:e}=r;if(!e){const t=await Object(j.a)("fetchFullChat",r);if(!t)return;e=t.fullInfo}e.isPreHistoryHidden&&await Object(j.a)("togglePreHistoryHidden",{chat:r,isEnabled:!1}),Object(j.a)("setDiscussionGroup",{channel:n,chat:r})})()}),Object(s.b)("unlinkDiscussionGroup",(e,t,a)=>{const{channelId:s}=a,c=Object(o.f)(e,s);if(!c)return;let n;c.fullInfo&&c.fullInfo.linkedChatId&&(n=Object(o.f)(e,c.fullInfo.linkedChatId)),(async()=>{await Object(j.a)("setDiscussionGroup",{channel:c}),n&&y(n)})()}),Object(s.b)("setActiveChatFolder",(e,t,a)=>({...e,chatFolders:{...e.chatFolders,activeChatFolder:a}})),Object(s.b)("loadMoreMembers",e=>{(async()=>{const{chatId:t}=Object(o.y)(e)||{},a=t?Object(o.f)(e,t):void 0;if(!a||Object(m.ib)(a))return;const c=a.fullInfo&&a.fullInfo.members&&a.fullInfo.members.length||void 0,n=await Object(j.a)("fetchMembers",a.id,a.accessHash,"recent",c);if(!n)return;const{members:i,users:l}=n;i&&i.length&&(e=Object(s.e)(),e=Object(r.f)(e,Object(d.c)(l,"id")),e=Object(r.H)(e,a.id,{fullInfo:{...a.fullInfo,members:[...(a.fullInfo||{}).members||[],...i||[]]}}),Object(s.g)(e))})()});var E=a(153);const w=new Map,M=Object(g.g)(e=>e(),1e3,!0);async function S(e,t,a,n,i=!1,b=!1){const u=e.id;let m;switch(n){case l.e.Backwards:m=void 0;break;case l.e.Around:m=-(Math.round(c.V/2)+1);break;case l.e.Forwards:m=-(c.V+1)}const h=await Object(j.a)("fetchMessages",{chat:Object(o.Db)(Object(s.e)(),u,t),offsetId:a,addOffset:m,limit:c.V,threadId:t});if(!h)return;const{messages:O,users:g,chats:f,threadInfos:p}=h,I=Object(d.c)(O,"id"),v=Object.keys(I).map(Number);let y=Object(s.e)();y=Object(r.b)(y,u,I),y=i?Object(r.db)(y,u,t,v):Object(r.V)(y,u,t,v),y=Object(r.f)(y,Object(d.c)(g,"id")),y=Object(r.c)(y,Object(d.c)(f,"id")),y=Object(r.lb)(y,u,p);let C=Object(o.Y)(y,u,t);const E=Object(o.gb)(y,u,t);if(i&&C&&E&&Object(d.b)(C,E)&&(y=Object(r.V)(y,u,t,E),C=Object(o.Y)(y,u,t),y=Object(r.x)(y,u,t,"outlyingIds",void 0),i=!1),!b){const e=i?E:C,{newViewportIds:s}=k(e,a,n);y=Object(r.z)(y,u,t,s)}Object(s.g)(y)}function k(e,t,a){const{length:s}=e,n=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex((a,s)=>a===t||at)}(e,t):-1,r=a===l.e.Backwards?n:n+1||s,o=r-c.V,i=r+c.V-1,d=e.slice(Math.max(0,o),i+1);let b,u;switch(a){case l.e.Backwards:b=r>0,u=o>=0;break;case l.e.Forwards:b=r0,u=d.length===c.V}return{newViewportIds:d,areSomeLocal:b,areAllLocal:u}}async function N(e){let t;const a=e.attachment?(e,c)=>{w.has(c)||(t=c,w.set(c,a));const n=Object(s.e)();Object(s.g)({...n,fileUploads:{byMessageLocalId:{...n.fileUploads.byMessageLocalId,[c]:{progress:e}}}})}:void 0;e.replyingTo&&await Object(g.f)();const c=Object(s.e)(),n=Object(o.y)(c);if(!n)return;const{threadId:r}=n;e.replyingTo||r===i.MAIN_THREAD_ID||(e.replyingTo=Object(o.Eb)(c,e.chat.id,r)),await Object(j.a)("sendMessage",e,a),a&&t&&w.delete(t)}Object(s.b)("loadViewportMessages",(e,t,a)=>{const{direction:s=l.e.Around,isBudgetPreload:n=!1}=a||{};let{chatId:i,threadId:d}=a||{};if(!i){const t=Object(o.y)(e);if(!t)return;i=t.chatId,d=t.threadId}const b=Object(o.f)(e,i);if(!b||b.isRestricted)return;const u=Object(o.Hb)(e,i,d),m=Object(o.Y)(e,i,d),h=Object(o.gb)(e,i,d);if(u&&u.length&&s!==l.e.Around){const a=s===l.e.Backwards?u[0]:u[u.length-1],c=Boolean(h),o=c?h:m,{newViewportIds:O,areSomeLocal:j,areAllLocal:g}=k(o,a,s);if(j&&(e=Object(r.z)(e,i,d,O)),async function(e,t,a,s,c,n,r,o){t||await S(c,n,o,r,a,s);s||(await Promise.resolve(),e.loadViewportMessages({chatId:c.id,threadId:n,direction:r,isBudgetPreload:!0}))}(t,g,c,n,b,d,s,a),n)return}else{const t=Object(o.I)(e,i)||Object(o.lb)(e,i,d),a=Boolean(t&&m&&!m.includes(t)),s=(a?h:m)||[],{newViewportIds:u,areSomeLocal:O,areAllLocal:j}=k(s,t,l.e.Around);O&&u.length>=c.V&&(e=Object(r.z)(e,i,d,u)),j||S(b,d,t,l.e.Around,a,n)}return e}),Object(s.b)("loadMessage",(e,t,a)=>{const{chatId:c,messageId:n,replyOriginForId:l}=a,b=Object(o.f)(e,c);b&&async function(e,t,a){const c=await Object(j.a)("fetchMessage",{chat:e,messageId:t});if(!c)return;if(c===i.MESSAGE_DELETED){if(a){let t=Object(s.e)();const c=Object(o.k)(t,e.id,a);t=Object(r.L)(t,e.id,a,{...c,replyToMessageId:void 0}),Object(s.g)(t)}return}let n=Object(s.e)();n=Object(r.L)(n,e.id,t,c.message),n=Object(r.f)(n,Object(d.c)(c.users,"id")),Object(s.g)(n)}(b,n,l)}),Object(s.b)("sendMessage",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:n,threadId:r,type:i}=s;if("scheduled"===i&&!a.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:a}};const l=Object(o.f)(e,n);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:n,threadId:r,value:!1});const b={...a,chat:l,replyingTo:Object(o.mb)(e,n,r),noWebPage:Object(o.cb)(e,n,r)},u=!a.attachments||a.attachments.length<=1,m=!u&&a.attachments&&a.attachments.length>1;if(u){const{attachments:e,...t}=b;N({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:a,...s}=b,n=Object(d.n)(a,c.L);for(let a=0;a0?o:void 0}),r.forEach(e=>{N({...s,attachment:e,groupedId:o})})}}else{const{text:e,entities:t,attachments:a,replyingTo:s,...c}=b;e&&N({...c,text:e,entities:t,replyingTo:s}),a.forEach(e=>{N({...c,attachment:e})})}}),Object(s.b)("editMessage",(e,t,a)=>{const{text:s,entities:c}=a,n=Object(o.y)(e);if(!n)return;const{chatId:r,threadId:i,type:l}=n,d=Object(o.f)(e,r),b=Object(o.D)(e,r,i,l);d&&b&&(Object(j.a)("editMessage",{chat:d,message:b,text:s,entities:c,noWebPage:Object(o.cb)(e,r,i)}),t.setEditingId({messageId:void 0}))}),Object(s.b)("cancelSendingMessage",(e,t,a)=>{const{chatId:s,messageId:c}=a,n=Object(o.k)(e,s,c),r=n&&w.get(n.previousLocalId||n.id);r&&Object(j.b)(r),t.apiUpdate({"@type":"deleteMessages",ids:[c],chatId:s})}),Object(s.b)("saveDraft",(e,t,a)=>{const{chatId:s,threadId:c,draft:n}=a;if(!n)return;const{text:l,entities:d}=n,b=Object(o.f)(e,s);return c===i.MAIN_THREAD_ID&&Object(j.a)("saveDraft",{chat:b,text:l,entities:d,replyToMsgId:Object(o.mb)(e,s,c)}),Object(r.x)(e,s,c,"draft",n)}),Object(s.b)("clearDraft",(e,t,a)=>{const{chatId:s,threadId:c,localOnly:n}=a;if(!Object(o.B)(e,s,c))return;const l=Object(o.f)(e,s);return n||c!==i.MAIN_THREAD_ID||Object(j.a)("clearDraft",l),Object(r.x)(e,s,c,"draft",void 0)}),Object(s.b)("toggleMessageWebPage",(e,t,a)=>{const{chatId:s,threadId:c,noWebPage:n}=a;return Object(r.x)(e,s,c,"noWebPage",n)}),Object(s.b)("pinMessage",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageId:c,isUnpin:n,isOneSide:r,isSilent:i}=a;Object(j.a)("pinMessage",{chat:s,messageId:c,isUnpin:n,isOneSide:r,isSilent:i})}),Object(s.b)("unpinAllMessages",(e,t,a)=>{const c=Object(o.f)(e,a.chatId);c&&async function(e){await Object(j.a)("unpinAllMessages",{chat:e});let t=Object(s.e)();t=Object(r.x)(t,e.id,i.MAIN_THREAD_ID,"pinnedIds",[]),Object(s.g)(t)}(c)}),Object(s.b)("deleteMessages",(e,t,a)=>{const{messageIds:s,shouldDeleteForAll:c}=a,n=Object(o.y)(e);if(!n)return;const{chatId:r,threadId:i}=n,l=Object(o.f)(e,r);Object(j.a)("deleteMessages",{chat:l,messageIds:s,shouldDeleteForAll:c});const d=Object(o.C)(e,r,i);s.includes(d)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteScheduledMessages",(e,t,a)=>{const{messageIds:s}=a,c=Object(o.y)(e);if(!c)return;const{chatId:n}=c,r=Object(o.f)(e,n);Object(j.a)("deleteScheduledMessages",{chat:r,messageIds:s});const i=Object(o.E)(e,n);s.includes(i)&&t.setEditingId({messageId:void 0})}),Object(s.b)("deleteHistory",(e,t,a)=>{(async()=>{const{chatId:s,shouldDeleteForAll:c}=a,n=Object(o.f)(e,s);if(!n)return;const r=n.lastMessage&&n.lastMessage.id;await Object(j.a)("deleteHistory",{chat:n,shouldDeleteForAll:c,maxId:r}),t.openChat({id:void 0})})()}),Object(s.b)("markMessageListRead",(e,t,a)=>{const s=Object(o.y)(e);if(!s)return;const{chatId:c,threadId:n}=s,r=Object(o.Db)(e,c,n);if(!r)return;const{maxId:i}=a;M(()=>{Object(j.a)("markMessageListRead",{chat:r,threadId:n,maxId:i})})}),Object(s.b)("markMessagesRead",(e,t,a)=>{const s=Object(o.r)(e);if(!s)return;const{messageIds:c}=a;Object(j.a)("markMessagesRead",{chat:s,messageIds:c})}),Object(s.b)("loadWebPagePreview",(e,t,a)=>{const{text:c}=a;!async function(e){const t=await Object(j.a)("fetchWebPagePreview",{message:e});Object(s.g)({...Object(s.e)(),webPagePreview:t})}(c)}),Object(s.b)("clearWebPagePreview",e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}}),Object(s.b)("sendPollVote",(e,t,a)=>{const{chatId:s,messageId:c,options:n}=a,r=Object(o.f)(e,s);r&&Object(j.a)("sendPollVote",{chat:r,messageId:c,options:n})}),Object(s.b)("loadPollOptionResults",(e,t,a)=>{const{chat:c,messageId:n,option:o,offset:i,limit:l,shouldResetVoters:b}=a;!async function(e,t,a,c,n,o){const i=await Object(j.a)("loadPollOptionResults",{chat:e,messageId:t,option:a,offset:c,limit:n});if(!i)return;let l=Object(s.e)();l=Object(r.f)(l,Object(d.c)(i.users,"id"));const{voters:b}=l.pollResults;Object(s.g)({...l,pollResults:{...l.pollResults,voters:{...b,[a]:[...!o&&b&&b[a]?b[a]:[],...i&&i.users.map(e=>e.id)].filter((e,t,a)=>a.indexOf(e)===t)},offsets:{...l.pollResults.offsets?l.pollResults.offsets:{},[a]:i.nextOffset||""}}})}(c,n,o,i,l,b)}),Object(s.b)("forwardMessages",e=>{const{fromChatId:t,messageIds:a,toChatId:c}=e.forwardMessages,n=t?Object(o.f)(e,t):void 0,r=c?Object(o.f)(e,c):void 0,i=t&&a?a.sort((e,t)=>e-t).map(a=>Object(o.k)(e,t,a)).filter(Boolean):void 0;n&&r&&i&&i.length&&function(e,t,a){Object(j.a)("forwardMessages",{fromChat:e,toChat:t,messages:a}),Object(s.g)({...Object(s.e)(),forwardMessages:{}})}(n,r,i)}),Object(s.b)("loadScheduledHistory",e=>{const t=Object(o.r)(e);if(!t)return;const{hash:a}=e.scheduledMessages.byChatId[t.id]||{};!async function(e,t){const a=await Object(j.a)("fetchScheduledHistory",{chat:e,hash:t});if(!a)return;const{hash:c,messages:n}=a,o=Object(d.c)(n,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.u)(b,e.id,o,c),b=Object(r.x)(b,e.id,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(b)}(t,a)}),Object(s.b)("sendScheduledMessages",(e,t,a)=>{const{chatId:s,id:c}=a,n=Object(o.f)(e,s);n&&Object(j.a)("sendScheduledMessages",{chat:n,ids:[c]})}),Object(s.b)("rescheduleMessage",(e,t,a)=>{const{chatId:s,messageId:c,scheduledAt:n}=a,r=Object(o.f)(e,s),i=r&&Object(o.pb)(e,r.id,c);r&&i&&Object(j.a)("rescheduleMessage",{chat:r,message:i,scheduledAt:n})}),Object(s.b)("requestThreadInfoUpdate",(e,t,a)=>{const{chatId:s,threadId:c}=a,n=Object(o.Db)(e,s,c);n&&Object(j.a)("requestThreadInfoUpdate",{chat:n,threadId:c})}),Object(s.b)("loadPinnedMessages",(e,t,a)=>{const{chatId:c}=a,n=Object(o.f)(e,c);n&&async function(e){const t=await Object(j.a)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:a,chats:c,users:n}=t,o=Object(d.c)(a,"id"),l=Object.keys(o).map(Number).sort((e,t)=>t-e);let b=Object(s.e)();b=Object(r.b)(b,e.id,o),b=Object(r.x)(b,e.id,i.MAIN_THREAD_ID,"pinnedIds",l),b=Object(r.f)(b,Object(d.c)(n,"id")),b=Object(r.c)(b,Object(d.c)(c,"id")),Object(s.g)(b)}(n)}),Object(s.b)("loadMessageLink",(e,t,a)=>{const{messageId:s,chatId:c}=a,n=Object(o.f)(e,c),r=Object(o.k)(e,c,s);n&&r&&(async()=>{const e=await Object(j.a)("fetchMessageLink",{chat:n,message:r});e&&Object(E.c)(e.link)})()});var P=a(52);const T=Object(g.g)(e=>e(),500,!1);async function A(e,t){const a=await Object(j.a)("searchGifs",{query:e,offset:t});a&&Object(s.g)(Object(r.Q)(Object(s.e)(),!t,a.gifs,a.nextOffset))}Object(s.b)("loadStickerSets",e=>{const{hash:t}=e.stickers.added||{};!async function(e=0){const t=await Object(j.a)("fetchStickerSets",{hash:e});if(!t)return;Object(s.g)(Object(r.ib)(Object(s.e)(),"added",t.hash,t.sets))}(t)}),Object(s.b)("loadAddedStickers",(e,t)=>{const{setIds:a}=e.stickers.added;a&&a.length&&(async()=>{for(let e=0;e0&&await Object(g.e)(500)})()}),Object(s.b)("loadRecentStickers",e=>{const{hash:t}=e.stickers.recent||{};!async function(e=0){const t=await Object(j.a)("fetchRecentStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,recent:t}})}(t)}),Object(s.b)("loadFavoriteStickers",e=>{const{hash:t}=e.stickers.favorite||{};!async function(e=0){const t=await Object(j.a)("fetchFavoriteStickers",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,favorite:t}})}(t)}),Object(s.b)("loadFeaturedStickers",e=>{const{hash:t}=e.stickers.featured||{};!async function(e=0){const t=await Object(j.a)("fetchFeaturedStickers",{hash:e});if(!t)return;Object(s.g)(Object(r.ib)(Object(s.e)(),"featured",t.hash,t.sets))}(t)}),Object(s.b)("loadStickers",(e,t,a)=>{const{stickerSetId:c}=a;let{stickerSetAccessHash:n}=a;if(!n){const t=Object(o.xb)(e,c);if(!t)return;n=t.accessHash}!async function(e,t){const a=await Object(j.a)("fetchStickers",{stickerSetId:e,accessHash:t});if(!a)return;const{set:c,stickers:n,packs:o}=a;let i=Object(s.e)();i=Object(r.hb)(i,c.id,{...c,stickers:n,packs:o});const l=i.stickers.forEmoji.emoji;l&&o[l]&&(i=Object(r.o)(i));Object(s.g)(i)}(c,n)}),Object(s.b)("loadAnimatedEmojis",()=>{!async function(){const e=await Object(j.a)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:a}=e;Object(s.g)(Object(r.q)(Object(s.e)(),{...t,stickers:a}))}()}),Object(s.b)("loadSavedGifs",e=>{const{hash:t}=e.gifs.saved;!async function(e=0){const t=await Object(j.a)("fetchSavedGifs",{hash:e});if(!t)return;const a=Object(s.e)();Object(s.g)({...a,gifs:{...a.gifs,saved:t}})}(t)}),Object(s.b)("faveSticker",(e,t,a)=>{const{sticker:s}=a;s&&Object(j.a)("faveSticker",{sticker:s})}),Object(s.b)("unfaveSticker",(e,t,a)=>{const{sticker:c}=a;c&&function(e){const t=Object(s.e)();Object(s.g)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter(({id:t})=>t!==e.id)}}}),Object(j.a)("faveSticker",{sticker:e,unfave:!0})}(c)}),Object(s.b)("toggleStickerSet",(e,t,a)=>{const{stickerSetId:s}=a,c=Object(o.xb)(e,s);if(!c)return;const{accessHash:n,installedDate:r}=c;Object(j.a)(r?"uninstallStickerSet":"installStickerSet",{stickerSetId:s,accessHash:n})}),Object(s.b)("loadEmojiKeywords",(e,t,a)=>{const{language:c}=a;let n=Object(o.F)(e,c);n&&n.isLoading||(Object(s.g)({...e,emojiKeywords:{...e.emojiKeywords,[c]:{...n,isLoading:!0}}}),(async()=>{const t=await Object(j.a)("fetchEmojiKeywords",{language:c,fromVersion:n?n.version:0});e=Object(s.e)(),n=Object(o.F)(e,c),t?Object(s.g)({...e,emojiKeywords:{...e.emojiKeywords,[c]:{isLoading:!1,version:t.version,keywords:{...n&&n.keywords,...t.keywords}}}}):Object(s.g)({...e,emojiKeywords:{...e.emojiKeywords,[c]:{...n,isLoading:!1}}})})())}),Object(s.b)("setStickerSearchQuery",(e,t,a)=>{const{query:c}=a;c&&T(()=>{!async function(e,t=0){const a=await Object(j.a)("searchStickers",{query:e,hash:t});if(!a)return;const c=Object(s.e)(),{setsById:n,added:o}=c.stickers,i=a.sets.map(({id:e})=>e);o.setIds&&o.setIds.forEach(t=>{if(!i.includes(t)){const{title:a}=n[t]||{};a&&Object(P.a)(a,e)&&i.unshift(t)}});Object(s.g)(Object(r.ib)(c,"search",a.hash,a.sets,i))}(c)})}),Object(s.b)("setGifSearchQuery",(e,t,a)=>{const{query:s}=a;"string"==typeof s&&T(()=>{A(s)})}),Object(s.b)("searchMoreGifs",e=>{const{query:t,offset:a}=e.gifs.search;"string"==typeof t&&T(()=>{A(t,a)})}),Object(s.b)("loadStickersForEmoji",(e,t,a)=>{const{emoji:c}=a,{hash:n}=e.stickers.forEmoji;T(()=>{!async function(e,t=0){let a=Object(s.e)();Object(s.g)({...a,stickers:{...a.stickers,forEmoji:{...a.stickers.forEmoji,emoji:e}}});const c=await Object(j.a)("fetchStickersForEmoji",{emoji:e,hash:t});if(a=Object(s.e)(),!c||a.stickers.forEmoji.emoji!==e)return;a=Object(r.jb)(a,e,c.stickers,c.hash),Object(s.g)(a)}(c,n)})}),Object(s.b)("clearStickersForEmoji",e=>({...e,stickers:{...e.stickers,forEmoji:{}}}));var x=a(36);const R=Object(g.g)(e=>e(),500,!1);async function L(e="",t,a,n,i,l){let b;if(n){const s=await Object(j.a)("searchMessagesLocal",{chatOrUser:n,query:e,type:t,limit:c.y,offsetId:a,minDate:l,maxDate:i});if(s){const{messages:e,users:t,totalCount:a,nextOffsetId:c}=s;b={messages:e,users:t,chats:[],totalCount:a,nextRate:c}}}else b=await Object(j.a)("searchMessagesGlobal",{query:e,offsetRate:a,limit:c.y,type:t,maxDate:i,minDate:l});let u=Object(s.e)();const m=Object(o.t)(u);if(!b||""!==e&&e!==m)return void Object(s.g)(Object(r.T)(u,{messages:!1}));const{messages:h,users:O,chats:g,totalCount:f,nextRate:p}=b;g.length&&(u=Object(r.c)(u,Object(d.c)(g,"id"))),O.length&&(u=Object(r.f)(u,Object(d.c)(O,"id"))),h.length&&(u=Object(r.d)(u,h)),u=Object(r.U)(u,h,f,t,p),Object(s.g)(u)}async function F(){const e=await Object(j.a)("fetchChats",{limit:c.j,archived:!0,withPinned:!0});if(!e)return;let t=Object(s.e)();t=Object(r.ob)(t,Object(d.c)(e.users,"id")),t=Object(r.M)(t,Object(d.c)(e.chats,"id")),t=Object(r.r)(t,"archived",e.chatIds),t=Object(r.J)(t,"archived",e),Object(s.g)(t)}async function D(){let e=Object(s.e)();const{recentlyFoundChatIds:t}=e.globalSearch,{userIds:a}=e.contactList||{};if(!(a&&a.length||t&&t.length))return;const c=[...t||[],...a||[]].map(t=>Object(o.Gb)(e,t)).filter(Boolean),n=await Object(j.a)("fetchUsers",{users:c});n&&(e=Object(s.e)(),e=Object(r.ob)(e,Object(d.c)(n,"id")),Object(s.g)(e))}Object(s.b)("setGlobalSearchQuery",(e,t,a)=>{const{chatId:c}=e.globalSearch,{query:n}=a;n&&!c&&R(()=>{!async function(e){const t=await Object(j.a)("searchChats",{query:e});let a=Object(s.e)();const c=Object(o.t)(a);if(!t||!c||e!==c)return void Object(s.g)(Object(r.T)(a,{chats:!1}));const{localChats:n,localUsers:i,globalChats:l,globalUsers:b}=t;(n.length||l.length)&&(a=Object(r.c)(a,Object(d.c)([...n,...l],"id")));(i.length||b.length)&&(a=Object(r.f)(a,Object(d.c)([...i,...b],"id")));a=Object(r.T)(a,{chats:!1}),a=Object(r.R)(a,{localResults:{chatIds:n.map(({id:e})=>e),userIds:i.map(({id:e})=>e)},globalResults:{...a.globalSearch.globalResults,chatIds:b.map(({id:e})=>e),userIds:l.map(({id:e})=>e)}}),Object(s.g)(a)}(n)})}),Object(s.b)("setGlobalSearchDate",(e,t,a)=>{const{date:c}=a,n=c?Object(x.m)(c):c,i=Object(r.R)(e,{date:c,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}});Object(s.g)(i);const{chatId:l}=e.globalSearch;L("","text",void 0,l?Object(o.f)(e,l):void 0,n,c)}),Object(s.b)("searchMessagesGlobal",(e,t,a)=>{const{query:s,resultsByType:c,chatId:n,date:r}=e.globalSearch,i=r?Object(x.m)(r):r,{type:l}=a,{nextOffsetId:d}=c&&c[l]||{};L(s,l,d,n?Object(o.f)(e,n):void 0,i,r)}),Object(s.b)("searchTextMessagesLocal",e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},n=t?Object(o.f)(e,t):void 0,l=Object(o.A)(e);if(!n||!l||!a)return;const{query:b,results:u}=l,m=u?u.nextOffsetId:void 0;let h;if(a!==i.MAIN_THREAD_ID){const s=Object(o.Cb)(e,t,a);h=s?s.topMessageId:void 0}!async function(e,t,a,n,i){const l=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:"text",query:n,topMessageId:a,limit:c.X,offsetId:i});if(!l)return;const{messages:b,users:u,totalCount:m,nextOffsetId:h}=l,O=Object(d.c)(b,"id"),g=Object.keys(O).map(Number);let f=Object(s.e)();const p=Object(o.A)(f);if(!p||n&&n!==p.query)return;f=Object(r.b)(f,e.id,O),f=Object(r.f)(f,Object(d.c)(u,"id")),f=Object(r.Z)(f,e.id,t,g,m,h),Object(s.g)(f)}(n,a,h,b,m)}),Object(s.b)("searchMediaMessagesLocal",e=>{const t=Object(o.w)(e),a=t?e.users.byId[t]||e.chats.byId[t]:void 0,n=Object(o.v)(e);if(!a||!n)return;const{currentType:i,resultsByType:l}=n,b=i&&l&&l[i],u=b?b.nextOffsetId:void 0;i&&async function(e,t,a){const n=await Object(j.a)("searchMessagesLocal",{chatOrUser:e,type:t,limit:c.ob,offsetId:a});if(!n)return;const{messages:i,users:l,totalCount:b,nextOffsetId:u}=n,m=Object(d.c)(i,"id"),h=Object.keys(m).map(Number);let O=Object(s.e)();if(!Object(o.v)(O))return;O=Object(r.b)(O,e.id,m),O=Object(r.f)(O,Object(d.c)(l,"id")),O=Object(r.W)(O,e.id,t,h,b,u),Object(s.g)(O)}(a,i,u)}),Object(s.b)("searchMessagesByDate",(e,t,a)=>{const{timestamp:c}=a,{chatId:n}=Object(o.y)(e)||{};if(!n)return;const r=Object(o.f)(e,n);r&&async function(e,t){const a=await Object(j.a)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});if(!a)return;Object(s.d)().focusMessage({chatId:e.id,messageId:a})}(r,c)}),Object(s.b)("checkPublicLink",(e,t,a)=>{const{chatId:c}=Object(o.y)(e)||{};if(!c)return;if(e.management.progress===l.f.InProgress)return;const{username:n}=a;(async()=>{e=Object(r.bb)(e,l.f.InProgress),e=Object(r.ab)(e,c,{isUsernameAvailable:void 0}),Object(s.g)(e);const t=await Object(j.a)("checkChatUsername",{username:n});e=Object(s.e)(),e=Object(r.bb)(e,t?l.f.Complete:l.f.Error),e=Object(r.ab)(e,c,{isUsernameAvailable:t}),Object(s.g)(e)})()}),Object(s.b)("updatePublicLink",(e,t,a)=>{const{chatId:c}=Object(o.y)(e)||{};let n=c&&Object(o.f)(e,c);if(!c||!n)return;const{username:i}=a;(async()=>{if(e=Object(r.bb)(e,l.f.InProgress),Object(s.g)(e),Object(m.ib)(n)){if(n=await Object(j.a)("migrateChat",n),!n)return;t.openChat({id:n.id})}const a=await Object(j.a)("setChatUsername",{chat:n,username:i});e=Object(s.e)(),e=Object(r.bb)(e,a?l.f.Complete:l.f.Error),e=Object(r.ab)(e,c,{isUsernameAvailable:void 0}),Object(s.g)(e)})()}),Object(s.b)("updatePrivateLink",e=>{const{chatId:t}=Object(o.y)(e)||{},a=t&&Object(o.f)(e,t);t&&a&&Object(j.a)("updatePrivateLink",{chat:a})}),Object(s.b)("sync",(e,t)=>{!async function(e){c.p&&console.log(">>> START SYNC");await Object(j.a)("fetchCurrentUser");const t=await async function(){const e=await Object(j.a)("fetchChats",{limit:c.j,withPinned:!0});if(!e)return;let t=Object(s.e)();const{recentlyFoundChatIds:a}=t.globalSearch,{userIds:n}=t.contactList||{},{currentUserId:l}=t,b=[...a||[],...n||[],...l?[l]:[]],u=b.map(e=>Object(o.Gb)(t,e)).filter(Boolean),h=b.map(e=>Object(o.f)(t,e)).filter(Boolean),{chatId:O}=Object(o.y)(t)||{};if(O){const e=Object(o.f)(t,O);if(e&&!b.includes(O)&&h.push(e),Object(m.lb)(O)){const e=Object(o.Gb)(t,O);e&&!b.includes(O)&&u.push(e)}}u.push(...e.users),h.push(...e.chats),t=Object(r.s)(t,Object(d.c)(h,"id")),t=Object(r.r)(t,"active",e.chatIds),t={...t,chats:{...t.chats}},t=Object(r.J)(t,"active",e),Object.keys(e.draftsById).map(Number).forEach(a=>{t=Object(r.x)(t,a,i.MAIN_THREAD_ID,"draft",e.draftsById[a])}),Object.keys(e.replyingToById).map(Number).forEach(a=>{t=Object(r.x)(t,a,i.MAIN_THREAD_ID,"replyingToId",e.replyingToById[a])}),Object(s.g)(t),O&&!t.chats.byId[O]&&Object(s.d)().openChat({id:void 0});return u}();await async function(e){let t=!1,a=e||[],n=Object(s.e)();const{chatId:l}=Object(o.y)(n)||{},b=Object.keys(n.messages.byChatId).map(Number).reduce((e,t)=>{const a=Object(o.B)(n,t,i.MAIN_THREAD_ID);return a?{...e,[t]:a}:e},{});if(l){const e=await(u=n.chats.byId[l],Object(j.a)("fetchMessages",{chat:u,threadId:i.MAIN_THREAD_ID,offsetId:u.lastReadInboxMessageId,addOffset:-(Math.round(c.V/2)+1),limit:c.V}));n=Object(s.e)();const{chatId:b}=Object(o.y)(n)||{};if(e&&b===l){const s=n.messages.byChatId[l],c=Object(d.c)(e.messages,"id"),o=Object.keys(c).map(Number);n={...n,messages:{...n.messages,byChatId:{[l]:{byId:c,threadsById:{[i.MAIN_THREAD_ID]:{...s&&s.threadsById[i.MAIN_THREAD_ID],listedIds:o,viewportIds:o,outlyingIds:void 0}}}}}},n=Object(r.M)(n,Object(d.c)(e.chats,"id")),n=Object(r.lb)(n,l,e.threadInfos),t=!0,a=Array.prototype.concat(a,e.users)}}var u;t||(n={...n,messages:{...n.messages,byChatId:{}}});Object.keys(b).map(Number).forEach(e=>{n=Object(r.x)(n,e,i.MAIN_THREAD_ID,"draft",b[e])}),e?n=Object(r.y)(n,Object(d.c)(a,"id")):a&&(n=Object(r.ob)(n,Object(d.c)(a,"id")));Object(s.g)(n);const{chatId:m,messageId:h}=n.audioPlayer;m&&h&&!Object(o.k)(n,m,h)&&Object(s.d)().closeAudioPlayer()}(t),Object(s.g)({...Object(s.e)(),lastSyncTime:Date.now()}),c.p&&console.log(">>> FINISH SYNC");e()}(t.afterSync)}),Object(s.b)("afterSync",(e,t)=>{!async function(e){c.p&&console.log(">>> START AFTER-SYNC");e.loadFavoriteStickers(),await Promise.all([D(),F()]),await Object(j.a)("fetchCurrentUser"),c.p&&console.log(">>> FINISH AFTER-SYNC")}(t)});const B=Object(g.a)(e=>e(),500,!1,!0);function U(e,{visibility:t,allowedIds:a,deniedIds:s}){const{users:{byId:c},chats:{byId:n}}=e,r={visibility:t};let o,i;const l=e=>{if(!Object(m.lb)(e))return;const{id:t,accessHash:a}=c[e]||{};return t?{id:t,accessHash:a}:void 0},d=e=>{if(Object(m.lb)(e))return;const t=n[e];return t?{id:t.id}:void 0};return"contacts"!==t&&"nobody"!==t||(o=a.map(l).filter(Boolean),i=a.map(d).filter(Boolean),o.length>0&&(r.allowedUsers=o),i.length>0&&(r.allowedChats=i)),"everybody"!==t&&"contacts"!==t||(o=s.map(l).filter(Boolean),i=s.map(d).filter(Boolean),o.length>0&&(r.blockedUsers=o),i.length>0&&(r.blockedChats=i)),r}Object(s.b)("loadFullUser",(e,t,a)=>{const{userId:s}=a,c=Object(o.Gb)(e,s);if(!c)return;const{id:n,accessHash:r}=c;B(()=>Object(j.a)("fetchFullUser",{id:n,accessHash:r}))}),Object(s.b)("loadUser",(e,t,a)=>{const{userId:c}=a,n=Object(o.Gb)(e,c);n&&(async()=>{const t=await Object(j.a)("fetchUsers",{users:[n]});t&&(e=Object(s.e)(),e=Object(r.ob)(e,Object(d.c)(t,"id")),Object(s.g)(e))})()}),Object(s.b)("loadTopUsers",e=>{const{hash:t,lastRequestedAt:a}=e.topPeers;(!a||Date.now()-a>6e4)&&async function(e){const t=await Object(j.a)("fetchTopUsers",{hash:e});if(!t)return;const{hash:a,ids:c,users:n}=t;let o=Object(s.e)();o=Object(r.f)(o,Object(d.c)(n,"id")),o={...o,topPeers:{...o.topPeers,hash:a,userIds:c,lastRequestedAt:Date.now()}},Object(s.g)(o)}(t)}),Object(s.b)("loadContactList",e=>{const{hash:t}=e.contactList||{};!async function(e){const t=await Object(j.a)("fetchContactList",{hash:e});if(!t)return;let a=Object(r.f)(Object(s.e)(),Object(d.c)(t.users,"id"));a=Object(r.c)(a,Object(d.c)(t.chats,"id"));const c=e=>e.lastName||e.firstName||"",n=new Intl.Collator("en-US"),o=t.users.sort((e,t)=>n.compare(c(e),c(t))).filter(e=>!e.isSelf);Object(s.g)({...a,contactList:{hash:t.hash,userIds:o.map(e=>e.id)}})}(t)}),Object(s.b)("loadCurrentUser",()=>{Object(j.a)("fetchCurrentUser")}),Object(s.b)("updateContact",(e,t,a)=>{const{userId:c,isMuted:n,firstName:i,lastName:d}=a;!async function(e,t,a,c){const n=Object(s.e)(),i=Object(o.Gb)(n,e);if(!i)return;Object(s.d)().updateChatMutedState({chatId:e,isMuted:t}),Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.InProgress));await Object(j.a)("updateContact",{phone:i.phoneNumber,firstName:a,lastName:c})&&Object(s.g)(Object(r.nb)(Object(s.e)(),i.id,{firstName:a,lastName:c}));Object(s.g)(Object(r.bb)(Object(s.e)(),l.f.Complete))}(c,n,i,d)}),Object(s.b)("deleteUser",(e,t,a)=>{const{userId:c}=a;!async function(e){const t=Object(s.e)(),a=Object(o.Gb)(t,e);if(!a)return;const{id:c,accessHash:n}=a;await Object(j.a)("deleteUser",{id:c,accessHash:n})}(c)}),Object(s.b)("loadProfilePhotos",(e,t,a)=>{const{profileId:c}=a,n=Object(m.lb)(c),i=n?Object(o.Gb)(e,c):void 0,l=n?void 0:Object(o.f)(e,c);(async()=>{const e=await Object(j.a)("fetchProfilePhotos",i,l);if(!e||!e.photos)return;let t=Object(s.e)();n?t=Object(r.nb)(t,c,{photos:e.photos}):(t=Object(r.f)(t,Object(d.c)(e.users,"id")),t=Object(r.H)(t,c,{photos:e.photos})),Object(s.g)(t)})()}),Object(s.b)("clickInlineButton",(e,t,a)=>{const{button:n}=a;switch(n.type){case"command":t.sendBotCommand({command:n.value});break;case"url":n.value.match(c.hb)||n.value.match(c.ib)?t.openTelegramLink({url:n.value}):t.toggleSafeLinkModal({url:n.value});break;case"callback":{const t=Object(o.r)(e);if(!t)return;!async function(e,t,a){const c=await Object(j.a)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:a});if(!c||!c.message)return;const{message:n,alert:r}=c;r?Object(s.d)().showError({error:{message:n}}):Object(s.d)().showNotification({message:n})}(t,n.messageId,n.value);break}case"requestPoll":t.openPollModal();break;case"buy":{const a=Object(o.r)(e),{messageId:s,value:c}=n;if(!a)return;c?t.getReceipt({receiptMessageId:c,chatId:a.id,messageId:s}):(t.getPaymentForm({messageId:s}),t.setInvoiceMessageInfo(Object(o.k)(e,a.id,s)),t.openPaymentModal({messageId:s}));break}}}),Object(s.b)("sendBotCommand",(e,t,a)=>{const{command:s}=a,{currentUserId:c}=e,n=Object(o.r)(e);c&&n&&async function(e,t,a){await Object(j.a)("sendMessage",{chat:e,text:a})}(n,0,s)}),Object(s.b)("updateProfile",(e,t,a)=>{const{photo:c,firstName:n,lastName:i,bio:d,username:b}=a;(async()=>{const{currentUserId:t}=e;if(t){if(Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.InProgress}}),c&&await Object(j.a)("updateProfilePhoto",c),n||i||d){if(await Object(j.a)("updateProfile",{firstName:n,lastName:i,about:d})){e=Object(s.e)();const a=t&&Object(o.Gb)(e,t);a&&Object(s.g)(Object(r.nb)(e,a.id,{firstName:n,lastName:i,fullInfo:{...a.fullInfo,bio:d}}))}}if(b){await Object(j.a)("updateUsername",b)&&t&&Object(s.g)(Object(r.nb)(Object(s.e)(),t,{username:b}))}Object(s.g)({...Object(s.e)(),profileEdit:{progress:l.j.Complete}})}})()}),Object(s.b)("checkUsername",(e,t,a)=>{const{username:c}=a;(async()=>{if(e.profileEdit&&e.profileEdit.progress===l.j.InProgress)return;Object(s.g)({...e,profileEdit:{progress:e.profileEdit?e.profileEdit.progress:l.j.Idle,isUsernameAvailable:void 0}});const t=await Object(j.a)("checkUsername",c);e=Object(s.e)(),Object(s.g)({...e,profileEdit:{...e.profileEdit,isUsernameAvailable:t}})})()}),Object(s.b)("loadWallpapers",()=>{(async()=>{const e=await Object(j.a)("fetchWallpapers",0);if(!e)return;const t=Object(s.e)();Object(s.g)({...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}})})()}),Object(s.b)("uploadWallpaper",(e,t,a)=>{const c=a,n=URL.createObjectURL(c);Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[{slug:l.n,document:{fileName:"",size:c.size,mimeType:c.type,previewBlobUrl:n}},...e.settings.loadedWallpapers||[]]}}),(async()=>{const t=await Object(j.a)("uploadWallpaper",c);if(!t)return;const{wallpaper:a}=t;if(!(e=Object(s.e)()).settings.loadedWallpapers)return;const r=e.settings.loadedWallpapers[0];if(!r||r.slug!==l.n)return;const o={...a,document:{...a.document,previewBlobUrl:n}};Object(s.g)({...e,settings:{...e.settings,loadedWallpapers:[o,...e.settings.loadedWallpapers.slice(1)]}})})()}),Object(s.b)("loadBlockedContacts",()=>{(async()=>{const e=await Object(j.a)("fetchBlockedContacts");if(!e)return;let t=Object(s.e)();e.users&&e.users.length&&(t=Object(r.f)(t,Object(d.c)(e.users,"id"))),e.chats&&e.chats.length&&(t=Object(r.M)(t,Object(d.c)(e.chats,"id"))),t={...t,blocked:{...t.blocked,ids:[...t.blocked.ids||[],...e.blockedIds],totalCount:e.totalCount}},Object(s.g)(t)})()}),Object(s.b)("blockContact",(e,t,a)=>{const{contactId:c}=a;(async()=>{if(!await Object(j.a)("blockContact",c))return;const e=Object(s.e)();Object(s.g)(Object(r.a)(e,c))})()}),Object(s.b)("unblockContact",(e,t,a)=>{const{contactId:c}=a;let n;if(Object(m.lb)(c)){const t=Object(o.Gb)(e,c);if(!t)return;n=t.accessHash}(async()=>{if(!await Object(j.a)("unblockContact",c,n))return;const e=Object(s.e)();Object(s.g)(Object(r.p)(e,c))})()}),Object(s.b)("loadAuthorizations",()=>{(async()=>{const e=await Object(j.a)("fetchAuthorizations");e&&Object(s.g)({...Object(s.e)(),activeSessions:e})})()}),Object(s.b)("terminateAuthorization",(e,t,a)=>{const{hash:c}=a;(async()=>{if(!await Object(j.a)("terminateAuthorization",c))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.hash!==c)})})()}),Object(s.b)("terminateAllAuthorizations",()=>{(async()=>{if(!await Object(j.a)("terminateAllAuthorizations"))return;const e=Object(s.e)();Object(s.g)({...e,activeSessions:e.activeSessions.filter(e=>e.isCurrent)})})()}),Object(s.b)("loadNotificationExceptions",()=>{Object(j.a)("fetchNotificationExceptions")}),Object(s.b)("loadNotificationSettings",()=>{(async()=>{const e=await Object(j.a)("fetchNotificationSettings");e&&Object(s.g)(Object(r.v)(Object(s.e)(),e))})()}),Object(s.b)("updateNotificationSettings",(e,t,a)=>{const{peerType:c,isSilent:n,shouldShowPreviews:o}=a;(async()=>{await Object(j.a)("updateNotificationSettings",c,{isSilent:n,shouldShowPreviews:o})&&Object(s.g)(Object(r.cb)(Object(s.e)(),c,n,o))})()}),Object(s.b)("updateContactSignUpNotification",(e,t,a)=>{const{isSilent:c}=a;(async()=>{await Object(j.a)("updateContactSignUpNotification",c)&&Object(s.g)(Object(r.v)(Object(s.e)(),{hasContactJoinedNotifications:!c}))})()}),Object(s.b)("loadLanguages",()=>{(async()=>{const e=await Object(j.a)("fetchLanguages");e&&Object(s.g)(Object(r.v)(Object(s.e)(),{languages:e}))})()}),Object(s.b)("loadPrivacySettings",()=>{(async()=>{const[e,t,a,c,n]=await Promise.all([Object(j.a)("fetchPrivacySettings","phoneNumber"),Object(j.a)("fetchPrivacySettings","lastSeen"),Object(j.a)("fetchPrivacySettings","profilePhoto"),Object(j.a)("fetchPrivacySettings","forwards"),Object(j.a)("fetchPrivacySettings","chatInvite")]);if(!(e&&t&&a&&c&&n))return;const r=Object(s.e)();r.settings.privacy.phoneNumber=e,r.settings.privacy.lastSeen=t,r.settings.privacy.profilePhoto=a,r.settings.privacy.forwards=c,r.settings.privacy.chatInvite=n,Object(s.g)(r)})()}),Object(s.b)("setPrivacyVisibility",(e,t,a)=>{const{privacyKey:c,visibility:n}=a,{privacy:{[c]:r}}=e.settings;if(!r)return;const o=U(e,{visibility:n,allowedIds:[...r.allowUserIds,...r.allowChatIds],deniedIds:[...r.blockUserIds,...r.blockChatIds]});(async()=>{const e=await Object(j.a)("setPrivacySettings",c,o);if(e){const t=Object(s.e)();t.settings.privacy[c]=e,Object(s.g)(t)}})()}),Object(s.b)("setPrivacySettings",(e,t,a)=>{const{privacyKey:c,isAllowList:n,contactsIds:r}=a,{privacy:{[c]:o}}=e.settings;if(!o)return;const i=U(e,{visibility:o.visibility,allowedIds:n?r:[...o.allowUserIds,...o.allowChatIds],deniedIds:n?[...o.blockUserIds,...o.blockChatIds]:r});(async()=>{const e=await Object(j.a)("setPrivacySettings",c,i);if(e){const t=Object(s.e)();t.settings.privacy[c]=e,Object(s.g)(t)}})()}),Object(s.b)("loadPasswordInfo",()=>{(async()=>{const e=await Object(j.a)("getPasswordInfo");if(!e)return;let t=Object(s.e)();t=Object(r.v)(t,{hasPassword:e.hasPassword}),t=Object(r.mb)(t,{hint:e.hint}),Object(s.g)(t)})()}),Object(s.b)("checkPassword",(e,t,a)=>{const{currentPassword:c,onSuccess:n}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("checkPassword",c);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1})),e&&n()})()}),Object(s.b)("clearPassword",(e,t,a)=>{const{currentPassword:c,onSuccess:n}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("clearPassword",c);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1})),e&&n()})()}),Object(s.b)("updatePassword",(e,t,a)=>{const{currentPassword:c,password:n,hint:o,email:i,onSuccess:l}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updatePassword",c,n,o,i);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1})),e&&l()})()}),Object(s.b)("updateRecoveryEmail",(e,t,a)=>{const{currentPassword:c,email:n,onSuccess:o}=a;Object(s.g)(Object(r.mb)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await Object(j.a)("updateRecoveryEmail",c,n);Object(s.g)(Object(r.mb)(Object(s.e)(),{isLoading:!1,waitingEmailCodeLength:void 0})),e&&o()})()}),Object(s.b)("provideTwoFaEmailCode",(e,t,a)=>{const{code:s}=a;Object(j.a)("provideRecoveryEmailCode",s)}),Object(s.b)("clearTwoFaError",e=>Object(r.mb)(e,{error:void 0}));var H=a(60);Object(s.b)("validateRequestedInfo",(e,t,a)=>{const{requestInfo:c,saveInfo:n}=a,i=Object(o.hb)(e);i&&async function(e,t,a){const c=await Object(j.a)("validateRequestedInfo",{messageId:e,requestInfo:t,shouldSave:a});if(!c)return;const{id:n,shippingOptions:o}=c;if(!n)return;let i=Object(r.E)(Object(s.e)(),n);o?(i=Object(r.gb)(i,o),i=Object(r.C)(i,l.i.Shipping)):i=Object(r.C)(i,l.i.PaymentInfo);Object(s.g)(i)}(i,c,n)}),Object(s.b)("getPaymentForm",(e,t,a)=>{const{messageId:c}=a;c&&async function(e){const t=await Object(j.a)("getPaymentForm",{messageId:e});if(!t)return;let a=Object(r.B)(Object(s.e)(),t),c=l.i.PaymentInfo;a.payment.invoice&&(a.payment.invoice.shippingAddressRequested||a.payment.invoice.nameRequested||a.payment.invoice.phoneRequested||a.payment.invoice.emailRequested)&&(c=l.i.ShippingInfo);a=Object(r.C)(a,c),Object(s.g)(a)}(c)}),Object(s.b)("getReceipt",(e,t,a)=>{const{receiptMessageId:c,chatId:n,messageId:i}=a;i&&c&&n&&async function(e,t,a){const c=await Object(j.a)("getReceipt",t);if(!c)return;let n=Object(s.e)();const i=Object(o.k)(n,a,e);n=Object(r.D)(n,c,i),Object(s.g)(n)}(i,c,n)}),Object(s.b)("clearPaymentError",e=>{Object(s.g)({...e,payment:{...e.payment,error:void 0}})}),Object(s.b)("clearReceipt",e=>{Object(s.g)({...e,payment:{...e.payment,receipt:void 0}})}),Object(s.b)("sendCredentialsInfo",(e,t,a)=>{const c=Object(o.kb)(e);if(!c)return;const{credentials:n}=a,{data:i}=n;!async function(e,t){const a=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}),c=await fetch("https://api.stripe.com/v1/tokens"+a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:"Bearer "+t}}),n=await c.json();if(n.error){const e=Object(H.b)(n.error),t=Object(s.e)();return void Object(s.g)({...t,payment:{...t.payment,error:{...e}}})}let o=Object(r.F)(Object(s.e)(),{type:n.type,id:n.id});o=Object(r.C)(o,l.i.Checkout),Object(s.g)(o)}(i,c)}),Object(s.b)("sendPaymentForm",(e,t,a)=>{const{shippingOptionId:c,saveCredentials:n}=a,i=Object(o.hb)(e),l=Object(o.ib)(e),d=Object(o.kb)(e),b=Object(o.zb)(e);i&&d&&async function(e,t,a,c){if(await Object(j.a)("sendPaymentForm",{messageId:e,credentials:t,requestedInfoId:a,shippingOptionId:c})){const e=Object(r.h)(Object(s.e)());Object(s.g)(Object(r.i)(e))}}(i,{save:n,data:b},l,c)}),Object(s.b)("setPaymentStep",(e,t,a={})=>Object(r.C)(e,a.step||l.i.ShippingInfo)),Object(s.b)("setInvoiceMessageInfo",(e,t,a)=>Object(r.A)(e,a));a(87);var G=a(29),q=a(78);const _=Object(g.g)(e=>e(),1e3,!0);Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateChat":{a.noTopChatsRequest||Object(o.M)(e,a.id)||t.loadTopChats();const c=Object(r.H)(e,a.id,a.chat,a.newProfilePhoto);Object(s.g)(c);const n=Object(o.q)(c);_(()=>Object(q.a)(n));break}case"updateChatJoin":{const c=Object(o.j)(e,a.id);if(!c)break;e=Object(r.I)(e,c,[a.id]),e=Object(r.H)(e,a.id,{isNotJoined:!1}),Object(s.g)(e);const n=Object(o.f)(e,a.id);n&&t.requestChatUpdate({chatId:n.id});break}case"updateChatLeave":{const t=Object(o.j)(e,a.id);if(!t)break;const{[t]:c}=e.chats.listIds;c&&(e=Object(r.r)(e,t,c.filter(e=>e!==a.id))),e=Object(r.H)(e,a.id,{isNotJoined:!0}),Object(s.g)(e);break}case"updateChatInbox":Object(s.g)(Object(r.H)(e,a.id,a.chat));break;case"updateChatTypingStatus":{const{id:t,typingStatus:c}=a;Object(s.g)(Object(r.H)(e,t,{typingStatus:c})),setTimeout(()=>{const e=Object(s.e)(),a=Object(o.f)(e,t);a&&c&&a.typingStatus&&a.typingStatus.timestamp===c.timestamp&&Object(s.g)(Object(r.H)(e,t,{typingStatus:void 0}))},6e3);break}case"newMessage":{const{message:c}=a,{chatId:n,threadId:l,type:d}=Object(o.y)(e)||{};if(c.senderId===e.currentUserId&&!c.isFromScheduled)return;const b=Object(o.f)(e,a.chatId);if(!b)return;const u="thread"===d&&l===i.MAIN_THREAD_ID&&a.chatId===n;u?setTimeout(()=>{t.requestChatUpdate({chatId:a.chatId})},1e3):Object(s.g)(Object(r.H)(e,a.chatId,{unreadCount:b.unreadCount?b.unreadCount+1:1,...a.message.hasUnreadMention&&{unreadMentionsCount:b.unreadMentionsCount?b.unreadMentionsCount+1:1}}));const m=Object(o.q)(Object(s.e)());Object(q.a)(m),Object(G.b)({chat:b,message:c,isActiveChat:u});break}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:c}=a;if(!1!==c.hasUnreadMention)return;t.forEach(t=>{const s="channelId"in a?a.channelId:Object(o.p)(e,t),c=Object(o.f)(e,s);c&&c.unreadMentionsCount&&(e=Object(r.H)(e,s,{unreadMentionsCount:c.unreadMentionsCount-1}))}),Object(s.g)(e);break}case"updateChatFullInfo":{const{fullInfo:t}=a,c=e.chats.byId[a.id];if(!c)return;Object(s.g)(Object(r.H)(e,a.id,{fullInfo:{...c.fullInfo,...t}}));break}case"updatePinnedChatIds":{const{ids:t,folderId:n}=a,r=n===c.h?"archived":"active";e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:t.length?t:void 0}}},Object(s.g)(e);break}case"updateChatPinned":{const{id:t,isPinned:n}=a,r=Object(o.j)(e,t);if(r){const{[r]:a}=e.chats.orderedPinnedIds;let s=a||[];if(n){if(!s.includes(t)){if("active"===r&&s.length>=c.K){const t=e.chats.listIds.active;s=s.filter(e=>t&&t.includes(e))}s=[t,...s]}}else s=s.filter(e=>e!==t);e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:s.length?s:void 0}}}}Object(s.g)(e);break}case"updateChatListType":{const{id:t,folderId:c}=a;Object(s.g)(Object(r.K)(e,t,c));break}case"updateChatFolder":{const{id:t,folder:c}=a,{byId:n,orderedIds:r}=e.chatFolders,o=c?{...n,[t]:c}:Object(d.l)(n,Object.keys(n).map(Number).filter(e=>e!==t)),i=c?r&&r.includes(t)?r:[...r||[],t]:r?r.filter(e=>e!==t):void 0;Object(s.g)({...e,chatFolders:{...e.chatFolders,byId:o,orderedIds:i}});break}case"updateChatFoldersOrder":{const{orderedIds:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,orderedIds:t}});break}case"updateRecommendedChatFolders":{const{folders:t}=a;Object(s.g)({...e,chatFolders:{...e.chatFolders,recommended:t}});break}case"updateChatMembers":{const t=e.chats.byId[a.id],{replacedMembers:c,addedMember:n,deletedMemberId:o}=a;if(!t)return;let i=!1,l=t.fullInfo&&t.fullInfo.members?[...t.fullInfo.members]:[];if(c)l=c,i=!0;else if(n)l.length&&l.some(e=>e.userId===n.userId)||(l.push(n),i=!0);else if(l.length&&o){const e=l.findIndex(e=>e.userId===o);e>-1&&(l.slice(e,1),i=!0)}if(i){const c=l.filter(({isOwner:e,isAdmin:t})=>e||t);Object(s.g)(Object(r.H)(e,a.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:c}}))}break}case"deleteProfilePhotos":{const{chatId:t,ids:c}=a,n=e.chats.byId[t];n&&n.photos&&Object(s.g)(Object(r.H)(e,t,{photos:n.photos.filter(e=>!c.includes(e.id))}));break}}});function V(e,t,a,s,c=!1){const n=c?Object(o.pb)(e,t,a):Object(o.k)(e,t,a);if(n&&s.content){const{photo:e,video:t,sticker:a,document:c}=Object(m.v)(n);e&&s.content.photo?(s.content.photo.blobUrl=e.blobUrl,s.content.photo.thumbnail=e.thumbnail):t&&s.content.video?s.content.video.blobUrl=t.blobUrl:a&&s.content.sticker?s.content.sticker.isPreloadedGlobally=a.isPreloadedGlobally:c&&s.content.document&&(s.content.document.previewBlobUrl=c.previewBlobUrl)}return c?Object(r.eb)(e,t,a,s):Object(r.L)(e,t,a,s)}function $(e,t){const{id:a,chatId:s}=t;if(e=Object(r.V)(e,s,i.MAIN_THREAD_ID,[a]),Object(o.X)(e,s,i.MAIN_THREAD_ID)){const t=Object(o.H)(e,s,i.MAIN_THREAD_ID),c=Object(r.g)(e,s,i.MAIN_THREAD_ID,a),n=Object(o.Hb)(c,s,i.MAIN_THREAD_ID);t&&!n.includes(t)||(e=c)}const{threadInfo:c,firstMessageId:n}=Object(o.Bb)(e,s,t)||{};return!n&&Object(m.sb)(t)||c&&(e=Object(r.V)(e,s,c.threadId,[a]),Object(o.X)(e,s,c.threadId)&&(e=Object(r.g)(e,s,c.threadId,a),n||(e=Object(r.x)(e,s,c.threadId,"firstMessageId",t.id)),c.lastMessageId||(e=Object(r.x)(e,s,c.threadId,"threadInfo",{...c,lastMessageId:t.id})))),e}function z(e,t,a,s=!1){const{chats:c}=e,n=c.byId[t]&&c.byId[t].lastMessage;if(n&&!s){if(!(n.id===a.id||n.id===a.previousLocalId||a.id>n.id))return e}return Object(r.H)(e,t,{lastMessage:a})}function W(e,t){const a=Object(o.m)(e,t),s=Object(o.Y)(e,t,i.MAIN_THREAD_ID);if(!a||!s)return;let c=s.length;for(;c--;){const e=a[s[c]];if(!e.isDeleting)return e}}function K(e,t,a,c){if(e){t.forEach(t=>{const a=W(c=Object(r.L)(c,e,t,{isDeleting:!0}),e);a&&(c=z(c,e,a,!0))}),Object(s.g)(c),a.requestChatUpdate({chatId:e});const n=[];return t.forEach(t=>{const a=Object(o.k)(c,e,t);if(!a)return;const{threadInfo:s}=Object(o.Bb)(c,e,a)||{};s&&n.push(s.threadId)}),Object(d.o)(n).forEach(t=>{a.requestThreadInfoUpdate({chatId:e,threadId:t})}),void setTimeout(()=>{Object(s.g)(Object(r.j)(Object(s.e)(),e,t))},350)}const n=[];t.forEach(e=>{const t=Object(o.p)(c,e);if(t){n.push(t);const a=W(c=Object(r.L)(c,t,e,{isDeleting:!0}),t);a&&(c=z(c,t,a,!0)),setTimeout(()=>{Object(s.g)(Object(r.j)(Object(s.e)(),t,[e]))},350)}}),Object(s.g)(c),Object(d.o)(n).forEach(e=>{a.requestChatUpdate({chatId:e})})}Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"newMessage":{const{chatId:c,id:n,message:i}=a;e=$(e=V(e,c,n,i),i),i.threadInfo&&(e=Object(r.kb)(e,i.threadInfo.chatId,i.threadInfo.threadId,i.threadInfo)),Object(s.g)(e);const l=Object(o.k)(e,c,n);if(Object(o.a)(e,c,i)){if(i.isOutgoing&&(!i.content||!i.content.action)){const a=Object(o.y)(e);a&&t.focusMessage({chatId:c,threadId:a.threadId,messageId:i.id,noHighlight:!0})}const{threadInfo:a}=Object(o.Bb)(e,c,i)||{};a&&t.requestThreadInfoUpdate({chatId:c,threadId:a.threadId}),i.isOutgoing||setTimeout(()=>{Object(s.g)(z(Object(s.e)(),c,l))},350)}else Object(s.g)(z(Object(s.e)(),c,l));Object(o.M)(e,c)||t.loadTopChats();break}case"newScheduledMessage":{const{chatId:t,id:c,message:n}=a;e=V(e,t,c,n,!0);const l=Object(o.ob)(e,t)||[];e=Object(r.x)(e,t,i.MAIN_THREAD_ID,"scheduledIds",Object(d.o)([...l,c])),Object(s.g)(e);break}case"updateMessage":{const{chatId:t,id:c,message:n}=a;if(!Object(o.k)(e,t,c))return;e=V(e,t,c,n);const i=Object(o.k)(e,t,c);n.threadInfo&&(e=Object(r.kb)(e,n.threadInfo.chatId,n.threadInfo.threadId,n.threadInfo)),e=z(e,t,i),Object(s.g)(e);break}case"updateScheduledMessage":{const{chatId:t,id:c,message:n}=a;if(!Object(o.pb)(e,t,c))return;e=V(e,t,c,n,!0);const l=Object.keys(Object(o.qb)(e,t)||{}).map(Number).sort((e,t)=>t-e);e=Object(r.x)(e,t,i.MAIN_THREAD_ID,"scheduledIds",l),Object(s.g)(e);break}case"updateMessageSendSucceeded":{const{chatId:t,localId:c,message:n}=a;e=$(e,n);const i=Object(o.k)(e,t,c);e=Object(r.j)(e,t,[c]),n.isScheduled&&(e=Object(r.k)(e,t,[c])),e=Object(r.L)(e,t,n.id,{...i,...n,previousLocalId:c});const l=Object(o.k)(e,t,n.id);e=z(e,t,l),Object(s.g)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:c,message:n}=a,l=Object(o.ob)(e,t)||[];e=Object(r.x)(e,t,i.MAIN_THREAD_ID,"scheduledIds",[...l,n.id]);const d=Object(o.pb)(e,t,c);e=Object(r.k)(e,t,[c]),e=Object(r.eb)(e,t,n.id,{...d,...n,previousLocalId:c}),Object(s.g)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:c,messageIds:n}=a,l=Object(o.jb)(e,t)||[],d=c?[...l,...n].sort((e,t)=>t-e):l.filter(e=>!n.includes(e));Object(s.g)(Object(r.x)(e,t,i.MAIN_THREAD_ID,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:c,threadInfo:n,firstMessageId:i}=a,l={...Object(o.Cb)(e,t,c),...n};if(!l.threadId)return;e=Object(r.kb)(e,t,c,l),i&&(e=Object(r.x)(e,t,c,"firstMessageId",i)),Object(s.g)(e);break}case"resetMessages":{const{id:c}=a,n=Object(o.m)(e,c);n&&!Object(m.lb)(c)&&(e=Object(r.j)(e,c,Object.keys(n).map(Number)),Object(s.g)(e),t.loadFullChat({chatId:c,force:!0}));break}case"deleteMessages":{const{ids:s,chatId:c}=a;K(c,s,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:c}=a;!function(e,t,a,c){if(!e)return;t.forEach(t=>{c=Object(r.eb)(c,e,t,{isDeleting:!0})}),Object(s.g)(c),setTimeout(()=>{c=Object(r.k)(Object(s.e)(),e,t);const a=Object(o.qb)(c,e);c=Object(r.x)(c,e,i.MAIN_THREAD_ID,"scheduledIds",Object.keys(a||{}).map(Number)),Object(s.g)(c)},350)}(c,t,0,e);break}case"deleteHistory":{const{chatId:s}=a;K(s,Object.keys(e.messages.byChatId[s].byId).map(Number),t,e);break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:c}=a;t.forEach(t=>{const a=Object(o.p)(e,t);a&&(e=Object(r.L)(e,a,t,c))}),Object(s.g)(e);break}case"updateChannelMessages":{const{channelId:t,ids:c,messageUpdate:n}=a;c.forEach(a=>{e=Object(r.L)(e,t,a,n)}),Object(s.g)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:c}=a,n=Object(o.l)(e,t);if(n&&n.content.poll){const t={...n.content.poll,...c},{results:a}=t.results||{};if(a&&!a.some(e=>e.isChosen)){const{results:e}=n.content.poll.results,s=e&&e.filter(e=>e.isChosen);s&&s.forEach(e=>{const s=a.findIndex(t=>t.option===e.option);s>=0&&(t.results.results[s].isChosen=!0)})}Object(s.g)(Object(r.L)(e,n.chatId,n.id,{content:{...n.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:c,options:n}=a,i=Object(o.l)(e,t);if(!i||!i.content.poll||!i.content.poll.results)break;const{poll:l}=i.content,{recentVoterIds:d,totalVoters:b,results:u}=l.results,m=d?[...d]:[],h=b?b+1:1,O=u?[...u]:[];m.push(c),n.forEach(t=>{const a=O.find(e=>e.option===t),s=O.findIndex(e=>e.option===t),n=a?{...a}:{option:t,votersCount:0};n.votersCount+=1,c===e.currentUserId&&(n.isChosen=!0),s?O[s]=n:O.push(n)}),Object(s.g)(Object(r.L)(e,i.chatId,i.id,{content:{...i.content,poll:{...l,results:{...l.results,recentVoterIds:m,totalVoters:h,results:O}}}}));break}}});const Q=Object(g.g)((function(){let e=Object(s.e)();Y.forEach(([t,a])=>{e=Object(r.nb)(e,t,{status:a})}),Object(s.g)(e),Y=[]}),3e3,!0);let Y=[];Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"deleteUser":return Object(r.l)(e,a.id);case"updateUser":return Object(r.nb)(e,a.id,a.user);case"updateUserStatus":return s=a.userId,c=a.status,Y.push([s,c]),void Q();case"updateUserFullInfo":{const{id:t,fullInfo:s}=a,c=e.users.byId[t];if(!c)return;return Object(r.nb)(e,t,{fullInfo:{...c.fullInfo,...s}})}}var s,c}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateStickerSet":return Object(r.hb)(e,a.id,a.stickerSet)}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updatePeerBlocked":return a.isBlocked?Object(r.a)(Object(s.e)(),a.id):Object(r.p)(Object(s.e)(),a.id);case"updateResetContactList":Object(s.g)({...Object(s.e)(),contactList:{hash:0,userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[a.key]=a.rules}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateNotifySettings":return Object(r.cb)(e,a.peerType,a.isSilent,a.shouldShowPreviews);case"updateNotifyExceptions":{const{id:t,isMuted:c,isSilent:n,shouldShowPreviews:o}=a;e.chats.byId[t]&&(e=Object(r.H)(e,t,{isMuted:c})),Object(s.g)(Object(r.e)(e,t,{isMuted:c,isSilent:n,shouldShowPreviews:o}));break}}}),Object(s.b)("apiUpdate",(e,t,a)=>{switch(a["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:a.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:a.message}}}});var X=a(48),J=a(8),Z=a(35),ee=a(131),te=a(47),ae=a(111),se=a(77),ce=a(25),ne=a(62),re=a(42),oe=a(32),ie=a(154),le=a(141);a(197);var de=Object(n.h)(({id:e,name:t,value:a,label:s,checked:c=!1,disabled:r,inactive:o,noAnimation:i,onChange:l,onCheck:d})=>{const b=Object(n.m)(e=>{l&&l(e),d&&d(e.currentTarget.checked)},[l,d]),u=Object(J.a)("Switcher",r&&"disabled",o&&"inactive",i&&"no-animation");return n.a.createElement("label",{className:u,title:s},n.a.createElement("input",{type:"checkbox",id:e,name:t,value:a,checked:c,disabled:r,onChange:b}),n.a.createElement("span",{className:"widget"}))});a(198);const be=[0,1,2];var ue=Object(n.h)(Object(s.h)(e=>{const{query:t,fetchingStatus:a,chatId:s,date:c}=e.globalSearch,{currentUserId:n}=e,{byId:r}=e.chats,{theme:o,animationLevel:i}=e.settings.byKey;return{searchQuery:t,isLoading:!!a&&Boolean(a.chats||a.messages),currentUserId:n,chatsById:r,globalSearchChatId:s,searchDate:c,theme:o,animationLevel:i}},(e,t)=>Object(d.l)(t,["openChat","openTipsChat","setGlobalSearchDate","setGlobalSearchChatId","setSettingOption"]))(({content:e,contactsFilter:t,onSearchQuery:a,onSelectSettings:s,onSelectContacts:r,onSelectArchived:o,setGlobalSearchChatId:i,onReset:d,searchQuery:b,isLoading:u,currentUserId:O,globalSearchChatId:j,searchDate:g,theme:f,animationLevel:p,chatsById:I,openChat:v,openTipsChat:y,setGlobalSearchDate:C,setSettingOption:E})=>{const w=Object(ce.a)(),M=e===l.d.ChatList,S={date:void 0},k={id:void 0},N=Object(n.p)(()=>g?Object(x.a)(new Date(1e3*g)):void 0,[g]),P=Object(n.p)(()=>M&&I?Object.values(I).reduce((e,t)=>Object(m.hb)(t)&&t.unreadCount?e+1:e,0):0,[M,I]),T=Object(n.p)(()=>({onTrigger:e,isOpen:t})=>n.a.createElement(oe.a,{round:!0,ripple:M&&!h.g,size:"smaller",color:"translucent",className:t?"active":"",onClick:M?e:()=>d(),ariaLabel:M?w("AccDescrOpenMenu2"):"Return to chat list"},n.a.createElement("div",{className:Object(J.a)("animated-menu-icon",!M&&"state-back")})),[M,w,d]),A=Object(n.m)(()=>{b||a("")},[b,a]),R=Object(n.m)(()=>{v({id:O})},[O,v]),L=Object(n.m)(e=>{e.stopPropagation();const t="light"===f?"dark":"light";E({theme:t}),Object(se.a)(t,p>0)},[p,E,f]),F=Object(n.m)(e=>{e.stopPropagation();const t=0===p?2:0;be.forEach((e,a)=>{document.body.classList.toggle("animation-level-"+a,t===a)}),E({animationLevel:t})},[p,E]),D=Boolean(j)||e===l.d.GlobalSearch||e===l.d.Contacts,B=e===l.d.Contacts?w("SearchFriends"):w("Search");return n.a.createElement("div",{className:"LeftMainHeader"},n.a.createElement("div",{id:"LeftMainHeader",className:"left-header"},n.a.createElement(ne.a,{trigger:T,footer:`${c.f} alpha ${c.g}`},n.a.createElement(re.a,{icon:"saved-messages",onClick:R},w("SavedMessages")),n.a.createElement(re.a,{icon:"archive",onClick:o},n.a.createElement("span",{className:"menu-item-name"},w("ArchivedChats")),P>0&&n.a.createElement("div",{className:"archived-badge"},P)),n.a.createElement(re.a,{icon:"user",onClick:r},w("Contacts")),n.a.createElement(re.a,{icon:"settings",onClick:s},w("Settings")),n.a.createElement(re.a,{icon:"darkmode",onClick:L},n.a.createElement("span",{className:"menu-item-name"},w("lng_menu_night_mode")),n.a.createElement(de,{id:"darkmode",label:w("dark"===f?"lng_settings_disable_night_theme":"lng_settings_enable_night_theme"),checked:"dark"===f,noAnimation:!0})),n.a.createElement(re.a,{icon:"animations",onClick:F},n.a.createElement("span",{className:"menu-item-name capitalize"},w("Appearance.Animations").toLowerCase()),n.a.createElement(de,{id:"animations",label:"Toggle Animations",checked:p>0})),n.a.createElement(re.a,{icon:"help",onClick:y},w("TelegramFeatures")),n.a.createElement(re.a,{icon:"bug",href:c.x},"Report Bug"),n.a.createElement(re.a,{icon:"char-K",href:"https://web.telegram.org/k/",onClick:()=>{localStorage.setItem("kz_version",JSON.stringify("K"))}},"Switch to K Version"),n.a.createElement(re.a,{icon:"char-W",href:"https://web.telegram.org/?legacy=1"},"Switch to Old Version")),n.a.createElement(ie.a,{inputId:"telegram-search-input",parentContainerClassName:"LeftSearch",className:j||g?"with-picker-item":"",value:t||b,focused:D,isLoading:u,placeholder:B,autoComplete:"off",canClose:Boolean(j||g),onChange:a,onReset:d,onFocus:A},N&&n.a.createElement(le.a,{icon:"calendar",title:N,canClose:!0,isMinimized:Boolean(j),className:"search-date",onClick:C,clickArg:S}),j&&n.a.createElement(le.a,{chatOrUserId:j,onClick:i,canClose:!0,clickArg:k}))))})),me=a(21);a(199);var he=Object(s.h)(e=>Object(d.l)(e,["connectionState"]))(({connectionState:e})=>{const t=Object(ce.a)();return"connectionStateConnecting"===e&&n.a.createElement("div",{id:"ConnectionState",dir:t.isRtl?"rtl":void 0},n.a.createElement(me.a,{color:"black"}),n.a.createElement("div",{className:"state-text"},t("WaitingForNetwork")))}),Oe=a(132),je=a(51),ge=a(26),fe=(e,t,a)=>{const s=Object(n.q)(),c=(e=>Object(n.p)(()=>Object(g.g)(e=>e(),e),[e]))(t),r=Object(ge.a)();return Object(je.a)(()=>{let t=!0;c(()=>{s.current=e(),t||r()}),t=!1},a),s.current},pe=a(168),Ie=a(189);var ve=Object(n.h)(Object(s.h)(e=>{const{chats:{byId:t},users:{byId:a},chatFolders:{byId:s,orderedIds:c,activeChatFolder:n},currentUserId:r,lastSyncTime:i}=e;return{chatsById:t,usersById:a,chatFoldersById:s,orderedFolderIds:c,lastSyncTime:i,notifySettings:Object(o.eb)(e),notifyExceptions:Object(o.db)(e),activeChatFolder:n,currentUserId:r}},(e,t)=>Object(d.l)(t,["loadChatFolders","setActiveChatFolder","openChat"]))(({chatsById:e,usersById:t,chatFoldersById:a,notifySettings:s,notifyExceptions:c,orderedFolderIds:r,activeChatFolder:o,currentUserId:i,lastSyncTime:l,loadChatFolders:b,setActiveChatFolder:u,openChat:O})=>{const j=Object(n.q)(null),g=Object(ce.a)();Object(n.n)(()=>{l&&b()},[l,b]);const f=Object(n.p)(()=>r?r.map(e=>a[e]||{}).filter(Boolean):void 0,[a,r]),p=fe(()=>{if(!f||!f.length)return;const a=Object.keys(e).map(Number),n=f.map(n=>{const{unreadDialogsCount:r,hasActiveDialogs:o}=Object(m.p)(e,t,n,a,s,c)||{};return{id:n.id,badgeCount:r,isBadgeActive:o}});return Object(d.c)(n,"id")},3e3,[f,e,t,s,c]),I=Object(n.p)(()=>{if(f&&f.length)return[{title:g("FilterAllChats")},...f.map(e=>({title:e.title,...p&&p[e.id]}))]},[f,p,g]),v=Object(n.m)(e=>{u(e)},[u]);Object(n.n)(()=>{I&&I.length&&o>=I.length&&u(0)},[o,I,u]),Object(n.n)(()=>{if(j.current&&h.l&&I&&I.length)return Object(Oe.b)(j.current,{onSwipe:(e,t)=>{t===Oe.a.Left?u(Math.min(o+1,I.length-1)):t===Oe.a.Right&&u(Math.max(0,o-1))}})},[o,I,u]);const y=Object(n.q)();y.current=0!==o,Object(n.n)(()=>y.current?Object(te.a)(()=>{y.current&&u(0)}):void 0,[o,u]),Object(n.n)(()=>{const e=e=>{if(e.metaKey&&e.code.startsWith("Digit")&&I){const[,t]=e.code.match(/Digit(\d)/)||[];if(!t)return;if("0"===t)return void O({id:i});const a=Number(t)-1;if(a>I.length-1)return;u(a),e.preventDefault()}};return document.addEventListener("keydown",e,!0),()=>{document.removeEventListener("keydown",e,!0)}});const{shouldRender:C,transitionClassNames:E}=Object(Z.a)(!r,void 0,!0);function w(e){const t=Object.values(a).find(({title:e})=>e===I[o].title);return t&&0!==o?n.a.createElement(Ie.a,{folderType:"folder",folderId:t.id,noChatsText:g("FilterNoChatsToDisplay"),isActive:e}):n.a.createElement(Ie.a,{folderType:"all",isActive:e})}return n.a.createElement("div",{className:"ChatFolders"},I&&I.length?n.a.createElement(pe.a,{tabs:I,activeTab:o,onSwitchTab:v}):C?n.a.createElement("div",{className:Object(J.a)("tabs-placeholder",E)}):void 0,n.a.createElement(ae.a,{ref:j,name:g.isRtl?"slide-reversed":"slide",activeKey:o,renderCount:I?I.length:void 0},w))})),ye=a(11),Ce=a(17),Ee=a(16);var we=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"LeftSearch");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)});var Me=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"ContactList");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)}),Se=a(53);a(210);let ke;var Ne=Object(n.h)(({isShown:e,onNewPrivateChat:t,onNewChannel:a,onNewGroup:s})=>{const[c,r]=Object(n.r)(!1);Object(n.n)(()=>{e||r(!1)},[e]);const o=Object(ce.a)(),i=Object(J.a)("NewChatButton",e&&"revealed",c&&"menu-is-open"),l=Object(n.m)(()=>{ke&&(clearTimeout(ke),ke=void 0)},[]),d=Object(n.m)(()=>{ke&&(clearTimeout(ke),ke=void 0),ke=window.setTimeout(()=>{r(!1)},750)},[]);return n.a.createElement("div",{className:i,onMouseEnter:l,onMouseLeave:d},n.a.createElement(oe.a,{round:!0,color:"primary",className:c?"active":"",onClick:()=>{r(!c)},ariaLabel:o(c?"Close":"NewMessageTitle"),tabIndex:-1},n.a.createElement("i",{className:"icon-new-chat-filled"}),n.a.createElement("i",{className:"icon-close"})),n.a.createElement(Se.a,{isOpen:c,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},n.a.createElement(re.a,{icon:"channel",onClick:a},o("NewChannel")),n.a.createElement(re.a,{icon:"group",onClick:s},o("NewGroup")),n.a.createElement(re.a,{icon:"user",onClick:t},o("NewMessageTitle"))))});a(211);const Pe=Object.keys(l.d).length/2;let Te;var Ae=Object(n.h)(({content:e,searchQuery:t,searchDate:a,contactsFilter:s,onSearchQuery:c,onContentChange:r,onReset:o})=>{const[i,d]=Object(n.r)(h.l),b=Object(n.q)(!1),u=Object(n.m)(()=>{r(l.d.Settings)},[r]),m=Object(n.m)(()=>{r(l.d.Contacts)},[r]),O=Object(n.m)(()=>{r(l.d.NewChannelStep1)},[r]),j=Object(n.m)(()=>{r(l.d.NewGroupStep1)},[r]),g=Object(n.m)(()=>{r(l.d.Archived)},[r]),f=Object(n.m)(()=>{e===l.d.ChatList&&(b.current=!0,d(!0))},[e]),p=Object(n.m)(()=>{b.current=!1,Te&&(clearTimeout(Te),Te=void 0),Te=window.setTimeout(()=>{b.current||d(!1)},250)},[]);return Object(n.n)(()=>{let t;return e!==l.d.ChatList?t=window.setTimeout(()=>{d(!1)},250):(b.current||h.l)&&d(!0),()=>{t&&(clearTimeout(t),t=void 0)}},[e]),n.a.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.l?void 0:f,onMouseLeave:h.l?void 0:p},n.a.createElement(ue,{content:e,contactsFilter:s,onSearchQuery:c,onSelectSettings:u,onSelectContacts:m,onSelectArchived:g,onReset:o}),n.a.createElement(he,null),n.a.createElement(ae.a,{name:"zoom-fade",renderCount:Pe,activeKey:e},c=>{switch(e){case l.d.ChatList:return n.a.createElement(ve,null);case l.d.GlobalSearch:return n.a.createElement(we,{searchQuery:t,searchDate:a,isActive:c,onReset:o});case l.d.Contacts:return n.a.createElement(Me,{filter:s});default:return}}),n.a.createElement(Ne,{isShown:i,onNewPrivateChat:m,onNewChannel:O,onNewGroup:j}))});var xe=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"Settings");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)});var Re=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"NewChat");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)});var Le,Fe=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"ArchivedChats");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)});a(212);!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"}(Le||(Le={}));const De=Object.keys(Le).length/2;var Be=Object(n.h)(Object(s.h)(e=>{const{globalSearch:{query:t,date:a},chatFolders:{activeChatFolder:s}}=e;return{searchQuery:t,searchDate:a,activeChatFolder:s}},(e,t)=>Object(d.l)(t,["setGlobalSearchQuery","setGlobalSearchChatId","resetChatCreation","setGlobalSearchDate","loadPasswordInfo","clearTwoFaError"]))(({searchQuery:e,searchDate:t,activeChatFolder:a,setGlobalSearchQuery:s,setGlobalSearchChatId:c,resetChatCreation:r,setGlobalSearchDate:o,loadPasswordInfo:i,clearTwoFaError:d})=>{const[b,u]=Object(n.r)(l.d.ChatList),[m,O]=Object(n.r)(l.m.Main),[j,g]=Object(n.r)(""),[f,p]=Object(n.r)(0);let I=Le.Main;switch(b){case l.d.Archived:I=Le.Archived;break;case l.d.Settings:I=Le.Settings;break;case l.d.NewChannelStep1:case l.d.NewChannelStep2:I=Le.NewChannel;break;case l.d.NewGroupStep1:case l.d.NewGroupStep2:I=Le.NewGroup}const v=Object(n.m)(e=>{if(b!==l.d.NewGroupStep2||e){if(b===l.d.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(b===l.d.Settings)switch(m){case l.m.EditProfile:case l.m.Folders:case l.m.General:case l.m.Notifications:case l.m.Privacy:case l.m.Language:return void O(l.m.Main);case l.m.GeneralChatBackground:return void O(l.m.General);case l.m.GeneralChatBackgroundColor:return void O(l.m.GeneralChatBackground);case l.m.PrivacyPhoneNumber:case l.m.PrivacyLastSeen:case l.m.PrivacyProfilePhoto:case l.m.PrivacyForwarding:case l.m.PrivacyGroupChats:case l.m.PrivacyActiveSessions:case l.m.PrivacyBlockedUsers:case l.m.TwoFaDisabled:case l.m.TwoFaEnabled:case l.m.TwoFaCongratulations:return void O(l.m.Privacy);case l.m.PrivacyPhoneNumberAllowedContacts:case l.m.PrivacyPhoneNumberDeniedContacts:return void O(l.m.PrivacyPhoneNumber);case l.m.PrivacyLastSeenAllowedContacts:case l.m.PrivacyLastSeenDeniedContacts:return void O(l.m.PrivacyLastSeen);case l.m.PrivacyProfilePhotoAllowedContacts:case l.m.PrivacyProfilePhotoDeniedContacts:return void O(l.m.PrivacyProfilePhoto);case l.m.PrivacyForwardingAllowedContacts:case l.m.PrivacyForwardingDeniedContacts:return void O(l.m.PrivacyForwarding);case l.m.PrivacyGroupChatsAllowedContacts:case l.m.PrivacyGroupChatsDeniedContacts:return void O(l.m.PrivacyGroupChats);case l.m.TwoFaNewPassword:return void O(l.m.TwoFaDisabled);case l.m.TwoFaNewPasswordConfirm:return void O(l.m.TwoFaNewPassword);case l.m.TwoFaNewPasswordHint:return void O(l.m.TwoFaNewPasswordConfirm);case l.m.TwoFaNewPasswordEmail:return void O(l.m.TwoFaNewPasswordHint);case l.m.TwoFaNewPasswordEmailCode:return void O(l.m.TwoFaNewPasswordEmail);case l.m.TwoFaChangePasswordCurrent:case l.m.TwoFaTurnOff:case l.m.TwoFaRecoveryEmailCurrentPassword:return void O(l.m.TwoFaEnabled);case l.m.TwoFaChangePasswordNew:return void O(l.m.TwoFaChangePasswordCurrent);case l.m.TwoFaChangePasswordConfirm:return void O(l.m.TwoFaChangePasswordNew);case l.m.TwoFaChangePasswordHint:return void O(l.m.TwoFaChangePasswordConfirm);case l.m.TwoFaRecoveryEmail:return void O(l.m.TwoFaRecoveryEmailCurrentPassword);case l.m.TwoFaRecoveryEmailCode:return void O(l.m.TwoFaRecoveryEmail);case l.m.FoldersCreateFolder:case l.m.FoldersEditFolder:return void O(l.m.Folders)}b!==l.d.ChatList||0!==a?(u(l.d.ChatList),g(""),s({query:""}),o({date:void 0}),c({id:void 0}),r(),setTimeout(()=>{p(Date.now())},250)):u(l.d.GlobalSearch)}else u(l.d.NewGroupStep1)},[b,a,s,o,c,r,m]),y=Object(n.m)(t=>{b!==l.d.Contacts?(u(l.d.GlobalSearch),t!==e&&s({query:t})):g(t)},[b,s,e]);return Object(n.n)(()=>b!==l.d.ChatList||0===a?Object(te.a)(()=>v()):void 0,[a,b,v]),Object(n.n)(()=>{d(),m===l.m.Privacy&&i()},[d,i,m]),n.a.createElement(ae.a,{id:"LeftColumn",name:h.g?"slide-layers":"push-slide",renderCount:De,activeKey:I},a=>{switch(I){case Le.Archived:return n.a.createElement(Fe,{isActive:a,onReset:v});case Le.Settings:return n.a.createElement(xe,{currentScreen:m,onScreenSelect:O,onReset:v});case Le.NewChannel:return n.a.createElement(Re,{key:f,isChannel:!0,content:b,onContentChange:u,onReset:v});case Le.NewGroup:return n.a.createElement(Re,{key:f,content:b,onContentChange:u,onReset:v});default:return n.a.createElement(Ae,{content:b,searchQuery:e,searchDate:t,contactsFilter:j,onContentChange:u,onSearchQuery:y,onReset:v})}})})),Ue=a(139),He=a(12),Ge=a(13),qe=a(56);var _e=()=>{const[e,t]=Object(n.r)(qe.a.get());return Object(n.n)(()=>{const e=Object(g.g)(()=>{t(qe.a.get())},250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}},[]),e},Ve=a(175);function $e(e,t){const a=e<=c.db?16:32,s=function(e){if(e>c.ab){const t=Math.min(Math.max(.25*e,288),424),a=Math.min(.25*e,424);return Math.min(e-t-a,728)}if(e>c.Z){const t=Math.min(Math.max(.4*e,288),424);return Math.min(e-t,728)}if(e>728)return 728;return e}(e),n=e<=c.db?54:64,r=t?s-a-n:s-a,o=e>c.db?Math.min(s-a,512):s-a,i=o/r,l=r/o;return{composerHiddenScale:i,toolbarHiddenScale:l,composerTranslateX:t?n/2*l:0,toolbarTranslateX:t?n/2*-1*i:0,unpinHiddenScale:o/258,toolbarForUnpinHiddenScale:258/o}}var ze=a(134),We=a(144),Ke=a(135),Qe=a(49),Ye=a(109),Xe=a(123);var Je=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"HeaderMenuContainer",!t);return a?n.a.createElement(a,e):void 0});var Ze=Object(n.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const c=Object(o.f)(e,t),n=Boolean(c&&Object(m.jb)(c));if(c&&c.isRestricted)return{noMenu:!0};const r=Object(o.P)(e,t),l="thread"===s&&a===i.MAIN_THREAD_ID,d="thread"===s&&a!==i.MAIN_THREAD_ID,b=Object(o.W)(e),u=Boolean(Object(o.L)(e,t)),O=Boolean(l&&c&&(n||Object(m.nb)(c))&&c.isNotJoined),j=l||d,g=l&&!r&&!O,f=!Object(o.S)(e),p=l&&!O;return{noMenu:!(h.g&&O||h.g&&j||g||f||p),isChannel:n,isRightColumnShown:b,canStartBot:u,canSubscribe:O,canSearch:j,canMute:g,canSelect:f,canLeave:p}},(e,t)=>Object(d.l)(t,["joinChannel","sendBotCommand","openLocalTextSearch"]))(({chatId:e,threadId:t,noMenu:a,isChannel:s,canStartBot:c,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,isRightColumnShown:b,joinChannel:u,sendBotCommand:m,openLocalTextSearch:O})=>{const j=Object(n.q)(null),[g,f]=Object(n.r)(!1),[p,I]=Object(n.r)(void 0),v=Object(n.m)(()=>{f(!0);const e=j.current.getBoundingClientRect();I({x:e.right,y:e.bottom})},[]),y=Object(n.m)(()=>{f(!1)},[]),C=Object(n.m)(()=>{I(void 0)},[]),E=Object(n.m)(()=>{u({chatId:e})},[u,e]),w=Object(n.m)(()=>{m({command:"/start"})},[m]),M=Object(n.m)(()=>{if(O(),h.g){document.querySelector("#MobileSearch input").focus()}else setTimeout(()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()},400)},[O]),S=Object(ce.a)();return n.a.createElement("div",{className:"HeaderActions"},!h.g&&r&&n.a.createElement(oe.a,{size:"tiny",ripple:!0,fluid:!0,onClick:E},S(s?"Subscribe":"Join Group")),!h.g&&c&&n.a.createElement(oe.a,{size:"tiny",ripple:!0,fluid:!0,onClick:w},S("Start")),!h.g&&o&&n.a.createElement(oe.a,{round:!0,ripple:b,color:"translucent",size:"smaller",onClick:M,ariaLabel:"Search in this chat"},n.a.createElement("i",{className:"icon-search"})),(h.g||!r)&&n.a.createElement(oe.a,{ref:j,className:g?"active":"",round:!0,ripple:!h.g,size:"smaller",color:"translucent",disabled:a,ariaLabel:"More actions",onClick:v},n.a.createElement("i",{className:"icon-more"})),p&&n.a.createElement(Je,{chatId:e,threadId:t,isOpen:g,anchor:p,isChannel:s,canSubscribe:r,canSearch:o,canMute:i,canSelect:l,canLeave:d,onSubscribeChannel:E,onSearchClick:M,onClose:y,onCloseAnimationEnd:C}))})),et=a(115),tt=a(23),at=a(108),st=a(44);function ct(e){const t=e&&Object(m.E)(e),{sticker:a}=e&&e.content||{},s=t&&a&&!Object(h.p)()&&t.includes("image/webp"),[r,o]=Object(n.r)(st.a),i=e&&e.id;return Object(n.o)(()=>{s&&Object(st.c)("b64-"+i,t).then(o).catch(e=>{c.p&&console.error(e)})},[i,s,t]),s?r:t}var nt=a(117),rt=a(43),ot=a(34);function it(e,t,a,s,c){return`M${e},${t+c}a${c},${c},0,0,1,\n ${a},0v${s-2*c}a${c},${c},0,0,1,${-a},0Z`}var lt=Object(n.h)(({count:e,index:t})=>{const a=Object(n.q)(null),s=Object(n.p)(()=>function(e,t){const a=e-t-1,s=function(e){let t=8;1===e?t=36:2===e?t=17:3===e?t=11:(4===e||e>3)&&(t=7.5);return t}(e),c=function(e,t){let a=36;1===e?a=36:2===e?a=17:3===e?a=1===t?12:11:(4===e||e>3)&&(a=7.5);return a}(e,a),n=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,s),r="clipPath"+e,o=function(e,t,a){let s="";if(3===a)s=it(0,0,2,t,1)+it(0,12,2,t+1,1)+it(0,25,2,t,1);else for(let e=0;e\n \n `}(r,s,e),i=function(e,t,a){if(1===a)return 0;if(2===a)return 0===e?0:t+2;return 3===a?0===e?0:1===e?12:25:(t+2)*e}(a,s,e),l=function(e,t,a,s){if(t<=4)return 0;if(e<=1)return 0;if(e>=t-2)return s-36;return(a+4)/2+(e-2)*(a+2)}(a,e,s,n);return{markHeight:c,clipPath:o,markTranslateY:i,trackTranslateY:l,trackHeight:n,clipPathId:r}}(e,t),[e,t]);if(Object(n.n)(()=>{if(!a.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:c,markTranslateY:n,clipPathId:r,clipPath:o}=s,i=a.current.firstElementChild;if(a&&a.current){const s=a.current,{style:l}=s;l.height=e+"px",l.transform=`translateY(-${t}px)`,l.clipPath=`url("#${r}")`;const d=s.querySelector("svg"),b=s.querySelector("div"),u=s.querySelector("defs");d||i&&(i.innerHTML=` ${o} `),u&&(u.innerHTML=o),b&&(b.style.height=c+"px",b.style.transform=`translateY(${n}px)`)}},[s]),1===e)return n.a.createElement("div",{className:"pinned-message-border"},n.a.createElement("div",{className:"pinned-message-border-wrapper-1",ref:a}));const{trackHeight:c,trackTranslateY:r,markHeight:o,markTranslateY:i,clipPathId:l}=s;return n.a.createElement("div",{className:Object(J.a)("pinned-message-border",e>4&&"pinned-message-border-mask")},n.a.createElement("div",{className:"pinned-message-border-wrapper",ref:a,style:`clip-path: url("#${l}"); width: 2px;\n height: ${c}px; transform: translateY(-${r}px);`},n.a.createElement("span",null),n.a.createElement("div",{className:"pinned-message-border-mark",style:`height: ${o}px; transform: translateY(${i}px);`})))});var dt=Object(n.h)(({message:e,count:t,index:a,customTitle:s,className:c,onUnpinMessage:r,onClick:o,onAllPinnedClick:i})=>{const l=Object(ce.a)(),d=ct(e),b=Object(at.a)(Object(m.D)(e,"pictogram")),u=Object(m.N)(l,e,Boolean(d)),[h,O,j]=Object(ot.a)(),g=Object(n.m)(()=>{j(),r&&r(e.id)},[j,r,e.id]);return n.a.createElement("div",{className:Object(J.a)("HeaderPinnedMessage-wrapper",c)},t>1&&n.a.createElement(oe.a,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:l("EventLogFilterPinnedMessages"),onClick:i},n.a.createElement("i",{className:"icon-pin-list"})),r&&n.a.createElement(oe.a,{round:!0,size:"smaller",color:"translucent",ariaLabel:l("UnpinMessageAlertTitle"),className:"unpin-button",onClick:O},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(nt.a,{isOpen:h,onClose:j,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:g}),n.a.createElement("div",{className:"HeaderPinnedMessage",onClick:o,dir:l.isRtl?"rtl":void 0},n.a.createElement(lt,{count:t,index:a}),d&&function(e,t){const{width:a,height:s}=Object(et.k)();return n.a.createElement("img",{src:t||e,width:a,height:s,alt:""})}(d,b),n.a.createElement("div",{className:"message-text"},n.a.createElement("div",{className:"title",dir:"auto"},s||`${l("PinnedMessage")} ${a>0?"#"+(t-a):""}`),n.a.createElement("p",{dir:"auto"},Object(tt.a)(u))),n.a.createElement(rt.a,null)))}),bt=a(54),ut=a(176);a(215);var mt=Object(s.h)((e,{message:t})=>({sender:Object(o.tb)(e,t)}),(e,t)=>Object(d.l)(t,["focusMessage","closeAudioPlayer"]))(({message:e,className:t,noUi:a,sender:s,focusMessage:c,closeAudioPlayer:r})=>{const o=Object(ce.a)(),i=s?Object(m.V)(o,s):void 0,l=bt.c(Object(m.D)(e,"inline")),{playPause:d,isPlaying:b}=Object(ut.a)(Object(m.A)(e),Object(m.r)(e),l,void 0,void 0,!0),u=Object(n.m)(()=>{c({chatId:e.chatId,messageId:e.id})},[c,e.chatId,e.id]),O=Object(n.m)(()=>{b&&d(),r()},[r,b,d]);if(a)return;const j=Object(m.u)(e);return n.a.createElement("div",{className:Object(J.a)("AudioPlayer",t),dir:o.isRtl?"rtl":void 0},n.a.createElement(oe.a,{round:!0,ripple:!h.g,color:"translucent",size:"smaller",className:Object(J.a)("toggle-play",b?"pause":"play"),onClick:d,ariaLabel:b?"Pause audio":"Play audio"},n.a.createElement("i",{className:"icon-play"}),n.a.createElement("i",{className:"icon-pause"})),n.a.createElement("div",{className:"AudioPlayer-content",onClick:u},j?function(e){const{title:t,performer:a,fileName:s}=e;return n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"title",dir:"auto"},Object(tt.a)(t||s)),a&&n.a.createElement("div",{className:"subtitle",dir:"auto"},Object(tt.a)(a)))}(j):function(e,t){return n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"title",dir:"auto"},t&&Object(tt.a)(t)),n.a.createElement("div",{className:"subtitle",dir:"auto"},e))}(o("AttachAudio"),i),n.a.createElement(rt.a,null)),n.a.createElement(oe.a,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:O,ariaLabel:"Close player"},n.a.createElement("i",{className:"icon-close"})))});a(216);var ht=Object(n.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const{isLeftColumnShown:c,lastSyncTime:n}=e,{byId:r}=e.chats,l=Object(o.f)(e,t),{typingStatus:d}=l||{},{chatId:b,messageId:u}=e.audioPlayer,m=b&&u?Object(o.k)(e,b,u):void 0,h=Object(o.Db)(e,t,a);let O;if("pinned"===s){const a=Object(o.jb)(e,t);O=a&&a.length}else if("scheduled"===s){const a=Object(o.ob)(e,t);O=a&&a.length}else if("thread"===s&&a!==i.MAIN_THREAD_ID){const s=Object(o.Cb)(e,t,a);s&&(O=s.messagesCount)}const j={typingStatus:d,isLeftColumnShown:c,isRightColumnShown:Object(o.W)(e),isSelectModeActive:Object(o.S)(e),audioMessage:m,chat:l,chatsById:r,originChatId:h?h.id:t,messagesCount:O,isChatWithSelf:Object(o.P)(e,t),isChatWithBot:l&&Object(o.O)(e,l),lastSyncTime:n,notifySettings:Object(o.eb)(e),notifyExceptions:Object(o.db)(e)},g=Object(o.m)(e,t);if("thread"!==s||!g)return j;if(Object.assign(j,{messagesById:g}),a!==i.MAIN_THREAD_ID){const s=Object(o.Eb)(e,t,a),c=s?Object(o.k)(e,t,s):void 0,n=c?Object(o.K)(e,c):void 0;return{...j,pinnedMessageIds:s,canUnpin:!1,topMessageSender:n}}const f=Object(o.jb)(e,t);if(f&&f.length){const t=g[f[0]],{canUnpin:s}=t&&Object(o.b)(e,t,a)||{};return{...j,pinnedMessageIds:f,canUnpin:s}}return j},(e,t)=>Object(d.l)(t,["openChatWithInfo","pinMessage","focusMessage","openChat","loadPinnedMessages","toggleLeftColumn","exitMessageSelectMode"]))(({chatId:e,threadId:t,messageListType:a,pinnedMessageIds:s,messagesById:r,canUnpin:o,topMessageSender:l,typingStatus:d,isSelectModeActive:b,isLeftColumnShown:u,isRightColumnShown:O,audioMessage:j,chat:g,chatsById:f,originChatId:p,messagesCount:I,isChatWithSelf:v,isChatWithBot:y,lastSyncTime:C,notifySettings:E,notifyExceptions:w,openChatWithInfo:M,pinMessage:S,focusMessage:k,openChat:N,loadPinnedMessages:P,toggleLeftColumn:T,exitMessageSelectMode:A})=>{const x=Object(ce.a)(),[R,L]=Object(n.r)(0),F=Array.isArray(s)?s[R]:s,D=r&&F?r[F]:void 0,B=Array.isArray(s)?s.length:s?1:0,U=g&&Object(m.l)(x,g).length,H=l?Object(m.V)(x,l):void 0;Object(n.n)(()=>{t===i.MAIN_THREAD_ID&&C&&P({chatId:e})},[e,P,C,t]),Object(n.n)(()=>{L(0)},[s]),Object(We.a)(e,F,D);const{width:G}=_e(),q=G<=c.Z,_=G>=c.db&&u,V=Object(n.q)(null),$=Object(n.q)(!0),z=Object(n.m)(()=>{M({id:e})},[M,e]),W=Object(n.m)(t=>{S({chatId:e,messageId:t,isUnpin:!0})},[S,e]),K=Object(n.m)(()=>{if(D){k({chatId:D.chatId,threadId:t,messageId:D.id});const e=Object(ze.a)(B,R+1);L(e)}},[D,k,t,B,R]),Q=Object(n.m)(()=>{N({id:e,threadId:i.MAIN_THREAD_ID,type:"pinned"})},[N,e]),Y=Object(n.m)(()=>{if(h.g){const e=document.getElementById(c.v);e&&e.blur()}t!==i.MAIN_THREAD_ID||"thread"!==a?("scheduled"===a&&b&&A(),N({id:p,threadId:i.MAIN_THREAD_ID})):h.g?N({id:void 0}):T()},[N,p,t,a,T,b,A]),X=Object(n.p)(()=>{if(!q||!f)return;let e=!1;const t=Object.values(f).reduce((t,a)=>{if(Object(m.hb)(a))return t;const s=a.unreadCount||0;return!s||Object(m.Cb)(a,E,w)&&!a.unreadMentionsCount||(e=!0),t+s},0);return t?{isActive:e,totalCount:t}:void 0},[q,f,E,w]),ee=G>=c.Z&&Gc.db&&G30),te=ee||G>c.ab&&G{const e=V.current;if(e)return te&&ue?void(O||ee?($.current&&(e.classList.add("tools-stacked","animated"),$.current=!1),setTimeout(()=>{e.classList.remove("animated")},350)):(e.classList.remove("tools-stacked"),$.current=!0)):(e.classList.remove("tools-stacked","animated"),void($.current=!0))},[te,ue,ee,O]),n.a.createElement("div",{className:"MiddleHeader",ref:V},n.a.createElement(ae.a,{name:"slide-fade",activeKey:"thread"===a?t:1},me),n.a.createElement("div",{className:"header-tools"},ie&&de&&!se&&n.a.createElement(dt,{key:e,message:de,count:B,index:R,customTitle:be,className:le,onUnpinMessage:o?W:void 0,onClick:K,onAllPinnedClick:Q}),se&&re&&n.a.createElement(mt,{key:Object(m.A)(re),message:re,className:ne}),n.a.createElement(Ze,{chatId:e,threadId:t,messageListType:a})))})),Ot=a(159);function jt(e){return"albumId"in e}function gt(e,t){let a,s=[],c={originalDate:e[0].date,datetime:Number(Object(x.j)(1e3*e[0].date)),senderGroups:[s]};const n=[c];return e.forEach((r,o)=>{r.isInAlbum?a?(a.messages.push(r),r.content.text&&(a.mainMessage=r)):a={albumId:r.groupedId,messages:[r],mainMessage:r}:s.push(r);const i=e[o+1];if(!a||i&&i.groupedId&&i.groupedId===a.albumId||(s.push(a),a=void 0),i){const e=Number(Object(x.j)(1e3*i.date));c.datetime!==e?(c={originalDate:i.date,datetime:e,senderGroups:[]},n.push(c),s=[],c.senderGroups.push(s)):(i.id===t||r.senderId!==i.senderId||r.isOutgoing!==i.isOutgoing||Object(m.db)(r)||Object(m.db)(i)||r.forwardInfo&&i.forwardInfo&&(r.forwardInfo.senderUserId!==i.forwardInfo.senderUserId||r.forwardInfo.fromChatId!==i.forwardInfo.fromChatId||r.forwardInfo.hiddenUserName!==i.forwardInfo.hiddenUserName)||r.inlineButtons||i.inlineButtons)&&(s=[],c.senderGroups.push(s))}}),n}var ft=a(107);function pt(){const[e,t]=Object(ot.a)(!1),a=(s=1e3,c=!1,Object(n.p)(()=>Object(g.a)(e=>e(),s,c,r),[s,c,r]));var s,c,r;return{isScrolled:e,updateStickyDates:Object(n.m)((e,s)=>{t(),document.body.classList.contains("is-scrolling-messages")||Object(g.b)(()=>{document.body.classList.add("is-scrolling-messages")}),a(()=>{Object(g.b)(()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const a=function(e,t){const a=e.querySelectorAll(".sticky-date"),s=e.scrollTop;return Array.from(a).find(e=>{const{offsetTop:a,offsetHeight:c}=e,n=a-s;return-c<=n&&n<=(t?60:10)})}(e,s);a&&a.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")})})},[t,a])}}var It=a(155),vt=a(124);let yt=!1;var Ct=({containerRef:e,className:t,messageIds:a,focusingId:s,loadMoreForwards:r,loadMoreBackwards:o,isViewportNewest:i,firstUnreadId:l,onFabToggle:d,onNotchToggle:b,children:u})=>{const m=Object(n.q)(null),h=Object(n.q)(null),O=Object(n.q)(null),j=Object(n.m)(()=>{if(yt)return;if(!a||!a.length)return d(!1),void b(!1);if(!i)return d(!0),void b(!0);const{offsetHeight:t,scrollHeight:s,scrollTop:c}=e.current,n=s-c-t,r=n<=0;d(l?!r:!(n<=50)),b(!r)},[a,i,e,d,l,b]),{observe:g,freeze:f,unfreeze:p}=Object(ft.a)({rootRef:e,margin:c.U},t=>{if(!r||!o)return;const a=t.find(({isIntersecting:e})=>e);if(!a)return;const{target:s}=a;"backwards-trigger"===s.className?(Object(It.a)(e.current),o()):"forwards-trigger"===s.className&&(Object(It.a)(e.current),r())});Object(ft.c)(m,g),Object(ft.c)(h,g);const{observe:I,freeze:v,unfreeze:y}=Object(ft.a)({rootRef:e,margin:50},j);Object(ft.c)(O,I);const{observe:C}=Object(ft.a)({rootRef:e},j);return Object(ft.c)(O,C),Object(je.a)(()=>{s?(f(),v()):(y(),p())},[s]),Object(je.a)(()=>{yt=!0,setTimeout(()=>{yt=!1},100)},[a]),Object(n.n)(j,[l]),n.a.createElement("div",{className:t,teactFastList:!0},n.a.createElement("div",{ref:m,key:"backwards-trigger",className:"backwards-trigger"}),u,n.a.createElement("div",{ref:h,key:"forwards-trigger",className:"forwards-trigger"}),n.a.createElement("div",{ref:O,key:"fab-trigger",className:"fab-trigger"}))},Et=a(145),wt=a(146);function Mt(e){return"number"==typeof e}function St(e,t){return e?t?238:175:100}function kt(e){const t=Object(m.tb)(e),a=Object(m.qb)(e),s=Object(m.G)(e)||Object(m.R)(e),c=Object(m.P)(e),n=Boolean(Object(m.R)(e)),{width:r,height:o}=s?Object(et.f)(s,t,a,n):Object(et.h)(c,t,a),i=St(Boolean(Object(m.O)(e)));let l=1;re+t,t)}function Lt(e,t,a){return ea?a:e}function Ft(e){const t={width:0,height:0};return e.forEach(({dimensions:e,sides:a})=>{a&Tt&&(t.width=e.width+e.x),a&At&&(t.height=e.height+e.y)}),t}function Dt(e,t,a,s){const n=a.messages.map(e=>{const t=kt(e);return t.width/t.height});const r=function(e){return e.map(e=>e>1.2?"w":e<.8?"n":"q").join("")}(n),o=function(e){return e.reduce((e,t)=>t+e,1)/e.length}(n),i=n.length,l=n.some(e=>e>2),d=function(e,t,a){return a<=c.db?a/100*69-(t?1.625:0)*et.c:((e?30:29)-(t?1.625:0))*et.c}(e,t,s);let b;const u={ratios:n,proportions:r,averageRatio:o,maxWidth:d,minWidth:100,maxHeight:d,spacing:2};return b=i>=5||l?function({ratios:e,averageRatio:t,maxWidth:a,minWidth:s,spacing:c,maxHeight:n=4*a/3}){const r=function(e,t){return e.map(e=>t>1.1?Lt(e,1,2.75):Lt(e,.6667,1))}(e,t),o=e.length,i=new Array(o),l=[],d=e=>{const t=[];let s=0;e.forEach(e=>{t.push(((e,t)=>{const s=Rt(r.slice(e,e+t),0);return(a-(t-1)*c)/s})(s,e)),s+=e}),l.push({lineCounts:e,heights:t})};for(let e=1;e!==o;++e){const t=o-e;e<=3&&t<=3&&d([e,t])}for(let e=1;e!==o-1;++e)for(let a=1;a!==o-e;++a){const s=o-e-a;e<=3&&a<=(t<.85?4:3)&&s<=3&&d([e,a,s])}for(let e=1;e!==o-1;++e)for(let t=1;t!==o-e;++t)for(let a=1;a!==o-e-t;++a){const s=o-e-t-a;e<=3&&t<=3&&a<=3&&s<=4&&d([e,t,a,s])}let b,u=0;for(let e=0;e{for(let e=1;e!==r;++e)if(a[e-1]>a[e])return 1.5;return 1})(),m=Math.abs(o-n)*i*d;(!b||m1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:c}=e,n=Math.round(Math.min(a/t[0],Math.min(a/t[1],(c-s)/2)));return[{dimensions:{x:0,y:0,width:a,height:n},sides:xt|Pt|Tt},{dimensions:{x:0,y:n+s,width:a,height:n},sides:xt|At|Tt}]}(e):"ww"===a||"qq"===a?function(e){const{ratios:t,maxWidth:a,spacing:s,maxHeight:c}=e,n=(a-s)/2,r=Math.round(Math.min(n/t[0],Math.min(n/t[1],c)));return[{dimensions:{x:0,y:0,width:n,height:r},sides:Pt|xt|At},{dimensions:{x:n+s,y:0,width:n,height:r},sides:Pt|Tt|At}]}(e):function(e){const{ratios:t,minWidth:a,maxWidth:s,spacing:c,maxHeight:n}=e,r=Math.round(1.5*a),o=Math.min(Math.round(Math.max(.4*(s-c),(s-c)/t[0]/(1/t[0]+1/t[1]))),s-c-r),i=s-o-c,l=Math.min(n,Math.round(Math.min(i/t[0],o/t[1])));return[{dimensions:{x:0,y:0,width:i,height:l},sides:Pt|xt|At},{dimensions:{x:i+c,y:0,width:o,height:l},sides:Pt|Tt|At}]}(e)}(u):3===i?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:a,ratios:s,maxWidth:c,minWidth:n}=e,r=t,o=Math.round(Math.min((t-a)/2,s[1]*(c-a)/(s[2]+s[1]))),i=r-o-a,l=Math.max(n,Math.round(Math.min((c-a)/2,Math.min(o*s[2],i*s[1])))),d=Math.min(Math.round(r*s[0]),c-a-l);return[{dimensions:{x:0,y:0,width:d,height:r},sides:Pt|xt|At},{dimensions:{x:d+a,y:0,width:l,height:i},sides:Pt|Tt},{dimensions:{x:d+a,y:i+a,width:l,height:o},sides:At|Tt}]}(e):function(e){const{maxWidth:t,ratios:a,maxHeight:s,spacing:c}=e,n=t,r=Math.round(Math.min(n/a[0],.66*(s-c))),o=(t-c)/2,i=Math.min(s-r-c,Math.round(Math.min(o/a[1],o/a[2])));return[{dimensions:{x:0,y:0,width:n,height:r},sides:xt|Pt|Tt},{dimensions:{x:0,y:r+c,width:o,height:i},sides:At|xt},{dimensions:{x:o+c,y:r+c,width:n-o-c,height:i},sides:At|Tt}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function({maxWidth:e,ratios:t,spacing:a,maxHeight:s,minWidth:c}){const n=e,r=Math.round(Math.min(n/t[0],.66*(s-a))),o=Math.round((e-2*a)/(t[1]+t[2]+t[3])),i=Math.max(c,Math.round(Math.min(.4*(e-2*a),o*t[1]))),l=Math.round(Math.max(Math.max(c,.33*(e-2*a)),o*t[3])),d=n-i-l-2*a,b=Math.min(s-r-a,o);return[{dimensions:{x:0,y:0,width:n,height:r},sides:xt|Pt|Tt},{dimensions:{x:0,y:r+a,width:i,height:b},sides:At|xt},{dimensions:{x:i+a,y:r+a,width:d,height:b},sides:At},{dimensions:{x:i+a+d+a,y:r+a,width:l,height:b},sides:Tt|At}]}(e):function({maxHeight:e,ratios:t,maxWidth:a,spacing:s,minWidth:c}){const n=e,r=Math.round(Math.min(n*t[0],.6*(a-s))),o=Math.round((e-2*s)/(1/t[1]+1/t[2]+1/t[3])),i=Math.round(o/t[1]),l=Math.round(o/t[2]),d=n-i-l-2*s,b=Math.max(c,Math.min(a-r-s,o));return[{dimensions:{x:0,y:0,width:r,height:n},sides:Pt|xt|At},{dimensions:{x:r+s,y:0,width:b,height:i},sides:Pt|Tt},{dimensions:{x:r+s,y:i+s,width:b,height:l},sides:Tt},{dimensions:{x:r+s,y:i+l+2*s,width:b,height:d},sides:At|Tt}]}(e)}(u),{layout:b,containerStyle:Ft(b)}}let Bt;function Ut(e){return Bt||(Bt=document.createElement("span"),Bt.style.font='400 12px Roboto, "Helvetica Neue", "Apple Color Emoji", sans-serif',Bt.style.whiteSpace="nowrap",Bt.style.position="absolute",Bt.style.left="-999px",Bt.style.opacity=".01",document.body.appendChild(Bt)),Bt.innerHTML=e,Bt.offsetWidth}function Ht(e,t,a,s,c){Object(n.o)(()=>{if(a&&e.current){const t=e.current.closest(".MessageList");Object(vt.a)(t,e.current,c?"end":"center",20,void 0===s?1500:1e3,s)}},[e,t,a,s,c])}var Gt=a(112),qt=a(67);var _t=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"ContextMenuContainer",!t);return a?n.a.createElement(a,e):void 0});var Vt=Object(n.h)(Object(s.h)((e,{message:t})=>{const a=t.senderId,{targetUserId:s,targetChatId:c}=t.content.action||{},n=t.replyToMessageId,r=n?Object(o.k)(e,t.chatId,n):void 0,i=Object(o.U)(e,t),{direction:l,noHighlight:d}=i&&e.focusedMessage||{},b=Object(o.f)(e,t.chatId);return{sender:b&&(Object(m.jb)(b)||a===t.chatId)?b:a?Object(o.Gb)(e,a):void 0,...s&&{targetUser:Object(o.Gb)(e,s)},targetChatId:c,targetMessage:r,isFocused:i,...i&&{focusDirection:l,noFocusHighlight:d}}})(({message:e,observeIntersection:t,isEmbedded:a,appearanceOrder:s=0,isLastInList:c,sender:r,targetUser:o,targetMessage:i,targetChatId:l,isFocused:d,focusDirection:b,noFocusHighlight:u})=>{const m=Object(n.q)(null);Object(ft.c)(m,t),Object(We.a)(e.chatId,e.replyToMessageId,i),Ht(m,e.chatId,d,b,u);const h=Object(ce.a)(),O=s<=0,[j,g]=Object(ot.a)(O);Object(n.n)(()=>{O||setTimeout(g,10*s)},[s,g,O]);const{transitionClassNames:f}=Object(Z.a)(j,void 0,O,!1),p=Object(qt.a)(h,e,r,o,i,l,a?{isEmbedded:!0,asPlain:!0}:void 0),{isContextMenuOpen:I,contextMenuPosition:v,handleBeforeContextMenu:y,handleContextMenu:C,handleContextMenuClose:E,handleContextMenuHide:w}=Object(Et.a)(m),M=void 0!==v;if(a)return n.a.createElement("span",{className:"embedded-action-message"},Object(tt.a)(p));const S=Object(J.a)("ActionMessage message-list-item",d&&!u&&"focused",M&&"has-menu-open",c&&"last-in-list",f);return n.a.createElement("div",{ref:m,id:"message"+e.id,className:S,"data-message-id":e.id,onMouseDown:y,onContextMenu:C},n.a.createElement("span",null,p),v&&n.a.createElement(_t,{isOpen:I,anchor:v,message:e,messageListType:"thread",onClose:E,onCloseAnimationEnd:w}))}));a(217);var $t=({className:e,message:t,sender:a,title:s,customText:c,observeIntersection:r,onClick:o})=>{const i=Object(n.q)(null),l=Object(ft.b)(i,r),d=Object(at.a)(t&&Object(m.D)(t,"pictogram"),!l),b=t&&"sticker-reply-thumb"+t.id,u=ct(t),h=Boolean(t&&Object(m.I)(t)),O=Object(ce.a)(),j=a&&Object(m.V)(O,a);return n.a.createElement("div",{ref:i,className:Object(J.a)("EmbeddedMessage",e),onClick:t?o:void 0},u&&function(e,t,a,s){const{width:c,height:r}=Object(et.k)();return n.a.createElement("img",{id:e,src:a||t,width:c,height:r,alt:"",className:s?"round":""})}(b,u,d,h),n.a.createElement("div",{className:"message-text"},n.a.createElement("p",{dir:"auto"},t?Object(m.db)(t)?n.a.createElement(Vt,{message:t,isEmbedded:!0}):Object(tt.a)(Object(m.N)(O,t,Boolean(u))):c||" "),n.a.createElement("div",{className:"message-title",dir:"auto"},Object(tt.a)(j||s||" "))))},zt=a(160),Wt=a(167),Kt=a(172);a(221);var Qt=Object(n.h)(({message:e,outgoingStatus:t,signature:a,onClick:s})=>{const c=Object(ce.a)();return n.a.createElement("span",{className:"MessageMeta",dir:c.isRtl?"rtl":"ltr",onClick:s},Boolean(e.views)&&n.a.createElement(n.a.Fragment,null,n.a.createElement("span",{className:"message-views"},Object(Qe.b)(e.views)),n.a.createElement("i",{className:"icon-channelviews"})),a&&n.a.createElement("span",{className:"message-signature"},Object(tt.a)(a)),n.a.createElement("span",{className:"message-time"},e.isEdited&&c("EditedMessage")+" ",Object(x.h)(1e3*e.date)),t&&n.a.createElement(Kt.a,{status:t}))}),Yt=a(114),Xt=a(116),Jt=a(161);a(222);var Zt=({message:e,observeIntersection:t,observeIntersectionForPlaying:a,shouldLoop:s,lastSyncTime:r})=>{const o=Object(n.q)(null),[i,l,d]=Object(ot.a)(),b=e.content.sticker,{isAnimated:u,stickerSetId:h}=b,O=h===c.S,j=Object(ft.b)(o,t),g=Object(ft.b)(o,a),f=b.isPreloadedGlobally?"sticker"+b.id:Object(m.D)(e,"inline"),p=ct(e),I=Object(at.a)(f,!j,Object(m.C)(e,"inline",!0),r),v=Boolean(I),[y,C]=Object(ot.a)(v),E=u?y:v,{shouldRenderFullMedia:w,transitionClassNames:M}=Object(Yt.a)(E,"slow"),{width:S,height:k}=Object(et.l)(b),N=Object(J.a)("thumbnail",!p&&"empty"),P=Object(J.a)("Sticker media-inner",O&&"inactive");return n.a.createElement("div",{ref:o,className:P,onClick:O?void 0:l},!E&&n.a.createElement("img",{id:"sticker-thumb-"+e.id,src:p,width:S,height:k,alt:"",className:N}),!u&&w&&n.a.createElement("img",{id:"sticker-"+e.id,src:I,width:S,height:k,alt:"",className:Object(J.a)("full-media",M)}),u&&v&&n.a.createElement(Xt.a,{key:f,className:Object(J.a)("full-media",M),id:f,animationData:I,size:S,play:g,noLoop:!s,onLoad:C}),n.a.createElement(Jt.a,{isOpen:i,fromSticker:b,onClose:d}))},ea=a(128),ta=a(120),aa=a(162);function sa(e,t){return Object(aa.a)(Object(m.E)(e),Boolean(t),h.g&&!h.c)}var ca=a(38);var na=async(e,t,a,s)=>s?"rgba(255,255,255,1)":async function(e,t){const a=new Image;a.src=e,a.width||await new Promise(e=>{a.onload=e});const s=document.createElement("canvas"),c=s.getContext("2d");s.width=a.width,s.height=a.height,c.drawImage(a,0,0,a.width,a.height);const n=t?a.width-1:0,r=a.height-1;return`rgba(${Array.from(c.getImageData(n,r,1,1).data).join(",")})`}(e,t);var ra=a(121);var oa=({id:e,message:t,observeIntersection:a,shouldAutoLoad:s,isInSelectMode:c,isSelected:r,uploadProgress:o,size:i="inline",dimensions:l,nonInteractive:d,shouldAffectAppendix:b,onClick:u,onCancelUpload:h})=>{const O=Object(n.q)(null),j=(Object(m.G)(t)||Object(m.R)(t)).blobUrl,g=Object(ft.b)(O,a),[f,p]=Object(n.r)(s),I=f&&g,{mediaData:v,downloadProgress:y}=Object(ta.a)(Object(m.D)(t,i),!I),C=j||v,E=sa(t,C),{isUploading:w,isTransferring:M,transferProgress:S}=Object(m.s)(t,o||y,I&&!C),k=!1===Object(ca.a)(f),{shouldRender:N,transitionClassNames:P}=Object(Z.a)(M,void 0,k,"slow"),{shouldRenderThumb:T,shouldRenderFullMedia:A,transitionClassNames:x}=Object(Yt.a)(C,"slow"),R=Object(n.m)(()=>{w?h&&h(t):C?u&&u(t.id):p(e=>!e)},[C,w,t,h,u]),L=Object(m.tb)(t);Object(n.o)(()=>{if(!b)return;const e=O.current.closest(".message-content");C?na(C,L,0,r).then(t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute("data-has-custom-appendix","")}):e.classList.add("has-appendix-thumb")},[C,L,b,c,r]);const{width:F,height:D,isSmall:B}=l||kt(t),U=Object(J.a)("media-inner",!w&&!d&&"interactive",B&&"small-image",F===D&&"square-image"),H=l?`width: ${F}px; height: ${D}px; left: ${l.x}px; top: ${l.y}px;`:"";return n.a.createElement("div",{id:e,ref:O,className:U,style:H,onClick:w?void 0:R},T&&n.a.createElement("canvas",{ref:E,className:"thumbnail",style:`width: ${F}px; height: ${D}px`}),A&&n.a.createElement("img",{src:C,className:"full-media "+x,width:F,height:D,alt:""}),N&&n.a.createElement("div",{className:"media-loading "+P},n.a.createElement(ra.a,{progress:S,onClick:w?R:void 0})),!C&&!f&&n.a.createElement("i",{className:"icon-download"}),M&&n.a.createElement("span",{className:"message-upload-progress"},Math.round(100*S),"%"))},ia=a(137),la=a(136);function da(e,t){const a=Object(n.q)();a.current=t;const s=Object(n.m)(()=>{e.current&&e.current.pause()},[e]),c=Object(n.m)(()=>{e.current&&a.current&&Object(la.a)(e.current)},[e]);Object(X.a)(s,c)}var ba=a(147),ua=(e,t=!1)=>{const a=Object(n.q)(!1),s=Object(n.q)(!1),c=Object(n.m)(()=>{s.current=!0,t&&e.current&&(a.current||(a.current=!e.current.paused),e.current.pause())},[t,e]),r=Object(n.m)(()=>{t&&e.current&&a.current&&document.body.contains(e.current)&&Object(la.a)(e.current),a.current=!1,s.current=!1},[t,e]),o=Object(n.m)(()=>{Object(g.b)(r)},[r]);document.hasFocus()||c(),Object(ee.a)(c,o)};function ma(){return(ma=Object.assign||function(e){for(var t=1;t{const b=Object(n.q)(null),u=Object(n.q)(null),h=t.content.video,O=h.blobUrl,j=Boolean(O)||Object(m.b)(h),g=Object(ft.b)(b,a),[f,p]=Object(n.r)(s),I=Boolean(f&&g&&o),[v,y]=Object(n.r)(c),C=Object(at.a)(Object(m.D)(t,"pictogram"),!(g&&o),Object(m.C)(t,"pictogram"),o),E=sa(t),{mediaData:w,downloadProgress:M}=Object(ta.a)(Object(m.D)(t,"inline"),!I,Object(m.C)(t,"inline"),o),S=O||w,k=Boolean(j&&g&&S),{isBuffered:N,bufferingHandlers:P}=Object(ia.a)(!s),{isUploading:T,isTransferring:A,transferProgress:R}=Object(m.s)(t,r||M,I&&j&&!N),L=!1===Object(ca.a)(f),{shouldRender:F,transitionClassNames:D}=Object(Z.a)(A,void 0,L),{shouldRenderThumb:B,transitionClassNames:U}=Object(Yt.a)(S,"slow"),[H,G]=Object(n.r)(0),q=Object(n.m)(e=>{G(Math.max(0,e.currentTarget.currentTime-1))},[]),_=Object(m.tb)(t),V=Object(m.qb)(t),{width:$,height:z}=i||Object(et.h)(h,_,V);da(u,Boolean(k&&c)),ua(u,v),Object(ba.a)(u,[k]);const W=Object(n.m)(()=>{T?d&&d(t):j&&!S?p(e=>!e):j&&S&&!v?(y(!0),u.current.play()):l&&l(t.id)},[T,j,S,v,l,d,t]),K=Object(J.a)("media-inner dark",!T&&"interactive"),Q=Object(J.a)("full-media",U),Y=i?`width: ${$}px; height: ${z}px; left: ${i.x}px; top: ${i.y}px;`:"",X=k,ee=!j&&w,te=!j||f&&!v&&!F,ae=j&&!f;return n.a.createElement("div",{ref:b,id:e,className:K,style:Y,onClick:T?void 0:W},(!k||B)&&n.a.createElement("canvas",{ref:E,className:"thumbnail",style:`width: ${$}px; height: ${z}px;`}),C&&n.a.createElement("img",{src:C,className:"thumbnail",style:`width: ${$}px; height: ${z}px;`,alt:""}),X&&n.a.createElement("video",ma({ref:u,className:Q,width:$,height:z,autoPlay:v,muted:!0,loop:!0,playsInline:!0},P,{onTimeUpdate:q}),n.a.createElement("source",{src:S})),ee&&n.a.createElement("img",{src:w,className:"full-media "+U,width:$,height:z,alt:""}),te&&n.a.createElement("i",{className:"icon-large-play"}),F&&n.a.createElement("div",{className:"media-loading "+D},n.a.createElement(ra.a,{progress:R,onClick:T?W:void 0})),ae&&n.a.createElement("i",{className:"icon-download"}),A&&!j?n.a.createElement("span",{className:"message-upload-progress"},Math.round(100*R),"%"):A&&j?n.a.createElement("span",{className:"message-upload-progress"},"..."):n.a.createElement("div",{className:"message-media-duration"},h.isGif?"GIF":Object(x.e)(h.duration-H)))},Oa=a(18);a(224);var ja=Object(s.h)((e,{contact:t})=>({user:Object(o.Gb)(e,t.userId)}),(e,t)=>Object(d.l)(t,["openUserInfo"]))(({contact:e,user:t,openUserInfo:a})=>{const{firstName:s,lastName:c,phoneNumber:r,userId:o}=e,i=Object(n.m)(()=>{a({id:o})},[a,o]);return n.a.createElement("div",{className:Object(J.a)("Contact",Boolean(o)&&"interactive"),onClick:o?i:void 0},n.a.createElement(Gt.a,{size:"large",user:t,text:s||c}),n.a.createElement("div",{className:"contact-info"},n.a.createElement("div",{className:"contact-name"},s," ",c),n.a.createElement("div",{className:"contact-phone"},Object(Oa.c)(r))))}),ga=a(46);var fa=Object(n.h)(({id:e,options:t,selected:a=[],disabled:s,round:c,loadingOptions:r,onChange:o})=>{const[i,l]=Object(n.r)([]),d=Object(n.m)(e=>{const{value:t,checked:a}=e.currentTarget;let s;s=a?[...i,t]:i.filter(e=>e!==t),l(s),o(s)},[o,i]);return n.a.createElement("div",{id:e,className:"radio-group"},t.map(e=>n.a.createElement(ga.a,{label:e.label,subLabel:e.subLabel,value:e.value,checked:-1!==a.indexOf(e.value),disabled:s,round:c,isLoading:r?-1!==r.indexOf(e.value):void 0,onChange:d})))}),pa=a(126),Ia=a(180);a(227);function va(e,t){return t>0?(e/t*100).toFixed():0}var ya=({answer:e,voteResults:t,totalVoters:a,maxVotersCount:s,correctResults:c,shouldAnimate:r})=>{const o=t&&t.find(t=>t.option===e.option),i=0===c.length||-1!==c.indexOf(e.option),l=c.length>0&&i||o&&o.isChosen,d=o?va(o.votersCount,a||0):0,[b,u]=Object(n.r)(r?0:d),m=Object(n.q)(null),h=o?va(o.votersCount,s||0):0,O=b{r&&u(d)},[r,d]),Object(n.n)(()=>{const e=m.current;if(e&&r){const t=e.firstElementChild,a=O?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",a):e.innerHTML=`\n \n \n `}},[O,r]),!t||!o)return;const j=`width: ${h}%; transform:scaleX(${O?0:1})`;return n.a.createElement("div",{className:"PollOption",dir:"ltr"},n.a.createElement("div",{className:"poll-option-share "+("100"===d?"limit-width":"")},d,"%",l&&n.a.createElement("span",{className:Object(J.a)("poll-option-chosen",!i&&"wrong",r&&"animate")},n.a.createElement("i",{className:i?"icon-check":"icon-close"}))),n.a.createElement("div",{className:"poll-option-right"},n.a.createElement("div",{className:"poll-option-text",dir:"auto"},Object(tt.a)(e.text)),n.a.createElement("div",{className:Object(J.a)("poll-option-answer",l&&!i&&"wrong")},n.a.createElement("div",{className:"poll-option-corner",ref:m}),n.a.createElement("div",{className:"poll-option-line",style:j}))))};a(228);var Ca=Object(n.h)(Object(s.h)((e,{poll:t})=>{const{recentVoterIds:a}=t.results,{byId:s}=e.users;return a&&0!==a.length?{recentVoterIds:a,usersById:s}:{}},(e,t)=>Object(d.l)(t,["loadMessage","openPollResults"]))(({message:e,poll:t,recentVoterIds:a,usersById:s,loadMessage:c,onSendVote:r,openPollResults:o})=>{const{id:i,chatId:l}=e,{summary:d,results:b}=t,[u,m]=Object(n.r)(!1),[h,O]=Object(n.r)([]),[j,g]=Object(n.r)(!1),[f,p]=Object(n.r)(!1),[I,v]=Object(n.r)(!d.closed&&d.closeDate&&d.closeDate>0?Math.min(d.closeDate-Math.floor(Date.now()/1e3),d.closePeriod):0),y=Object(n.q)(null),{results:C,totalVoters:E}=b,w=C&&C.some(e=>e.isChosen),M=!d.closed&&!w,S=!M&&d.isPublic&&Number(b.totalVoters)>0,k=M&&d.multipleChoice,N=C?Math.max(...C.map(e=>e.votersCount)):E,P=C?C.reduce((e,t)=>(t.isCorrect&&e.push(t.option),e),[]):[],T=d.answers.map(e=>({label:e.text,value:e.option,hidden:Boolean(d.quiz&&d.closePeriod&&I<=0)}));Object(n.n)(()=>{u&&t.results.results&&t.results.results.some(e=>e.isChosen)&&m(!1)},[u,t.results.results]),Object(n.n)(()=>{I>0&&setTimeout(()=>v(I-1),1e3);const e=y.current;if(e){const t=12*Math.PI,a=e.lastElementChild,s=e.firstElementChild;if(I<=5&&e.classList.add("hurry-up"),a&&s){const e=(d.closePeriod-I)/d.closePeriod*t;s.textContent=Object(x.e)(I),a.firstElementChild.setAttribute("stroke-dashoffset","-"+e)}else e.innerHTML=`\n ${Object(x.e)(I)}\n \n \n `}},[I,d.closePeriod]),Object(n.n)(()=>{d.quiz&&(I<=0||w&&!d.closed)&&c({chatId:l,messageId:i})},[l,I,w,c,i,d.closed,d.quiz]),Object(n.n)(()=>{let e;return d.quiz&&!d.closed&&d.closePeriod&&d.closePeriod>0&&(e=window.setTimeout(()=>{c({chatId:l,messageId:i})},1e3*d.closePeriod)),()=>{e&&window.clearTimeout(e)}},[M,l,c,i,d.closePeriod,d.closed,d.quiz]);const A=Object(n.p)(()=>a?a.reduce((e,t)=>{const a=s[t];return a&&e.push(a),e},[]):[],[s,a]),R=Object(n.m)(e=>{O([e]),m(!0),p(!0),r([e])},[r]),L=Object(n.m)(e=>{O(e)},[]),F=Object(n.m)(()=>{m(!0),p(!0),r(h)},[r,h]),D=Object(n.m)(()=>{o({chatId:l,messageId:i})},[l,i,o]),B=Object(n.m)(()=>{g(!0)},[]),U=Object(n.m)(()=>{g(!1),p(!1)},[]);Object(n.n)(()=>{if(f&&w&&d.quiz&&b.results&&t.results.solution){b.results.find(e=>e.isChosen&&e.isCorrect)||g(!0)}},[w,f,b.results,d.quiz,t.results.solution]);const H=Object(ce.a)();return n.a.createElement("div",{className:"Poll",dir:H.isRtl?"auto":"ltr"},j&&t.results.solution&&n.a.createElement(Ia.a,{message:Object(wt.b)(t.results.solution,t.results.solutionEntities),duration:5e3,onDismiss:U,containerId:"#middle-column-portals"}),n.a.createElement("div",{className:"poll-question"},Object(tt.a)(d.question)),n.a.createElement("div",{className:"poll-type"},H(function(e){if(void 0===e.isPublic)return" ";if(e.quiz)return e.isPublic?"QuizPoll":"AnonymousQuizPoll";if(e.closed)return"FinalResults";return e.isPublic?"PublicPoll":"AnonymousPoll"}(d)),A.length>0&&n.a.createElement("div",{className:"poll-recent-voters"},A.map(e=>n.a.createElement(Gt.a,{size:"micro",user:e}))),I>0&&M&&n.a.createElement("div",{ref:y,className:"poll-countdown"}),d.quiz&&t.results.solution&&!M&&n.a.createElement(oe.a,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:j,onClick:B,ariaLabel:"Show Solution"},n.a.createElement("i",{className:"icon-lamp"}))),M&&n.a.createElement("div",{className:"poll-answers"},k?n.a.createElement(fa,{options:T,onChange:L,disabled:e.isScheduled||u,loadingOptions:u?h:void 0,round:!0}):n.a.createElement(pa.a,{name:"poll-"+i,options:T,onChange:R,disabled:e.isScheduled||u,loadingOption:u?h[0]:void 0})),!M&&n.a.createElement("div",{className:"poll-results"},d.answers.map((function(e){return n.a.createElement(ya,{key:e.option,shouldAnimate:f,answer:e,voteResults:C,totalVoters:E,maxVotersCount:N,correctResults:P})}))),!S&&!k&&n.a.createElement("div",{className:"poll-voters-count"},function(e,t,a){if(!a)return e(t?"Chat.Quiz.TotalVotesEmpty":"Chat.Poll.TotalVotesResultEmpty");return e(t?"Answer":"Vote",a,"i")}(H,d.quiz,b.totalVoters)),k&&n.a.createElement(oe.a,{isText:!0,disabled:0===h.length,size:"tiny",onClick:F},H("PollSubmitVotes")),S&&n.a.createElement(oe.a,{isText:!0,size:"tiny",onClick:D},H("PollViewResults")))})),Ea=a(39),wa=a(57);a(229);var Ma=Object(n.h)(({message:e,observeIntersection:t,shouldAutoLoad:a,inPreview:s,onMediaClick:c,onCancelMediaTransfer:r})=>{const o=Object(m.Q)(e);let i=!1;if(o&&o.photo){const{width:t,height:a}=kt(e);i=t===a}const l=Object(n.m)(()=>{c()},[c]);if(!o)return;const{siteName:d,url:b,displayUrl:u,title:h,description:O,photo:j}=o,g=j&&c&&!i&&!o.hasDocument,f=Object(Ea.a)(O,170),p=Object(J.a)("WebPage",j?i&&"with-square-photo":!s&&"without-photo");return n.a.createElement("div",{className:p,"data-initial":(d||u)[0],dir:"auto"},j&&n.a.createElement(oa,{message:e,observeIntersection:t,shouldAutoLoad:a,size:i?"pictogram":"inline",nonInteractive:!g,onClick:g?l:void 0,onCancelUpload:r}),n.a.createElement("div",{className:"WebPage-text"},n.a.createElement(wa.a,{className:"site-name",url:b,text:d||u}),!s&&h&&n.a.createElement("p",{className:"site-title"},Object(tt.a)(h)),f&&n.a.createElement("p",{className:"site-description"},Object(tt.a)(f,["emoji","br"]))))});a(230);var Sa=Object(n.h)(({message:e})=>{const t=Object(m.z)(e),{title:a,text:s,description:c,photoUrl:r}=t;return n.a.createElement("div",{className:"Invoice"},a&&n.a.createElement("p",{className:"title"},Object(tt.a)(a)),s&&n.a.createElement("p",null,Object(tt.a)(s,["emoji","br"])),n.a.createElement("div",{className:"description "+(r?"has-image":"")},r&&n.a.createElement("img",{className:"invoice-image",src:r,alt:""}),c&&n.a.createElement("p",{className:"description-text"},Object(tt.a)(c,["emoji","br"]))))});function ka(e){return Object(n.h)(Object(s.h)((e,t)=>{const{message:a}=t;return{isInSelectMode:Object(o.S)(e),isSelected:Object(o.V)(e,a.id)}},(e,t)=>Object(d.l)(t,["toggleMessageSelection"]))(t=>{const{isInSelectMode:a,isSelected:s,message:c,toggleMessageSelection:r,dimensions:o}=t,i=Object(n.m)(e=>{e.stopPropagation(),r({messageId:c.id,withShift:e&&e.shiftKey})},[r,c]),l=Object(n.p)(()=>({...t,isInSelectMode:a,isSelected:s,dimensions:{...t.dimensions,x:0,y:0},onClick:a?void 0:t.onClick}),[t,a,s]);return n.a.createElement("div",{className:Object(J.a)("album-item-select-wrapper",s&&"is-selected"),style:o?`left: ${o.x}px; top: ${o.y}px;`:"",onClick:a?i:void 0},a&&n.a.createElement("div",{className:"message-select-control"},s&&n.a.createElement("i",{className:"icon-select"})),n.a.createElement(e,l))}))}a(231);const Na=ka(oa),Pa=ka(ha);var Ta=Object(s.h)(e=>({uploadsById:e.fileUploads.byMessageLocalId}),(e,t)=>Object(d.l)(t,["cancelSendingMessage"]))(({album:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,hasCustomAppendix:c,lastSyncTime:r,isOwn:o,albumLayout:i,onMediaClick:l,uploadsById:d,cancelSendingMessage:b})=>{const u=e.messages.length,h=Object(n.m)(e=>{b({chatId:e.chatId,messageId:e.id})},[b]);const{width:O,height:j}=i.containerStyle;return n.a.createElement("div",{className:"Album",style:`width: ${O}px; height: ${j}px;`},e.messages.map((function(e,b){const{photo:O,video:j}=Object(m.v)(e),g=d[e.previousLocalId||e.id],f=g?g.progress:void 0,{dimensions:p,sides:I}=i.layout[b];if(O){const s=c&&(o?b===u-1:Boolean(I&xt&&I&At));return n.a.createElement(Na,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAffectAppendix:s,uploadProgress:f,dimensions:p,onClick:l,onCancelUpload:h})}if(j)return n.a.createElement(Pa,{id:"album-media-"+e.id,message:e,observeIntersection:t,shouldAutoLoad:a,shouldAutoPlay:s,uploadProgress:f,lastSyncTime:r,dimensions:p,onClick:l,onCancelUpload:h})})))});a(232);function Aa(){return(Aa=Object.assign||function(e){for(var t=1;t{const r=Object(n.q)(null),o=Object(n.q)(null),i=Object(n.q)(null),l=e.content.video,d=Object(ft.b)(r,t),[b,u]=Object(n.r)(a&&s),h=Boolean(b&&d&&c),{mediaData:O,downloadProgress:j}=Object(ta.a)(Object(m.D)(e,"inline"),!h,Object(m.C)(e,"inline"),c),g=sa(e,O),{isBuffered:f,bufferingHandlers:p}=Object(ia.a)(),I=b&&!f,v=!1===Object(ca.a)(b),{shouldRender:y,transitionClassNames:C}=Object(Z.a)(I||!f,void 0,v),{shouldRenderThumb:E,transitionClassNames:w}=Object(Yt.a)(O,"slow"),[M,S]=Object(n.r)(!1),[k,N]=Object(n.r)(0);Object(n.n)(()=>{if(!M)return;const e=188*Math.PI,t=e-k*e,a=i.current,s=o.current,c=s.firstElementChild;c?c.firstElementChild.setAttribute("stroke-dashoffset",t.toString()):s.innerHTML=`\n \n `,N(a.currentTime/a.duration)},[M,k]);const P=Boolean(O&&d),T=()=>{S(!1),N(0),Object(la.a)(i.current),requestAnimationFrame(()=>{o.current.innerHTML=""})},A=(R=T,()=>{xa&&xa(),xa=R});var R;Object(n.n)(()=>{i.current&&(P?Object(la.a)(i.current):i.current.pause())},[P]),da(i,P),ua(i,Boolean(O)),Object(ba.a)(i,[O]);const L=Object(n.m)(()=>{if(!O)return void u(e=>!e);const e=i.current;M?e.paused?Object(la.a)(e):e.pause():(A(),e.currentTime=0,S(!0))},[A,M,O]),F=Object(n.m)(e=>{const t=e.currentTarget;N(t.currentTime/t.duration)},[]),D=Object(J.a)("full-media",w);return n.a.createElement("div",{ref:r,className:"RoundVideo media-inner",onClick:L},E&&n.a.createElement("div",{className:"thumbnail-wrapper"},n.a.createElement("canvas",{ref:g,className:"thumbnail",style:`width: ${et.d}px; height: ${et.d}px`})),O&&n.a.createElement("div",{className:"video-wrapper"},n.a.createElement("video",Aa({ref:i,className:D,width:et.d,height:et.d,autoPlay:!0,muted:!M,loop:!M,playsInline:!0,onEnded:M?T:void 0},p,{onTimeUpdate:M?F:void 0}),n.a.createElement("source",{src:O}))),n.a.createElement("div",{className:"progress",ref:o}),y&&n.a.createElement("div",{className:"media-loading "+C},n.a.createElement(ra.a,{progress:j})),!O&&!b&&n.a.createElement("i",{className:"icon-large-play"}),n.a.createElement("div",{className:"message-media-duration"},M?Object(x.e)(i.current.currentTime):Object(x.e)(l.duration),(!M||i.current.paused)&&n.a.createElement("i",{className:"icon-muted-chat"})))};a(233);var La=({message:e,onClick:t})=>n.a.createElement("div",{className:"InlineButtons"},e.inlineButtons.map(e=>n.a.createElement("div",{className:"row"},e.map(e=>n.a.createElement(oe.a,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>t({button:e})},e.text,"url"===e.type&&n.a.createElement("i",{className:"icon-arrow-right"}))))));a(234);var Fa=Object(n.h)(Object(s.h)((e,{message:t})=>{const{threadId:a,chatId:s}=t.threadInfo,c=Object(o.Cb)(e,s,a)||t.threadInfo,{byId:n}=e.users,{byId:r}=e.chats;return{threadInfo:c,usersById:n,chatsById:r}},(e,t)=>Object(d.l)(t,["openChat"]))(({disabled:e,threadInfo:t,usersById:a,chatsById:s,openChat:c})=>{const r=Object(ce.a)(),{threadId:o,chatId:i,messagesCount:l,lastMessageId:d,lastReadInboxMessageId:b,recentReplierIds:u}=t,h=Object(n.m)(()=>{c({id:i,threadId:o})},[c,i,o]);if(void 0===l)return;const O=u&&u.map(e=>Object(m.lb)(e)?a[e]:s[e]).filter(Boolean);const j=Boolean(b&&d&&b0&&n.a.createElement("div",{className:"recent-repliers",dir:r.isRtl?"rtl":"ltr"},O.map(e=>n.a.createElement(Gt.a,{key:e.id,size:"small",user:Object(m.lb)(e.id)?e:void 0,chat:Object(m.lb)(e.id)?void 0:e}))),n.a.createElement("div",{className:"label",dir:"auto"},l?r("Comments",l,"i"):r("LeaveAComment")),n.a.createElement("i",{className:"icon-next"}))}));a(235);function Da(e){const t=Ua(e.currentTarget);t&&t.setAttribute("data-is-document-group-hover","")}function Ba(e){const t=Ua(e.currentTarget);t&&t.removeAttribute("data-is-document-group-hover")}function Ua(e){let t=e;do{t=t.nextElementSibling}while(t&&!t.classList.contains("last-in-document-group"));return t}var Ha=Object(n.h)(Object(s.h)((e,t)=>{const{focusedMessage:a,forwardMessages:s,lastSyncTime:c}=e,{message:n,album:r,withSenderName:i,withAvatar:l,threadId:d,messageListType:b}=t,{id:u,chatId:h,viaBotId:O,replyToMessageId:j,isOutgoing:g}=n,f=Object(o.f)(e,h),p=Object(o.P)(e,h),I=f&&Object(m.jb)(f),v=!p&&Object(m.eb)(n),y=i||l||v?Object(o.tb)(e,n):void 0,C=Object(o.K)(e,n),E=O?Object(o.Gb)(e,O):void 0,w=d?Object(o.Eb)(e,h,d):void 0,M=n.id===w,S=j===w,k=j&&!S?Object(o.k)(e,h,j):void 0,N=k&&Object(o.tb)(e,k),P=Object(o.Fb)(e,n),T="thread"===b&&(r?r.messages.some(t=>Object(o.U)(e,t)):Object(o.U)(e,n)),{direction:A,noHighlight:x}=T&&a||{},R=s.messageIds&&s.messageIds.includes(u),{query:L}=Object(o.A)(e)||{},F=Object(m.L)(n);let D;return D=r&&r.messages?r.messages.every(({id:t})=>Object(o.V)(e,t)):Object(o.V)(e,u),{forceSenderName:v,sender:y,originSender:C,botSender:E,shouldHideReply:S,isThreadTop:M,replyMessage:k,replyMessageSender:N,...g&&{outgoingStatus:Object(o.fb)(e,n,"scheduled"===b)},..."number"==typeof P&&{uploadProgress:P},isFocused:T,...T&&{focusDirection:A,noFocusHighlight:x},isForwarding:R,isChatWithSelf:p,isChannel:I,lastSyncTime:c,highlight:L,isSingleEmoji:Boolean(F),animatedEmoji:F?Object(o.c)(e,F):void 0,isInSelectMode:Object(o.S)(e),isSelected:D,isGroupSelected:!!n.groupedId&&!n.isInAlbum&&Object(o.Q)(e,h,n.groupedId),threadId:d,isPinnedList:"pinned"===b,shouldAutoLoadMedia:f?Object(o.ub)(e,n,f,y):void 0,shouldAutoPlayMedia:Object(o.vb)(e,n),shouldLoopStickers:Object(o.wb)(e)}},(e,t)=>Object(d.l)(t,["focusMessage","openMediaViewer","openAudioPlayer","cancelSendingMessage","openUserInfo","openChat","markMessagesRead","sendPollVote","toggleMessageSelection","setReplyingToId","openForwardMenu","clickInlineButton"]))(({message:e,observeIntersectionForBottom:t,observeIntersectionForMedia:a,observeIntersectionForAnimatedStickers:s,album:c,withAvatar:r,withSenderName:o,noComments:d,appearanceOrder:b,isFirstInGroup:u,isLastInGroup:h,isFirstInDocumentGroup:O,isLastInDocumentGroup:j,isLastInList:g,forceSenderName:f,sender:p,originSender:I,botSender:v,isThreadTop:y,shouldHideReply:C,replyMessage:E,replyMessageSender:w,outgoingStatus:M,uploadProgress:S,isFocused:k,focusDirection:N,noFocusHighlight:P,isForwarding:T,isChatWithSelf:A,isChannel:x,lastSyncTime:R,highlight:L,animatedEmoji:F,isInSelectMode:D,isSelected:B,isGroupSelected:U,threadId:H,messageListType:G,isPinnedList:q,shouldAutoLoadMedia:_,shouldAutoPlayMedia:V,shouldLoopStickers:$,focusMessage:z,openMediaViewer:W,openAudioPlayer:K,openUserInfo:Q,openChat:Y,cancelSendingMessage:X,markMessagesRead:ee,sendPollVote:te,toggleMessageSelection:ae,setReplyingToId:se,openForwardMenu:ne,clickInlineButton:re})=>{const ie=Object(n.q)(null),le=Object(n.q)(null),de=Object(n.q)(null);Object(ft.c)(le,t);const{width:be}=_e(),{isContextMenuOpen:ue,contextMenuPosition:me,handleBeforeContextMenu:he,handleContextMenu:Oe,handleContextMenuClose:je,handleContextMenuHide:ge}=Object(Et.a)(ie,!1,!0),fe=b<=0,[pe,Ie]=Object(ot.a)(fe);Object(n.n)(()=>{fe||setTimeout(Ie,10*b)},[b,Ie,fe]);const{transitionClassNames:ve}=Object(Z.a)(pe,void 0,fe,!1),{chatId:ye,id:Ce,threadInfo:Ee}=e,we=Object(m.tb)(e),Me="scheduled"===G||e.isScheduled,Se=Object(m.ub)(e)&&!C,ke=Boolean(Ee)&&"thread"===G,{forwardInfo:Ne,viaBotId:Pe}=e,Te=Ne&&!A&&!Ne.isLinkedChannelPost,Ae=!!e.groupedId&&!e.isInAlbum,xe=Boolean(c)&&c.messages.length>1,{text:Re,photo:Le,video:Fe,audio:De,voice:Be,document:Ue,sticker:He,contact:Ge,poll:qe,webPage:Ve,invoice:$e}=Object(m.v)(e),ze=Object(m.x)(e),Ke=Object(wt.a)(e,L,Mt(ze)),Qe=void 0!==me,Ye=Object(J.a)("Message message-list-item",u&&"first-in-group",h&&"last-in-group",O&&"first-in-document-group",j&&"last-in-document-group",g&&"last-in-list",we&&"own",Boolean(e.views)&&"has-views",e.isEdited&&"was-edited",Se&&"has-reply",Qe&&"has-menu-open",k&&!P&&"focused",T&&"is-forwarding",e.isDeleting&&"is-deleting",Ae&&"is-in-document-group",xe&&"is-album",e.hasUnreadMention&&"has-unread-mention",B&&"is-selected",D&&"is-in-selection-mode",y&&"is-thread-top",Boolean(e.inlineButtons)&&"has-inline-buttons",ve),Xe=function(e,{hasReply:t,customShape:a,isLastInGroup:s,asForwarded:c,hasThread:n,forceSenderName:r,hasComments:o}={}){const{text:i,photo:l,video:d,audio:b,voice:u,document:h,poll:O,webPage:j,contact:g}=Object(m.v)(e),f=["message-content"],p=(l||d)&&!i,I=Boolean(e.viaBotId);return Mt(a)?f.push("emoji-only emoji-only-"+a):i&&f.push("text"),a&&(f.push("custom-shape"),d&&d.isRound&&f.push("round"),o&&f.push("has-comments")),l||d?f.push("media"):b?f.push("audio"):u?f.push("voice"):h?f.push("document"):g?f.push("contact"):O?f.push("poll"):j&&(f.push("web-page"),j.photo&&f.push("media")),c&&!a&&f.push("is-forwarded"),t&&f.push("is-reply"),n&&f.push("has-replies"),I&&f.push("is-via-bot"),r&&f.push("force-sender-name"),a||(f.push("has-shadow"),(t||c||!p||I||r)&&f.push("has-solid-background"),!s||!l&&p||f.push("has-appendix")),f.join(" ")}(e,{hasReply:Se,customShape:ze,isLastInGroup:h,asForwarded:Te,hasThread:ke,forceSenderName:f,hasComments:e.threadInfo&&e.threadInfo.messagesCount>0}),Je=!Ne||!A&&p?p:I,Ze=Ne?I:p,at=x&&e.adminTitle||Ne&&!Te&&Ne.adminTitle||void 0,st=e.threadInfo&&(!Ae||j)&&"thread"===G&&!d,ct=Xe.includes("has-appendix");Object(We.a)(ye,Se?e.replyToMessageId:void 0,E,e.id),Ht(ie,ye,k,N,P),Object(n.o)(()=>{de.current&&(de.current.innerHTML=we?'':'')},[we,ct]);const nt=Object(n.m)(t=>{t.stopPropagation(),ae({messageId:Ce,groupedId:e.groupedId})},[Ce,e.groupedId,ae]),rt=Object(n.m)(e=>{const t=xe&&c&&c.messages?{messageId:Ce,childMessageIds:c.messages.map(({id:e})=>e),withShift:e&&e.shiftKey}:{messageId:Ce,withShift:e&&e.shiftKey};ae(t)},[ae,Ce,xe,c]),it=Object(n.m)(()=>{se({messageId:Ce})},[se,Ce]),lt=Object(n.m)(e=>{e.stopPropagation()},[]),dt=Object(n.m)(()=>{Je&&(Object(m.lb)(Je.id)?Q({id:Je.id}):Y({id:Je.id}))},[Je,Q,Y]),bt=Object(n.m)(()=>{Ze&&(Object(m.lb)(Ze.id)?Q({id:Ze.id}):Y({id:Ze.id}))},[Ze,Q,Y]),ut=Object(n.m)(()=>{v&&Q({id:v.id})},[v,Q]),mt=Object(n.m)(()=>{z({chatId:ye,threadId:H,messageId:e.replyToMessageId})},[z,ye,H,e.replyToMessageId]),ht=Object(n.m)(()=>{W({chatId:ye,threadId:H,messageId:Ce,origin:Me?l.h.ScheduledInline:l.h.Inline})},[ye,H,Ce,W,Me]),Ot=Object(n.m)(()=>{K({chatId:ye,messageId:Ce})},[ye,Ce,K]),jt=Object(n.m)(e=>{W({chatId:ye,threadId:H,messageId:e,origin:Me?l.h.ScheduledAlbum:l.h.Album})},[ye,H,W,Me]),gt=Object(n.m)(()=>{ee({messageIds:[Ce]})},[Ce,ee]),pt=Object(n.m)(()=>{X({chatId:ye,messageId:Ce})},[X,ye,Ce]),It=Object(n.m)(e=>{te({chatId:ye,messageId:Ce,options:e})},[ye,Ce,te]),vt=Object(n.m)(()=>{ne({fromChatId:ye,groupedId:e.groupedId})},[ne,ye,e.groupedId]),yt=Object(n.m)(()=>{if(c&&c.messages){const e=c.messages.map(({id:e})=>e);ne({fromChatId:ye,messageIds:e})}else ne({fromChatId:ye,messageIds:[Ce]})},[c,ne,ye,Ce]),Ct=Object(n.m)(()=>{z({chatId:ye,threadId:i.MAIN_THREAD_ID,messageId:Ce})},[z,ye,Ce]),Nt=Object(n.m)(()=>{z(Ae?{chatId:Ne.fromChatId,groupedId:e.groupedId,groupedChatId:ye}:{chatId:Ne.fromChatId,messageId:Ne.fromMessageId})},[z,Ne,e,ye,Ae]),Pt=Object(ce.a)();let Tt,At="",xt=!1;const Rt=Object(n.p)(()=>xe?Dt(we,Boolean(Te),c,be):void 0,[xe,be,we,Te,c]),Lt=Te?28:0;if(xe||!Le&&!Fe)Rt&&(Tt=Math.max(St(Boolean(Re),st),Rt.containerStyle.width),Tt-Rt.containerStyle.width>18&&(xt=!0));else{let t;Le?t=kt(e).width:Fe&&(t=Fe.isRound?et.d:kt(e).width),t&&(Tt=Math.max(St(Boolean(Re),st),t),Tt-t>18&&(xt=!0))}Tt&&(At=`width: ${Tt+Lt}px`);const Ft=Object(n.p)(()=>at?Ut(at):void 0,[at]),Bt=!(Qe||D||T)&&(!Ae||j),qt=Bt&&x&&!Me,Vt=Bt&&(Ne&&(Ne.isChannelPost||A&&!we)&&Ne.fromMessageId||q);return n.a.createElement("div",{ref:ie,id:"message"+Ce,className:Ye,style:Ft?`--meta-safe-author-width: ${Ft}px`:void 0,"data-message-id":Ce,onClick:D?rt:void 0,onDoubleClick:D?void 0:it,onMouseDown:D?void 0:he,onContextMenu:D?void 0:Oe,onMouseEnter:Ae&&!j?Da:void 0,onMouseLeave:Ae&&!j?Ba:void 0},n.a.createElement("div",{ref:le,className:"bottom-marker","data-message-id":Ce,"data-last-message-id":c?c.messages[c.messages.length-1].id:void 0,"data-has-unread-mention":e.hasUnreadMention}),!Ae&&n.a.createElement("div",{className:"message-select-control"},B&&n.a.createElement("i",{className:"icon-select"})),j&&n.a.createElement("div",{className:Object(J.a)("message-select-control group-select",U&&"is-selected"),onClick:nt},U&&n.a.createElement("i",{className:"icon-select"})),r&&function(){const e=Je&&Object(m.lb)(Je.id),t=Je&&e?Je:void 0,a=Je&&!e?Je:void 0,s=!Je&&Ne?Ne.hiddenUserName:void 0;return n.a.createElement(Gt.a,{size:"small",user:t,chat:a,text:s,lastSyncTime:R,onClick:t||a?dt:void 0})}(),n.a.createElement("div",{className:"message-content-wrapper",onClick:D&&Ae?rt:void 0},n.a.createElement("div",{className:Xe,style:At,dir:"auto"},ct&&n.a.createElement("div",{className:"svg-appendix",ref:de}),Te&&!ze&&(!Ae||O)&&n.a.createElement("div",{className:"message-title"},Pt("ForwardedMessage")),function(){const t=Object(J.a)("content-inner",Te&&!ze&&"forwarded-message",Se&&"reply-message",xt&&"no-media-corners"),r=h&&!Ke&&!Te&&!ke,i=!Ve&&!F&&Ke;return n.a.createElement("div",{className:t,onDoubleClick:lt,dir:"auto"},function(){if(ze||!(o&&!Le&&!Fe||Te||Pe||f)||Ae&&!O)return;let t,a;Ze?(t=Object(m.V)(Pt,Ze),Te||(a="color-"+Object(m.X)(Ze))):Ne&&Ne.hiddenUserName&&(t=Ne.hiddenUserName);return n.a.createElement("div",{className:"message-title",dir:"ltr"},t?n.a.createElement("span",{className:Object(J.a)(Ze&&"interactive",a),onClick:Ze?bt:void 0,dir:"auto"},Object(tt.a)(t)):v?void 0:" ",v&&n.a.createElement(n.a.Fragment,null,n.a.createElement("span",{className:"via"},Pt("ViaBot")),n.a.createElement("span",{className:"interactive",onClick:ut},Object(tt.a)("@"+v.username))),Ne&&Ne.isLinkedChannelPost?n.a.createElement("span",{className:"admin-title",dir:"auto"},Pt("DiscussChannel")):e.adminTitle&&!x?n.a.createElement("span",{className:"admin-title",dir:"auto"},e.adminTitle):void 0)}(),Se&&n.a.createElement($t,{message:E,sender:w,observeIntersection:a,onClick:mt}),He&&n.a.createElement(Zt,{message:e,observeIntersection:a,observeIntersectionForPlaying:s,shouldLoop:$,lastSyncTime:R}),F&&n.a.createElement(ea.a,{isInline:!0,sticker:F,observeIntersection:a,lastSyncTime:R}),xe&&n.a.createElement(Ta,{album:c,albumLayout:Rt,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:V,isOwn:we,hasCustomAppendix:r,lastSyncTime:R,onMediaClick:jt}),!xe&&Le&&n.a.createElement(oa,{message:e,observeIntersection:a,shouldAutoLoad:_,uploadProgress:S,shouldAffectAppendix:r,onClick:ht,onCancelUpload:pt}),!xe&&Fe&&Fe.isRound&&n.a.createElement(Ra,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:V,lastSyncTime:R}),!xe&&Fe&&!Fe.isRound&&n.a.createElement(ha,{message:e,observeIntersection:a,shouldAutoLoad:_,shouldAutoPlay:V,uploadProgress:S,lastSyncTime:R,onClick:ht,onCancelUpload:pt}),(De||Be)&&n.a.createElement(Wt.a,{message:e,uploadProgress:S,lastSyncTime:R,isSelectable:Ae,isSelected:B,onPlay:Ot,onReadMedia:!Be||we&&!A?void 0:gt,onCancelUpload:pt}),Ue&&n.a.createElement(zt.a,{message:e,observeIntersection:a,uploadProgress:S,isSelectable:Ae,isSelected:B,onCancelUpload:pt}),Ge&&n.a.createElement(ja,{contact:Ge}),qe&&n.a.createElement(Ca,{message:e,poll:qe,onSendVote:It}),!F&&Ke&&n.a.createElement("p",{className:"text-content "+(i?"with-meta":""),dir:"auto"},Ke,i&&n.a.createElement(Qt,{message:e,outgoingStatus:M,signature:at,onClick:rt})),Ve&&n.a.createElement(Ma,{message:e,observeIntersection:a,shouldAutoLoad:_,onMediaClick:ht,onCancelMediaTransfer:pt}),$e&&n.a.createElement(Sa,{message:e}))}(),(!Ae||j)&&!(!Ve&&!F&&Ke)&&n.a.createElement(Qt,{message:e,outgoingStatus:M,signature:at,onClick:rt}),qt?n.a.createElement(oe.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:Pt("lng_context_forward_msg"),onClick:j?vt:yt},n.a.createElement("i",{className:"icon-share-filled"})):Vt?n.a.createElement(oe.a,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:q?Ct:Nt},n.a.createElement("i",{className:"icon-arrow-right"})):void 0,st&&n.a.createElement(Fa,{message:e,disabled:d}),Xe.includes("has-appendix")&&n.a.createElement("div",{className:"svg-appendix",ref:de})),e.inlineButtons&&n.a.createElement(La,{message:e,onClick:re})),me&&n.a.createElement(_t,{isOpen:ue,anchor:me,message:e,album:c,messageListType:G,onClose:je,onCloseAnimationEnd:ge}))}));a(236);const Ga=h.b?1e3:350,qa=h.g?300:500,_a=Object(g.a)(e=>e(),200,!1);var Va=Object(n.h)(Object(s.h)((e,{chatId:t,threadId:a,type:s})=>{const c=Object(o.f)(e,t);if(!c)return{};const n=Object(o.x)(e,t,a,s),r="scheduled"===s?Object(o.qb)(e,t):Object(o.m)(e,t),l=Object(o.Eb)(e,t,a);if(a!==i.MAIN_THREAD_ID&&!(r&&l&&r[l]))return{};const{isRestricted:d,restrictionReason:b,lastMessage:u}=c,h=Object(o.I)(e,t),O=a===i.MAIN_THREAD_ID&&!n&&!c.unreadCount&&!h&&u&&!u.groupedId;let j;if(Object(o.L)(e,t)){const a=Object(o.g)(e,t);j=a.fullInfo?a.fullInfo.botDescription||"NoMessages":"Updating bot info..."}return{isChatLoaded:!0,isRestricted:d,restrictionReason:b,isChannelChat:Object(m.jb)(c),isChatWithSelf:Object(o.P)(e,t),messageIds:n,messagesById:r,firstUnreadId:Object(o.H)(e,t,a),isViewportNewest:"thread"!==s||Object(o.X)(e,t,a),threadFirstMessageId:Object(o.G)(e,t,a),focusingId:h,isSelectModeActive:Object(o.S)(e),animationLevel:e.settings.byKey.animationLevel,...O&&{lastMessage:u},botDescription:j,threadTopMessageId:l,hasLinkedChat:c.fullInfo&&"linkedChatId"in c.fullInfo?Boolean(c.fullInfo.linkedChatId):void 0}},(e,t)=>Object(d.l)(t,["loadViewportMessages","markMessageListRead","markMessagesRead","setScrollOffset"]))(({chatId:e,threadId:t,type:a,hasTools:r,onFabToggle:i,onNotchToggle:b,isChatLoaded:u,isChannelChat:h,canPost:O,isChatWithSelf:j,messageIds:f,messagesById:p,firstUnreadId:I,isViewportNewest:v,threadFirstMessageId:y,isRestricted:C,restrictionReason:E,focusingId:w,isSelectModeActive:M,animationLevel:S,loadViewportMessages:k,markMessageListRead:N,markMessagesRead:P,setScrollOffset:T,lastMessage:A,botDescription:R,threadTopMessageId:L,hasLinkedChat:F})=>{const D=Object(n.q)(null),B=Object(n.q)("thread"===a&&Object(o.rb)(Object(s.e)(),e,t)||0),U=Object(n.q)(),H=Object(n.q)(),G=Object(n.q)(),q=Object(n.q)(),_=Object(n.q)(),V=Object(n.q)(),$=Object(n.q)(!1),z=Object(n.q)(!f),[W,K]=Object(n.r)(),[Q,Y]=Object(n.r)(Boolean(w)),Z=Boolean(f);Object(je.a)(()=>{Z&&Object(g.d)(()=>{z.current=!1})},[Z]),Object(je.a)(()=>{_.current=I,q.current||(q.current=I)},[I]);const{observe:ee,freeze:te,unfreeze:ae}=Object(ft.a)({rootRef:D,throttleMs:Ga,margin:qa}),{observe:se,freeze:ne,unfreeze:re}=Object(ft.a)({rootRef:D},e=>{if("thread"!==a)return;let t=0;const s=[];e.forEach(e=>{const{isIntersecting:a,target:c}=e;if(!a)return;const{dataset:n}=c,r=Number(n.lastMessageId||n.messageId);r>t&&(t=r),n.hasUnreadMention&&s.push(r)}),_.current&&t>=_.current&&N({maxId:t}),s.length&&P({messageIds:s})});Object(je.a)(()=>{V.current=w,w?(te(),ne()):(re(),ae())},[w]);const{observe:oe}=Object(ft.a)({rootRef:D,throttleMs:Ga});Object(n.n)(()=>{w?Y(!0):setTimeout(()=>{Y(!1)},200)},[w]);const ie=Object(n.p)(()=>{if(!f||!p)return;const e=!L||f[0]&&y!==f[0]?f:[L,...f];if(!e.length)return;const t=e.map(e=>p[e]);return gt(Object(d.k)(t,["date","id"]),q.current)},[f,p,y,L]),[le,de,be]=Object(n.p)(()=>"thread"===a?[Object(g.a)(()=>k({direction:l.e.Backwards}),1e3,!0,!1),Object(g.a)(()=>k({direction:l.e.Forwards}),1e3,!0,!1),Object(g.a)(()=>k({direction:l.e.Around}),1e3,!0,!1)]:[],[k,f]),{isScrolled:ue,updateStickyDates:me}=pt(),he=Object(n.m)(()=>{if($.current)return void($.current=!1);const s=D.current;V.current||me(s,r),_a(()=>{Object(g.b)(()=>{s.parentElement&&(B.current=s.scrollHeight-s.scrollTop,"thread"===a&&T({chatId:e,threadId:t,scrollOffset:B.current}))})})},[me,r,a,T,e,t]);Object(n.n)(()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver(([e])=>{e.target.offsetParent&&K(e.contentRect.height)});return e.observe(D.current),()=>{e.disconnect()}},[]);const{height:Oe}=_e();Object(n.n)(()=>{D.current.dataset.normalHeight=String(D.current.offsetHeight)},[Oe]),Object(n.n)(()=>{if(!be||!u||C||w)return;const e=D.current;(!f||f.length{if(!f||!G.current)return;const e=G.current.filter(e=>f.includes(Number(e.dataset.messageId))),t=e[1]||e[0];t&&(U.current=t.id,H.current=t.getBoundingClientRect().top)},[f,v,W,r]),Object(Ot.a)(([e,t,a])=>{const s=D.current;if(G.current=Array.from(s.querySelectorAll(".message-list-item")),!s.offsetParent)return;const n=v&&f&&f.length{s.parentElement&&s.parentElement.classList.remove("force-messages-scroll")},1e3));const{scrollTop:o,scrollHeight:i,offsetHeight:l}=s,d=B.current,b=G.current[G.current.length-1],u=b?b.offsetHeight:0,m=v&&t&&d-(a||l)-u<=100;let h;const O=f&&e&&f[0]!==e[0],j=f&&e&&f[f.length-1]!==e[e.length-1],p=f&&V.current===f[f.length-1];if(m&&j&&!O&&!p&&(b&&Object(g.b)(()=>{Object(vt.a)(s,b,"end",20,void 0,void 0,void 0,!0)}),h=i-l,B.current=Math.max(i-h,l),!n))return;const I=void 0!==a&&a!==W,y=U.current&&s.querySelector("#"+U.current),C=!y&&q.current&&s.querySelector(".unread-divider");if(m&&I){if(Object(vt.b)())return;h=i-l}else if(y){h=o+(y.getBoundingClientRect().top-(H.current||0))}else h=C?C.offsetTop-(r?60:10):i-d;Object(It.a)(s,h),V.current||($.current=!0,Object(g.b)(()=>{$.current=!1})),B.current=Math.max(i-h,l)},[f,v,W,r]),Object(n.n)(()=>{(!S||S>0)&&Object(X.b)(200+c.c)},[S,M]);const ge=Object(ce.a)(),fe=Boolean(e&&Object(m.lb)(e)),pe=Boolean(!fe&&!h||j),Ie=Object(J.a)("MessageList custom-scroll",!pe&&"no-avatars",h&&"no-avatars",!O&&"no-composer","pinned"===a&&"type-pinned",M&&"select-mode-active",Q&&"has-focusing",ue&&"scrolled");return n.a.createElement("div",{ref:D,className:Ie,onScroll:he},C?n.a.createElement("div",{className:"empty"},n.a.createElement("span",null,E?E.text:"This is a private "+(h?"channel":"chat"))):R?n.a.createElement("div",{className:"empty rich"},n.a.createElement("span",null,Object(tt.a)(ge(R),["br","emoji","links"]))):f&&!ie?n.a.createElement("div",{className:"empty"},n.a.createElement("span",null,ge("NoMessages"))):f&&ie||A?n.a.createElement(Ct,{containerRef:D,className:"messages-container",messageIds:f||[A.id],focusingId:w,loadMoreForwards:de,loadMoreBackwards:le,isViewportNewest:v,firstUnreadId:I,onFabToggle:i,onNotchToggle:b},function(e,t,a,s,r,o,i,l,b,u,h,O,j,g=!1,f=!1){const p=n.a.createElement("div",{className:Object(J.a)("unread-divider","local-action-message"),key:"unread-messages"},n.a.createElement("span",null,e("UnreadMessages"))),I=f?0:t.reduce((e,t)=>e+Object(d.h)(t.senderGroups).length,0);let v=0;const y=t.map((t,O,f)=>{const y=t.senderGroups.map((t,c,g)=>{if(1===t.length&&!jt(t[0])&&Object(m.db)(t[0])){const e=t[0],s=c===g.length-1&&O===f.length-1;return Object(d.e)([e.id===l.current&&p,n.a.createElement(Vt,{key:e.id,message:e,observeIntersection:a,appearanceOrder:I-++v,isLastInList:s})])}let y;return Object(d.h)(t.map((C,E)=>{const w=jt(C)?C.mainMessage:C,M=jt(C)?C:void 0,S=Object(m.tb)(w),k=jt(C),N=t[E+1];w.previousLocalId&&i.current==="message"+w.previousLocalId&&(i.current="message"+w.id);const P=!k&&w.groupedId?w.groupedId:void 0,T=N&&!jt(N)?N.groupedId:void 0,A={isFirstInGroup:0===E,isLastInGroup:E===t.length-1,isFirstInDocumentGroup:Boolean(P&&P!==y),isLastInDocumentGroup:Boolean(P&&P!==T),isLastInList:E===t.length-1&&c===g.length-1&&O===f.length-1};y=P;const x=Object(m.F)(w),R="scheduled"!==u?x:`${w.date}_${x}`;return Object(d.e)([w.id===l.current?p:void 0,n.a.createElement(Ha,{key:R,message:w,observeIntersectionForBottom:a,observeIntersectionForMedia:s,observeIntersectionForAnimatedStickers:r,album:M,withAvatar:A.isLastInGroup&&o&&!S&&!(w.id===h),withSenderName:A.isFirstInGroup&&o&&!S,threadId:b,messageListType:u,noComments:!1===j,appearanceOrder:I-++v,isFirstInGroup:A.isFirstInGroup,isLastInGroup:A.isLastInGroup,isFirstInDocumentGroup:A.isFirstInDocumentGroup,isLastInDocumentGroup:A.isLastInDocumentGroup,isLastInList:A.isLastInList}),w.id===h&&n.a.createElement("div",{className:"local-action-message",key:"discussion-started"},n.a.createElement("span",null,e("DiscussionStarted")))])}))});return n.a.createElement("div",{className:"message-date-group",key:t.datetime,teactFastList:!0},n.a.createElement("div",{className:"sticky-date",key:"date-header"},n.a.createElement("span",{dir:"auto"},g&&t.originalDate===c.lb&&e("MessageScheduledUntilOnline"),g&&t.originalDate!==c.lb&&e("MessageScheduledOn",Object(x.c)(e,t.datetime,void 0,!0)),!g&&Object(x.c)(e,t.datetime))),Object(d.h)(y))});return Object(d.h)(y)}(ge,ie||gt([A]),se,ee,oe,pe,U,q,t,a,L,0,F,!!ie&&"scheduled"===a,!ie||!z.current)):n.a.createElement(Ee.a,{color:"white"}))}));a(237);var $a=Object(n.h)(Object(s.h)(e=>{const t=Object(o.y)(e);if(!t)return{};const{chatId:a,threadId:s,type:c}=t,n=Object(o.f)(e,a);return{messageListType:c,unreadCount:n&&s===i.MAIN_THREAD_ID&&"thread"===c?n.unreadCount:void 0}},(e,t)=>Object(d.l)(t,["focusLastMessage"]))(({isShown:e,canPost:t,messageListType:a,unreadCount:s,focusLastMessage:c})=>{const r=Object(ce.a)(),o=Object(n.q)(null),i=Object(n.m)(()=>{if(e)if("thread"===a)c();else{const e=o.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),a=t[t.length-1];if(!a)return;Object(vt.a)(e,a,"end",20)}},[e,a,c]),l=Object(J.a)("ScrollDownButton",e&&"revealed",!t&&"no-composer");return n.a.createElement("div",{ref:o,className:l},n.a.createElement("div",{className:"ScrollDownButton-inner"},n.a.createElement(oe.a,{color:"secondary",round:!0,onClick:i,ariaLabel:r("AccDescrPageDown")},n.a.createElement("i",{className:"icon-arrow-down"})),Boolean(s)&&n.a.createElement("div",{className:"unread-count"},Object(Qe.b)(s))))})),za=a(129),Wa=a(138);async function Ka(e,t,a,s){const c=URL.createObjectURL(t),{type:n,size:r}=t;let o,i;if(n.startsWith("image/"))if(a){const a=await Object(Ge.g)(c),{width:r,height:i}=a;if(r>1280||i>1280||"image/jpeg"!==n){const n=await function(e){return new Promise(t=>{const a=document.createElement("canvas"),s=a.getContext("2d");let{width:c,height:n}=e;(c>1280||n>1280)&&(c>=n?(n*=1280/c,c=1280):(c*=1280/n,n=1280)),a.width=c,a.height=n,s.drawImage(e,0,0,e.width,e.height,0,0,c,n),a.toBlob(t,"image/jpeg",100)})}(a);return n?(URL.revokeObjectURL(c),Ka(e,n,!0,s)):Ka(e,t,!1,s)}o={width:r,height:i}}else i=c;else if(n.startsWith("video/")){if(r<10485760){const{videoWidth:e,videoHeight:t,duration:a}=await Object(Ge.h)(c);o={width:e,height:t,duration:a}}i=await Object(Ge.c)(c)}return{blobUrl:c,filename:e,mimeType:n,size:r,quick:o,previewBlobUrl:i,...s}}var Qa=a(181),Ya=a.p+"8ccc0b555efcec3616377aea078dda16.js";const Xa={encoderPath:Ya,reuseWorker:!0},Ja={type:"audio/ogg"};let Za,es,ts;async function as(){return Za||(Za=a.e(9).then(a.t.bind(null,316,7)),es=(await Za).default,ts=new es(Xa)),Za}async function ss(e){await async function(){await as(),await ts.start()}();const t=Date.now();let a;const s=[],c=[];ts.ondataavailable=e=>{s.push(e)};const n=function(e,t){const a=e.sourceNode,s=a.context.createAnalyser();s.fftSize=64,a.connect(s);const c=s.frequencyBinCount,n=new Uint8Array(c);let r=!1;return function e(){if(r)return;s.getByteFrequencyData(n);const a=n.reduce((e,t)=>e+t,0),o=a/c/255;t(o<.1?0:o),requestAnimationFrame(e)}(),()=>{r=!0}}(ts,t=>{c.push(255*t),e(t)});return{stop:()=>new Promise((e,r)=>{ts.onstop=()=>{e({blob:new Blob(s,Ja),duration:Math.round(((a||Date.now())-t)/1e3),waveform:c})},ts.onerror=r;const o=Math.max(0,t+1e3-Date.now());setTimeout(()=>{ts.stop(),n()},o)}),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout(()=>{ts.pause(),a=Date.now(),n()},e)}}}const cs=["image/png","image/jpeg","image/gif"];function ns(e){const{text:t,entities:a}=e||{};if(!t)return"";const s=Object(wt.b)(t,a,void 0,void 0,!0);return Array.isArray(s)?s.join(""):s}let rs,os;var is=a(64);var ls=a(182),ds=a(190);var bs=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"DeleteMessageModal",!t);return a?n.a.createElement(a,e):void 0});function us(){return(us=Object.assign||function(e){for(var t=1;t{const a=Object(n.q)(!1),s=Object(n.m)(()=>{if(a.current=!0,hs)return hs=!1,void e();ms&&(clearTimeout(ms),ms=void 0),ms=window.setTimeout(()=>{a.current&&e()},200)},[e]),c=Object(n.m)(()=>{a.current=!1},[]);return n.a.createElement(oe.a,us({},t,{onMouseEnter:h.l?void 0:s,onMouseLeave:h.l?void 0:c,onClick:h.l?e:void 0}))});var js=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"AttachMenu",!t);return a?n.a.createElement(a,e):void 0});var gs=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"SymbolMenu",!t);return a?n.a.createElement(a,e):void 0});var fs=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"MentionTooltip",!t);return a?n.a.createElement(a,e):void 0});var ps=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"CustomSendMenu",!t);return a?n.a.createElement(a,e):void 0});var Is=e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"StickerTooltip",!t);return a?n.a.createElement(a,e):void 0},vs=a(183);var ys=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"BotKeyboardMenu",!t);return a?n.a.createElement(a,e):void 0}),Cs=a(184),Es=a(119);a(239);var ws=Object(n.h)(Object(s.h)(e=>{const{chatId:t,threadId:a,type:s}=Object(o.y)(e)||{};if(!t||!a||!s)return{};const{currentUserId:c,forwardMessages:{fromChatId:n,toChatId:r,messageIds:i}}=e,l=Object(o.mb)(e,t,a),d="scheduled"===s?Object(o.E)(e,t):Object(o.C)(e,t,a),b=e.settings.byKey.animationLevel>=1,u=r===t;let h,O;if(l?h=Object(o.k)(e,t,l):d?h=Object(o.D)(e,t,a,s):u&&1===i.length&&(h=Object(o.k)(e,n,i[0])),l&&h){const{forwardInfo:a}=h,s=t===c;a&&(a.isChannelPost||s)&&(O=Object(o.K)(e,h)),O||(O=Object(o.tb)(e,h))}else u&&(O=Object(m.lb)(n)?Object(o.Gb)(e,n):Object(o.f)(e,n));return{replyingToId:l,editingId:d,message:h,sender:O,shouldAnimate:b,forwardedMessagesCount:u?i.length:void 0}},(e,t)=>Object(d.l)(t,["setReplyingToId","setEditingId","focusMessage","exitForwardMode"]))(({replyingToId:e,editingId:t,message:a,sender:s,shouldAnimate:c,forwardedMessagesCount:r,setReplyingToId:o,setEditingId:i,focusMessage:l,exitForwardMode:d})=>{const b=Boolean((e||t)&&a||s&&r),u=Object(Es.a)([r],r?300:void 0),{shouldRender:m,transitionClassNames:h}=Object(Z.a)(u&&b,void 0,!c,void 0,!c),O=Object(n.m)(()=>{e?o({messageId:void 0}):t?i({messageId:void 0}):r&&d()},[e,t,r,o,i,d]);Object(n.n)(()=>b?Object(te.a)(O):void 0,[b,O]);const j=Object(n.m)(()=>{l({chatId:a.chatId,messageId:a.id})},[l,a]),g=Object(J.a)("ComposerEmbeddedMessage",h),f=r&&r>1?r+" forwarded messages":void 0;if(m)return n.a.createElement("div",{className:g},n.a.createElement("div",null,n.a.createElement(oe.a,{round:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:O},n.a.createElement("i",{className:"icon-close"})),n.a.createElement($t,{className:"inside-input",message:a,sender:s,customText:f,title:t?"Edit Message":void 0,onClick:j})))}));var Ms=Object(n.h)(e=>{const{attachments:t}=e,a=Object(Ce.a)(ye.a.Extra,"AttachmentModal",!t.length);return a?n.a.createElement(a,e):void 0});var Ss=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"PollModal",!t);return a?n.a.createElement(a,e):void 0});var ks=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"DropArea",!t);return a?n.a.createElement(a,e):void 0});a(240);const Ns=new RegExp(c.gb,"i");var Ps=Object(n.h)(Object(s.h)((e,{chatId:t,threadId:a})=>{const s=Object(o.cb)(e,t,a);return{webPagePreview:e.webPagePreview,noWebPage:s}},(e,t)=>Object(d.l)(t,["loadWebPagePreview","clearWebPagePreview","toggleMessageWebPage"]))(({chatId:e,threadId:t,messageText:a,disabled:s,webPagePreview:c,noWebPage:r,loadWebPagePreview:o,clearWebPagePreview:l,toggleMessageWebPage:d})=>{const b=Object(n.p)(()=>{const{text:e,entities:t}=Object(Wa.a)(a),s=t&&t.find(({type:e})=>e===i.ApiMessageEntityTypes.TextUrl);if(s)return s.url;const c=e.match(Ns);return c?c[0]:void 0},[a]);Object(n.n)(()=>{b?o({text:b}):(l(),d({chatId:e,threadId:t}))},[e,d,l,b,o,t]),Object(je.a)(()=>{l(),d({chatId:e,threadId:t})},[e]);const u=Boolean(c&&a.length&&!r&&!s),{shouldRender:m,transitionClassNames:h}=Object(Z.a)(u),O=Object(Ke.a)(c);if(!m||!O)return;const{photo:j,...g}=O,f={content:{webPage:g}};return n.a.createElement("div",{className:Object(J.a)("WebPagePreview",h)},n.a.createElement("div",null,n.a.createElement(oe.a,{round:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{d({chatId:e,threadId:t,noWebPage:!0})}},n.a.createElement("i",{className:"icon-close"})),n.a.createElement(Ma,{message:f,inPreview:!0})))})),Ts=a(122);var As=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"CalendarModal",!t);return a?n.a.createElement(a,e):void 0});var xs=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"PaymentModal",!t);return a?n.a.createElement(a,e):void 0});var Rs,Ls=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"ReceiptModal",!t);return a?n.a.createElement(a,e):void 0});a(241);!function(e){e.Send="send",e.Record="record",e.Edit="edit"}(Rs||(Rs={}));var Fs=Object(n.h)(Object(s.h)((e,{chatId:t,threadId:a,messageListType:s})=>{const c=Object(o.f)(e,t),n=c&&Object(o.o)(e,c),r=c?Object(o.O)(e,c):void 0,l=Object(o.P)(e,t),d=r&&Object(o.bb)(e,t),b=Object(o.ob)(e,t),{language:u}=e.settings.byKey,h=Object(o.F)(e,u);return{editingMessage:Object(o.D)(e,t,a,s),connectionState:e.connectionState,draft:Object(o.B)(e,t,a),chat:c,isChatWithBot:r,isChatWithSelf:l,canScheduleUntilOnline:!l&&!r&&c&&n&&Object(m.lb)(t)&&n.status&&Boolean(n.status.wasOnline),isRightColumnShown:Object(o.W)(e),isSelectModeActive:Object(o.S)(e),withScheduledButton:a===i.MAIN_THREAD_ID&&"thread"===s&&Boolean(b&&b.length),shouldSchedule:"scheduled"===s,botKeyboardMessageId:d?d.id:void 0,isForwarding:t===e.forwardMessages.toChatId,canSuggestMembers:c&&Object(m.kb)(c),isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:c&&c.fullInfo&&c.fullInfo.members,currentUserId:e.currentUserId,usersById:e.users.byId,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),shouldSuggestStickers:e.settings.byKey.shouldSuggestStickers,recentEmojis:e.recentEmojis,language:u,emojiKeywords:h?h.keywords:void 0}},(e,t)=>Object(d.l)(t,["sendMessage","editMessage","saveDraft","clearDraft","showError","setStickerSearchQuery","setGifSearchQuery","forwardMessages","openPollModal","closePollModal","closePaymentModal","clearReceipt","loadScheduledHistory","openChat","addRecentEmoji","loadEmojiKeywords"]))(({dropAreaState:e,shouldSchedule:t,canScheduleUntilOnline:a,onDropHide:r,editingMessage:o,chatId:l,threadId:d,messageListType:b,draft:u,chat:O,connectionState:j,isChatWithBot:f,isChatWithSelf:p,isRightColumnShown:I,isSelectModeActive:v,isForwarding:y,canSuggestMembers:C,isPollModalOpen:E,isPaymentModalOpen:w,isReceiptModalOpen:M,botKeyboardMessageId:S,withScheduledButton:k,stickersForEmoji:N,groupChatMembers:P,currentUserId:T,usersById:A,lastSyncTime:R,contentToBeScheduled:L,shouldSuggestStickers:F,language:D,emojiKeywords:B,recentEmojis:U,sendMessage:H,editMessage:G,saveDraft:q,clearDraft:_,showError:V,setStickerSearchQuery:$,setGifSearchQuery:z,forwardMessages:W,openPollModal:K,closePollModal:Q,loadScheduledHistory:Y,closePaymentModal:X,openChat:Z,clearReceipt:ee,addRecentEmoji:ae,loadEmojiKeywords:se})=>{const ne=Object(n.q)(null),[re,ie]=Object(n.r)(""),le=Object(n.q)(),de=Object(ca.a)(e),[be,ue,he]=Object(ot.a)(),[Oe,je]=Object(n.r)(),ge=Object(n.q)(re);Object(n.n)(()=>{ge.current=re},[re]),Object(n.n)(()=>{le.current=void 0},[l]),Object(n.n)(()=>{l&&R&&d===i.MAIN_THREAD_ID&&Y()},[l,Y,R,d]),Object(n.o)(()=>{ne.current&&(ne.current.innerHTML='')},[]),Object(n.n)(()=>{L&&(je(L),ue())},[L,ue]);const[fe,pe]=Object(n.r)([]),[Ie,ve,ye]=Object(ot.a)(),[Ce,Ee,we]=Object(ot.a)(),[Me,Se,ke]=Object(ot.a)(),[Ne,Pe,Te]=Object(ot.a)(),[Ae,xe]=Object(ot.a)(),[Re,Le,Fe]=Object(ot.a)(),{startRecordingVoice:De,stopRecordingVoice:Be,pauseRecordingVoice:He,activeVoiceRecording:Ge,currentRecordTime:qe,recordButtonRef:_e,startRecordTimeRef:Ve}=(()=>{const e=Object(n.q)(null),[t,a]=Object(n.r)(),s=Object(n.q)(),[c,r]=Object(n.r)();Object(n.n)(()=>{h.e&&as()},[]);const o=Object(n.m)(async()=>{try{const{stop:t,pause:c}=await ss(t=>{e.current&&(s.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),r(Date.now()))});s.current=Date.now(),r(Date.now()),a({stop:t,pause:c})}catch(e){console.error(e)}},[]),i=Object(n.m)(()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}},[t]),l=Object(n.m)(()=>{if(t){a(void 0),s.current=void 0,r(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}},[t]);return Object(n.n)(()=>t?Object(te.a)(l):void 0,[t,l]),{startRecordingVoice:o,pauseRecordingVoice:i,stopRecordingVoice:l,activeVoiceRecording:t,currentRecordTime:c,recordButtonRef:e,startRecordTimeRef:s}})(),$e=o?Rs.Edit:!h.m||Ge||re&&!fe.length||y?Rs.Send:Rs.Record,ze=!t,{isMentionTooltipOpen:We,mentionFilter:Ke,closeMentionTooltip:Qe,insertMention:Ye,mentionFilteredMembers:Xe}=Object(ds.a)(C&&!fe.length,re,ie,void 0,P,T,A),{isContextMenuOpen:Je,handleContextMenu:Ze,handleContextMenuClose:et,handleContextMenuHide:at}=Object(Et.a)(_e,!($e===Rs.Send&&ze)),st=Object(n.p)(()=>Object(m.c)(O,f),[O,f]),ct=O&&Object(m.gb)(O),nt=Object(m.k)(O),{isStickerTooltipOpen:rt,closeStickerTooltip:it}=function(e,t,a){const{loadStickersForEmoji:c,clearStickersForEmoji:r}=Object(s.d)(),o=h.d&&1===Object(is.a)(t)||!h.d&&Boolean(t.match(/^]*?>$/g)),i=Boolean(a)&&o;return Object(n.n)(()=>{e&&o?c({emoji:t}):!i&&o||r()},[t,o,r,c,e]),{isStickerTooltipOpen:i,closeStickerTooltip:r}}(Boolean(F&&st.canSendStickers&&!fe.length),re,N),{isEmojiTooltipOpen:lt,closeEmojiTooltip:dt,filteredEmojis:bt,insertEmoji:ut}=Object(ls.a)(Boolean(F&&st.canSendStickers&&!fe.length),re,U,void 0,ie,B),mt=Object(n.m)((e,t=c.v)=>{const a=window.getSelection(),s=document.getElementById(t),n=Object(tt.a)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(a.rangeCount){const t=a.getRangeAt(0);if(Object(Qa.a)(t))return void(h.d?document.execCommand("insertText",!1,e):(!function(e){const t=window.getSelection();if(t&&t.getRangeAt&&t.rangeCount){const a=t.getRangeAt(0);a.deleteContents();const s=a.createContextualFragment(e),c=s.lastChild;a.insertNode(s),c&&(a.setStartAfter(c),a.setEndAfter(c),t.removeAllRanges(),t.addRange(a))}}(n),s.dispatchEvent(new Event("input",{bubbles:!0}))))}ie(`${ge.current}${n}`),h.g||requestAnimationFrame(()=>{Object(za.a)(s)})},[]),ht=Object(n.m)(()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if(Object(Qa.a)(t))return void document.execCommand("delete",!1)}ie(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 a=t.lastChild;if(a.lastChild)for(;a.lastChild;)a=a.lastChild;const s=a.textContent.length,c=document.createRange(),n=window.getSelection();c.setStart(a,s),c.setEnd(a,s),n.removeAllRanges(),n.addRange(c),document.execCommand("delete",!1);const r=t.innerHTML;return document.body.removeChild(t),r}(ge.current))},[]),Ot=Object(n.m)(()=>{ie(""),pe([]),it(),he(),je(void 0),Qe(),dt(),h.g?setTimeout(()=>ke(),350):ke()},[it,he,Qe,dt,ke]),jt=Object(ca.a)(l);Object(n.n)(()=>{jt&&l!==jt&&(Be(),Ot())},[l,jt,Ot,Be]);const gt=((e,t,a,s,r,o)=>{Object(n.n)(()=>{a?(t(ns(a.content.text)),requestAnimationFrame(()=>{const e=document.getElementById(c.v);Object(za.a)(e,!0)})):t("")},[a,t]);return Object(n.m)(()=>{const{text:t,entities:c}=Object(Wa.a)(e.current);a&&(t||Object(m.cb)(a)?(o({messageId:a.id,text:t,entities:c}),s()):r())},[o,a,e,r,s])})(ge,ie,o,Ot,Pe,G);((e,t,a,s,r,o,i,l,d)=>{const b=Object(n.m)((e,t)=>{r.current.length&&!i?l({chatId:e,threadId:t,draft:Object(Wa.a)(r.current)}):d({chatId:e,threadId:t})},[d,i,r,l]),u=Object(n.p)(()=>Object(g.a)(e=>e(),c.u,!1),[t]),m=Object(ca.a)(t),h=Object(ca.a)(a);Object(n.n)(()=>(rs=t,os=a,()=>{rs=void 0,os=void 0,b(t,a)}),[t,a,b]),Object(n.n)(()=>{t===m&&a===h||e&&(o(ns(e)),requestAnimationFrame(()=>{const e=document.getElementById(c.v);Object(za.a)(e,!0)}))},[t,a,e,o,b,m,h]);const O=Object(ca.a)(s);Object(n.n)(()=>{t&&a&&m===t&&h===a&&O!==s&&(s.length?u(()=>{rs===t&&os===a&&b(t,a)}):b(t,a))},[t,s,m,O,h,u,a,b]),Object(n.n)(()=>{function e(){t&&a&&b(t,a)}return window.addEventListener("blur",e),()=>{window.removeEventListener("blur",e)}},[t,a,b])})(u,l,d,re,ge,ie,o,q,_),((e,t,a)=>{Object(n.n)(()=>{async function s(s){if(!s.clipboardData)return;const n=document.activeElement;if(n&&"INPUT"===n.tagName&&![c.v,c.w].includes(n.id))return;const{items:r}=s.clipboardData,o=Array.from(r).find(e=>cs.includes(e.type)),i=o&&o.getAsFile(),l=s.clipboardData.getData("text").substring(0,4096);if(i||l){if(s.preventDefault(),i&&!a){const e=await Ka(i.name,i,!0);t(t=>[...t,e])}l&&e(l,n?n.id:void 0)}}return document.addEventListener("paste",s,!1),()=>{document.removeEventListener("paste",s,!1)}},[e,a,t])})(mt,pe,o);const ft=Object(n.m)(async(e,t)=>{pe(await Promise.all(e.map(e=>Ka(e.name,e,t))))},[]),pt=Object(n.m)(async(e,t)=>{pe([...fe,...await Promise.all(e.map(e=>Ka(e.name,e,t)))])},[fe]),It=Object(n.m)(()=>{pe([])},[]),vt=Object(n.m)(async(e=!1,t)=>{if("connectionStateReady"!==j)return;let a=fe;if(Ge){const e=await Be();if(e){const{blob:t,duration:s,waveform:c}=e;a=[await Ka("wonderful-voice-message.ogg",t,!1,{voice:{duration:s,waveform:c}})]}}const{text:s,entities:n}=Object(Wa.a)(ge.current);if(a.length||s||y)if(a.length&&s&&s.length>1024){const e=s.length-1024;V({error:{message:"CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""}}})}else{if(a.length||s){if(nt&&!ct){const e=Math.floor(Date.now()/1e3),t=le.current&&Math.floor(e-le.current),a=nt.nextSendDate&&nt.nextSendDate>e;if(t&&t{e={...e,isPreloadedGlobally:!0},t?(je({sticker:e}),ue()):(H({sticker:e}),requestAnimationFrame(Ot))},[t,ue,H,Ot]),Ct=Object(n.m)(e=>{t?(je({gif:e}),ue()):(H({gif:e}),requestAnimationFrame(Ot))},[t,ue,H,Ot]),wt=Object(n.m)(e=>{t?(je({poll:e}),Q(),ue()):(H({poll:e}),Q())},[Q,ue,H,t]),Mt=Object(n.m)(()=>{t?(je({isSilent:!0}),ue()):vt(!0)},[vt,ue,t]),St=Object(n.m)(e=>{const{isSilent:t,...a}=Oe||{},s=Math.round(Math.max(e.getTime(),Date.now()+6e4)/1e3);Oe&&0!==Object.keys(a).length?(H({...Oe,scheduledAt:s}),requestAnimationFrame(Ot)):vt(!!t,s),he()},[he,vt,Ot,Oe,H]),kt=Object(n.m)(()=>{St(new Date(1e3*c.lb))},[St]),Nt=Object(n.m)(()=>{he(),je(void 0)},[he]),Pt=Object(n.m)(e=>{"stickers"===e?($({query:""}),z({query:void 0})):(z({query:""}),$({query:void 0}))},[$,z]),Tt=Object(n.m)(()=>{const e=document.getElementById(c.v);h.g&&e===document.activeElement?(e.blur(),setTimeout(()=>{Se()},100)):Se()},[Se]),At=Object(n.m)(()=>{Z({id:l,threadId:d,type:"scheduled"})},[Z,l,d]);Object(n.n)(()=>{I&&h.g&&ke()},[I,ke]),Object(n.n)(()=>{v?Le():setTimeout(()=>{Fe()},200)},[v,Fe,Le]);const xt=Object(n.m)(()=>{switch($e){case Rs.Send:t?(Ge&&He(),ue()):(vt(),requestAnimationFrame(Ot));break;case Rs.Record:De();break;case Rs.Edit:gt()}},[$e,Ot,t,De,gt,Ge,ue,He,vt]),Rt=Object(ce.a)(),Lt=$e===Rs.Record&&!st.canAttachMedia,Ft=Object(ca.a)(o,!0),Dt=o||Ft,Bt=new Date;Bt.setSeconds(0),Bt.setMilliseconds(0);const Ut=new Date;Ut.setFullYear(Ut.getFullYear()+1);let Ht="SendMessage";switch($e){case Rs.Edit:Ht="Save edited message";break;case Rs.Record:Ht=Lt?"Conversation.DefaultRestrictedMedia":"AccDescrVoiceMessage"}const Gt=Object(J.a)("Composer",!v&&"shown",Re&&"hover-disabled"),qt=Object(J.a)("mobile-symbol-menu-button",Ae?Me&&"menu-opened":Me&&"is-loading");return n.a.createElement("div",{className:Gt},st.canAttachMedia&&n.a.createElement(Ts.a,{containerId:"#middle-column-portals"},n.a.createElement(ks,{isOpen:e!==Ue.a.None,withQuick:[e,de].includes(Ue.a.QuickFile),onHide:r,onFileSelect:ft})),n.a.createElement(Ms,{attachments:fe,caption:fe.length?re:"",canSuggestMembers:C,groupChatMembers:P,currentUserId:T,usersById:A,recentEmojis:U,onCaptionUpdate:ie,language:D,addRecentEmoji:ae,loadEmojiKeywords:se,onSend:t?ue:vt,onFileAppend:pt,onClear:It}),n.a.createElement(Ss,{isOpen:Boolean(E),onClear:Q,onSend:wt}),n.a.createElement(xs,{isOpen:Boolean(w),onClose:X}),n.a.createElement(Ls,{isOpen:Boolean(M),onClose:ee}),Dt&&n.a.createElement(bs,{isOpen:Ne,isSchedule:"scheduled"===b,onClose:Te,message:Dt}),n.a.createElement(fs,{isOpen:We,filter:Ke,onClose:Qe,onInsertUserName:Ye,filteredChatMembers:Xe,usersById:A}),n.a.createElement("div",{id:"message-compose"},n.a.createElement("div",{className:"svg-appendix",ref:ne}),n.a.createElement(ws,null),n.a.createElement(Ps,{chatId:l,threadId:d,messageText:fe.length?"":re,disabled:!st.canAttachEmbedLinks}),n.a.createElement("div",{className:"message-input-wrapper"},h.g?n.a.createElement(oe.a,{className:qt,round:!0,color:"translucent",onClick:Me?ke:Tt,ariaLabel:"Choose emoji, sticker or GIF"},n.a.createElement("i",{className:"icon-smile"}),n.a.createElement("i",{className:"icon-keyboard"}),n.a.createElement(me.a,{color:"gray"})):n.a.createElement(Os,{className:""+(Me?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:Se,ariaLabel:"Choose emoji, sticker or GIF"},n.a.createElement("i",{className:"icon-smile"})),n.a.createElement(Cs.a,{id:"message-input-text",html:fe.length?"":re,placeholder:Ge&&window.innerWidth<=600?"":Rt("Message"),shouldSetFocus:Me,shouldSupressFocus:h.g&&Me,shouldSupressTextFormatter:lt||We,onUpdate:ie,onSend:$e===Rs.Edit?gt:t?ue:vt,onSupressedFocus:ke}),k&&n.a.createElement(oe.a,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:At,ariaLabel:"Open scheduled messages"},n.a.createElement("i",{className:"icon-schedule"})),S&&!Ge&&!o&&n.a.createElement(Os,{className:""+(Ie?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:ve,ariaLabel:"Open bot command keyboard"},n.a.createElement("i",{className:"icon-bot-command"})),!Ge&&!o&&n.a.createElement(Os,{className:""+(Ce?"activated":""),round:!0,faded:!0,color:"translucent",onActivate:Ee,ariaLabel:"Add an attachment"},n.a.createElement("i",{className:"icon-attach"})),Ge&&qe&&n.a.createElement("span",{className:"recording-state"},Object(x.i)(qe-Ve.current)),n.a.createElement(Is,{isOpen:rt,onStickerSelect:yt}),n.a.createElement(vs.a,{isOpen:lt,emojis:bt,onClose:dt,onEmojiSelect:ut,addRecentEmoji:ae,loadEmojiKeywords:se,language:D}),n.a.createElement(js,{isOpen:Ce,allowedAttachmentOptions:st,onFileSelect:ft,onPollCreate:K,onClose:we}),S&&n.a.createElement(ys,{messageId:S,isOpen:Ie,onClose:ye}),n.a.createElement(gs,{isOpen:Me,allowedAttachmentOptions:st,onLoad:xe,onClose:ke,onEmojiSelect:mt,onStickerSelect:yt,onGifSelect:Ct,onRemoveSymbol:ht,onSearchOpen:Pt,addRecentEmoji:ae}))),Ge&&n.a.createElement(oe.a,{round:!0,color:"danger",className:"cancel",onClick:Be,ariaLabel:"Cancel voice recording"},n.a.createElement("i",{className:"icon-delete"})),n.a.createElement(oe.a,{ref:_e,round:!0,color:"secondary",className:`${$e} ${Ge?"recording":""}`,disabled:Lt,ariaLabel:Rt(Ht),onClick:xt,onContextMenu:$e===Rs.Send&&ze?Ze:void 0},n.a.createElement("i",{className:"icon-send"}),n.a.createElement("i",{className:"icon-microphone-alt"}),n.a.createElement("i",{className:"icon-check"})),ze&&n.a.createElement(ps,{isOpen:Je,onSilentSend:p?void 0:Mt,onScheduleSend:t?void 0:ue,onClose:et,onCloseAnimationEnd:at}),n.a.createElement(As,{isOpen:be,withTimePicker:!0,selectedAt:Bt.getTime(),maxAt:Object(x.k)(Ut),isFutureMode:!0,secondButtonLabel:a?"Send When Online":void 0,onClose:Nt,onSubmit:St,onSecondButtonClick:a?kt:void 0}))}));var Ds=Object(n.h)(e=>{const{isActive:t}=e,a=Object(Ce.a)(ye.a.Extra,"MobileSearch",!t,!0);return a?n.a.createElement(a,e):void 0});var Bs=Object(n.h)(e=>{const{isActive:t}=e,a=Object(Ce.a)(ye.a.Extra,"MessageSelectToolbar",!t);return a?n.a.createElement(a,e):void 0});var Us=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"UnpinAllMessagesModal",!t);return a?n.a.createElement(a,e):void 0});a(242);const Hs=h.g?450+c.c:void 0;function Gs(e){return"file"===e.kind&&e.type&&c.l.includes(e.type)}var qs=Object(n.h)(Object(s.h)(e=>{const{theme:t}=e.settings.byKey,{isBlurred:a,background:s,backgroundColor:c,patternColor:n}=e.settings.themes[t]||{},r=Object(o.y)(e),{chats:{listIds:l}}=e,d={theme:t,customBackground:s,backgroundColor:c,patternColor:n,isRightColumnShown:Object(o.W)(e),isBackgroundBlurred:a,isMobileSearchActive:Boolean(h.g&&Object(o.A)(e)),isSelectModeActive:Object(o.S)(e),animationLevel:e.settings.byKey.animationLevel};if(!r||!l.active)return d;const{chatId:b,threadId:u,type:O}=r,j=Object(o.f)(e,b),g=Object(o.jb)(e,b),{chatId:f,messageId:p}=e.audioPlayer,I=j&&Object(m.e)(j,u),v=Object(o.L)(e,b),y="pinned"===O;return{...d,chatId:b,threadId:u,messageListType:O,isPrivate:Object(m.lb)(b),canPost:!y&&(!j||I)&&(!v||h.g),isPinnedMessageList:y,messageSendingRestrictionReason:j&&Object(m.K)(j),hasPinnedOrAudioMessage:u!==i.MAIN_THREAD_ID||Boolean(g&&g.length)||Boolean(f&&p),pinnedMessagesCount:g?g.length:0}},(e,t)=>Object(d.l)(t,["openChat","unpinAllMessages","loadUser"]))(({chatId:e,threadId:t,messageListType:a,isPrivate:s,isPinnedMessageList:r,canPost:o,messageSendingRestrictionReason:l,hasPinnedOrAudioMessage:d,pinnedMessagesCount:b,customBackground:u,theme:m,backgroundColor:O,patternColor:j,isRightColumnShown:g,isBackgroundBlurred:f,isMobileSearchActive:p,isSelectModeActive:I,animationLevel:v,openChat:y,unpinAllMessages:C,loadUser:E})=>{const{width:w}=_e(),[M,S]=Object(n.r)(Ue.a.None),[k,N]=Object(n.r)(),[P,T]=Object(n.r)(),[A,x]=Object(n.r)(!1),R=d&&(wc.ab&&w=c.Z&&we?Object(te.a)(()=>{y({id:void 0})}):void 0,[e,y]),Object(n.n)(()=>{S(Ue.a.None),N(void 0),T(void 0)},[e]),Object(n.n)(()=>{s&&E({userId:e})},[e,s,E]);const G=Object(n.m)(e=>{if(h.l)return;const{items:t}=e.dataTransfer||{},a=t&&Array.from(t).every(Gs);S(a?Ue.a.QuickFile:Ue.a.Document)},[]),q=Object(n.m)(()=>{S(Ue.a.None)},[]),_=Object(n.m)(()=>{x(!0)},[]),V=Object(n.m)(()=>{x(!1)},[]),$=Object(n.m)(()=>{C({chatId:e}),V(),y({id:e})},[C,y,V,e]),z=((e,t)=>{const[a,s]=Object(n.r)(t);return Object(n.n)(()=>{t&&(t.startsWith("#")?s(t):He.c(c.m,e,He.a.Blob).then(e=>{const t=URL.createObjectURL(e);Object(Ge.g)(t).then(()=>{s(`url(${t})`)})}))},[t,e]),t?a:void 0})(m,u),W=Object(J.a)(U&&"has-header-tools",u&&"custom-bg-image",O&&"custom-bg-color",u&&f&&"blurred",h.n?"mask-image-disabled":"mask-image-enabled"),K=Object(J.a)("messaging-disabled",!I&&"shown"),{composerHiddenScale:Q,toolbarHiddenScale:Y,composerTranslateX:X,toolbarTranslateX:Z,unpinHiddenScale:ee,toolbarForUnpinHiddenScale:se}=Object(n.p)(()=>$e(w,B),[B,w]),ne=Object(ce.a)(),re=Object(J.a)("middle-column-footer",!B&&"no-composer",B&&P&&!I&&"with-notch");return n.a.createElement("div",{id:"MiddleColumn",className:W,style:`\n --composer-hidden-scale: ${Q};\n --toolbar-hidden-scale: ${Y};\n --unpin-hidden-scale: ${ee};\n --toolbar-unpin-hidden-scale: ${se};\n --composer-translate-x: ${X}px;\n --toolbar-translate-x: ${Z}px;\n --pattern-color: ${j};\n --theme-background-color:\n ${O||("dark"===m?c.n:c.I)};\n `},n.a.createElement("div",{id:"middle-column-bg",style:z?"--custom-background: "+z:void 0}),n.a.createElement("div",{id:"middle-column-portals"}),L&&F&&n.a.createElement(n.a.Fragment,null,n.a.createElement("div",{className:"messages-layout",onDragEnter:B?G:void 0},n.a.createElement(ht,{chatId:L,threadId:F,messageListType:D}),n.a.createElement(ae.a,{name:v===c.e?"slide":"fade",activeKey:"thread"===D&&F===i.MAIN_THREAD_ID?1:2,shouldCleanup:!0},()=>n.a.createElement(n.a.Fragment,null,n.a.createElement(Va,{key:`${L}-${F}-${D}`,chatId:L,threadId:F,type:D,canPost:B,hasTools:U,onFabToggle:N,onNotchToggle:T}),n.a.createElement("div",{className:re},B&&n.a.createElement(Fs,{chatId:L,threadId:F,messageListType:D,dropAreaState:M,onDropHide:q}),r&&n.a.createElement("div",{className:"unpin-button-container",dir:ne.isRtl?"rtl":void 0},n.a.createElement(oe.a,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:_},n.a.createElement("i",{className:"icon-unpin"}),n.a.createElement("span",null,ne("Chat.Pinned.UnpinAll",b,"i")))),!r&&!B&&l&&n.a.createElement("div",{className:K},n.a.createElement("div",{className:"messaging-disabled-inner"},n.a.createElement("span",null,l))),n.a.createElement(Bs,{messageListType:D,isActive:I,canPost:B})))),n.a.createElement($a,{isShown:H,canPost:B})),h.g&&n.a.createElement(Ds,{isActive:Boolean(p)})),e&&n.a.createElement(Us,{isOpen:A,chatId:e,pinnedMessagesCount:b,onClose:V,onUnpin:$}))}));a(243);const _s=Object(g.a)(e=>e(),200,!1);var Vs;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Management=4]="Management",e[e.ManageInitial=5]="ManageInitial",e[e.ManageChannelSubscribers=6]="ManageChannelSubscribers",e[e.ManageChatAdministrators=7]="ManageChatAdministrators",e[e.ManageChatPrivacyType=8]="ManageChatPrivacyType",e[e.ManageDiscussion=9]="ManageDiscussion",e[e.ManageGroupPermissions=10]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=11]="ManageGroupRemovedUsers",e[e.ManageGroupUserPermissionsCreate=12]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=13]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=14]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=15]="ManageGroupAdminRights",e[e.ManageGroupMembers=16]="ManageGroupMembers",e[e.StickerSearch=17]="StickerSearch",e[e.GifSearch=18]="GifSearch",e[e.PollResults=19]="PollResults"}(Vs||(Vs={}));var $s=Object(n.h)(Object(s.h)((e,{chatId:t,isProfile:a,isManagement:s})=>{const{query:c}=Object(o.A)(e)||{},{query:n}=Object(o.z)(e)||{},{query:r}=Object(o.s)(e)||{},i=t?Object(o.f)(e,t):void 0,l=i&&Object(m.jb)(i);return{canManage:Boolean(!s&&a&&i&&!Object(o.P)(e,i.id)&&(Object(m.lb)(i.id)||(Object(m.gb)(i)||i.isCreator)&&!i.isNotJoined)),isChannel:l,messageSearchQuery:c,stickerSearchQuery:n,gifSearchQuery:r}},(e,t)=>Object(d.l)(t,["setLocalTextSearchQuery","setStickerSearchQuery","setGifSearchQuery","searchTextMessagesLocal","toggleManagement","searchMessagesByDate"]))(({isColumnOpen:e,isProfile:t,isSearch:a,isManagement:s,isStickerSearch:c,isGifSearch:r,isPollResults:o,profileState:i,managementScreen:d,canManage:b,isChannel:u,onClose:m,messageSearchQuery:O,stickerSearchQuery:j,gifSearchQuery:g,setLocalTextSearchQuery:f,setStickerSearchQuery:p,setGifSearchQuery:I,searchTextMessagesLocal:v,toggleManagement:y,searchMessagesByDate:C})=>{var E;const w=Object(n.q)(null),[M,S,k]=Object(ot.a)(),N=Object(n.m)(e=>{f({query:e}),e.length&&_s(v)},[v,f]),P=Object(n.m)(e=>{C({timestamp:e.valueOf()/1e3}),k()},[k,C]),T=Object(n.m)(e=>{p({query:e})},[p]),A=Object(n.m)(e=>{I({query:e})},[I]),[x,R]=Object(n.r)(!e);Object(n.n)(()=>{setTimeout(()=>{R(!e)},300)},[e]);const L=Object(ce.a)(),F=t?i===l.k.Profile?Vs.Profile:i===l.k.SharedMedia?Vs.SharedMedia:i===l.k.MemberList?Vs.MemberList:-1:a?Vs.Search:o?Vs.PollResults:c?Vs.StickerSearch:r?Vs.GifSearch:s?d===l.g.Initial?Vs.ManageInitial:d===l.g.ChatPrivacyType?Vs.ManageChatPrivacyType:d===l.g.Discussion?Vs.ManageDiscussion:d===l.g.ChannelSubscribers?Vs.ManageChannelSubscribers:d===l.g.GroupPermissions?Vs.ManageGroupPermissions:d===l.g.ChatAdministrators?Vs.ManageChatAdministrators:d===l.g.GroupRemovedUsers?Vs.ManageGroupRemovedUsers:d===l.g.GroupUserPermissionsCreate?Vs.ManageGroupUserPermissionsCreate:d===l.g.GroupUserPermissions?Vs.ManageGroupUserPermissions:d===l.g.GroupRecentActions?Vs.ManageGroupRecentActions:d===l.g.ChatAdminRights?Vs.ManageGroupAdminRights:d===l.g.GroupMembers?Vs.ManageGroupMembers:void 0:void 0,D=null!==(E=Object(Ke.a)(F,!0))&&void 0!==E?E:-1;function B(){if(-1!==D)switch(D){case Vs.PollResults:return n.a.createElement("h3",null,L("PollResults"));case Vs.Search:return n.a.createElement(n.a.Fragment,null,n.a.createElement(ie.a,{parentContainerClassName:"RightSearch",value:O,onChange:N}),n.a.createElement(oe.a,{round:!0,size:"smaller",color:"translucent",onClick:S,ariaLabel:"Search messages by date"},n.a.createElement("i",{className:"icon-calendar"})));case Vs.ManageInitial:return n.a.createElement("h3",null,L("Edit"));case Vs.ManageChatPrivacyType:return n.a.createElement("h3",null,L(u?"ChannelTypeHeader":"GroupTypeHeader"));case Vs.ManageDiscussion:return n.a.createElement("h3",null,L("Discussion"));case Vs.ManageChatAdministrators:return n.a.createElement("h3",null,L("ChannelAdministrators"));case Vs.ManageGroupRecentActions:return n.a.createElement("h3",null,L("Group.Info.AdminLog"));case Vs.ManageGroupAdminRights:return n.a.createElement("h3",null,L("EditAdminRights"));case Vs.ManageGroupPermissions:return n.a.createElement("h3",null,L("ChannelPermissions"));case Vs.ManageGroupRemovedUsers:return n.a.createElement("h3",null,L("ChannelBlockedUsers"));case Vs.ManageGroupUserPermissionsCreate:return n.a.createElement("h3",null,L("ChannelAddException"));case Vs.ManageGroupUserPermissions:return n.a.createElement("h3",null,L("UserRestrictions"));case Vs.StickerSearch:return n.a.createElement(ie.a,{value:j,placeholder:L("SearchStickersHint"),onChange:T});case Vs.GifSearch:return n.a.createElement(ie.a,{value:g,placeholder:L("SearchGifsTitle"),onChange:A});case Vs.SharedMedia:return n.a.createElement("h3",null,L("SharedMedia"));case Vs.ManageChannelSubscribers:return n.a.createElement("h3",null,L("ChannelSubscribers"));case Vs.MemberList:case Vs.ManageGroupMembers:return n.a.createElement("h3",null,L("GroupMembers"));default:return n.a.createElement(n.a.Fragment,null,n.a.createElement("h3",null,"Profile"),n.a.createElement("section",{className:"tools"},b&&n.a.createElement(oe.a,{round:!0,color:"translucent",size:"smaller",ariaLabel:L("Edit"),onClick:y},n.a.createElement("i",{className:"icon-edit"}))))}}const U=h.g||F===Vs.SharedMedia||F===Vs.MemberList||s,H=Object(J.a)("animated-close-icon",x&&"no-transition");return Object(n.n)(()=>{w.current.classList.toggle("state-back",U)},[U]),n.a.createElement("div",{className:"RightHeader"},n.a.createElement(oe.a,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:m,ariaLabel:L(U?"Common.Back":"Common.Close")},n.a.createElement("div",{ref:w,className:H})),n.a.createElement(ae.a,{name:x?"none":"slide-fade",activeKey:D},B),!h.g&&n.a.createElement(As,{isOpen:M,isPastMode:!0,submitButtonLabel:L("JumpToDate"),onClose:k,onSubmit:P}))})),zs=a(127);function Ws(e,t,a,s,r,o,i,l,d,b,u){const h="members"!==s&&r?r:s,O=Object(n.p)(()=>{if(o&&i)return Object(m.Eb)(o.map(({userId:e})=>e),i)},[o,i]),[j,g,f]=function(e,t,a,s){const[n,r]=Object(zs.a)(a?t:void 0,s,void 0,c.R),o=!n||!s||n[0]===s[0];return[n,r,!o]}(0,t,u,O),[p,I,v]=Ks("media",h,a,u,l,d),[y,C,E]=Ks("documents",h,a,u,l,d),[w,M,S]=Ks("links",h,a,u,l,d),[k,N,P]=Ks("audio",h,a,u,l,d);let T,A,x=!1;switch(h){case"members":T=j,A=g,x=f;break;case"media":T=p,A=I,x=v;break;case"documents":T=y,A=C,x=E;break;case"links":T=w,A=M,x=S;break;case"audio":T=k,A=N,x=P}return[h,T,A,x]}function Ks(e,t,a,s,r,o){const i=Object(n.q)();Object(je.a)(()=>{t===e&&r&&o&&(i.current=Object(m.w)(r,o,e).reverse())},[r,o,t,e]);const[l,d]=Object(zs.a)(s?a:void 0,i.current,void 0,"media"===e?c.ob:c.X);return[l,d,!(!l||!i.current||l[0]===i.current[0])]}var Qs=a(58);const Ys=Object(g.g)(e=>e(),250,!1);let Xs=!1;var Js=a(113),Zs=a(106);var ec=a(133),tc=a(191);a(244);var ac=Object(n.h)(({chat:e,user:t,photo:a,isFirstPhoto:s,isSavedMessages:c,lastSyncTime:r,onClick:o})=>{const l=Object(ce.a)(),d=t&&Object(m.pb)(t);function b(s="big",n){if(a&&!n)return`photo${a.id}?size=c`;let r;return c||d||(t?r=Object(m.f)(t,s):e&&(r=Object(m.f)(e,s))),r}const u=b(),h=Object(at.a)(u,!1,i.ApiMediaFormat.BlobUrl,r),O=Object(at.a)(!h&&s?b("normal",!0):void 0,!1,i.ApiMediaFormat.BlobUrl,r),j=Object(tc.a)(!h&&a&&a.thumbnail&&a.thumbnail.dataUri),g=h||O||j,f=Object(ca.a)(g);let p="";if(c)p=n.a.createElement("i",{className:"icon-avatar-saved-messages"});else if(d)p=n.a.createElement("i",{className:"icon-avatar-deleted-account"});else if(g)p=n.a.createElement("img",{src:g,className:"avatar-media",alt:"",decoding:"async"});else if(!g&&t){const e=Object(m.Z)(t);p=e?Object(Qe.c)(e,2):void 0}else if(!g&&e){const t=Object(m.l)(l,e);p=t&&Object(Qe.c)(t,Object(m.lb)(e.id)?2:1)}else p=n.a.createElement("div",{className:"spinner-wrapper"},n.a.createElement(me.a,{color:"white"}));const I=Object(J.a)("ProfilePhoto","color-bg-"+Object(m.X)(t||e),c&&"saved-messages",d&&"deleted-account",!c&&!g&&"no-photo");return n.a.createElement("div",{className:I,onClick:g?o:void 0},f&&g&&f!==g&&n.a.createElement("img",{src:f,className:"prev-avatar-media",alt:"",decoding:"async"}),"string"==typeof p?Object(tt.a)(p,["hq_emoji"]):p)});a(245);var sc=Object(n.h)(Object(s.h)((e,{userId:t,forceShowSelf:a})=>{const{lastSyncTime:s}=e,c=Object(o.Gb)(e,t),n=Object(o.f)(e,t),r=!a&&c&&c.isSelf,{animationLevel:i}=e.settings.byKey;return{lastSyncTime:s,user:c,chat:n,isSavedMessages:r,animationLevel:i}},(e,t)=>Object(d.l)(t,["loadFullUser","openMediaViewer"]))(({user:e,chat:t,isSavedMessages:a,lastSyncTime:s,animationLevel:c,loadFullUser:r,openMediaViewer:o})=>{const{id:d}=e||{},{id:b}=t||{},u=e?Object(m.Z)(e):t?t.title:"",O=(e?e.photos:t?t.photos:void 0)||[],j=c>=1?"slide":"none",[g,f]=Object(n.r)(0),p=a||O.length<=1||0===g,I=a||O.length<=1||g===O.length-1;Object(n.n)(()=>{g>O.length&&f(Math.max(0,O.length-1))},[g,O.length]);const v=Object(ce.a)();Object(n.n)(()=>{s&&d&&r({userId:d})},[d,r,s]),function(e,t,a){Object(n.n)(()=>{t.slice(a,a+4).forEach(e=>{bt.c(`photo${e.id}?size=c`)||bt.b(`photo${e.id}?size=c`,i.ApiMediaFormat.BlobUrl)})},[a,t])}(0,O,g);const y=Object(n.m)(()=>{o({avatarOwnerId:d||b,profilePhotoIndex:g,origin:l.h.ProfileAvatar})},[o,d,b,g]),C=Object(n.m)(()=>{p||f(g-1)},[g,p]),E=Object(n.m)(()=>{I||f(g+1)},[g,I]);if(Object(n.n)(()=>{const e=document.querySelector(".profile-slide-container > .active, .profile-slide-container > .to");if(e)return Object(Oe.b)(e,{excludedClosestSelector:".navigation",onSwipe:h.l?(e,t)=>{t===Oe.a.Right?C():t===Oe.a.Left&&E()}:void 0})},[E,C]),!e&&!t)return;function w(){const s=!a&&O&&O.length>0?O[g]:void 0;return n.a.createElement(ac,{key:g,user:e,chat:t,photo:s,isSavedMessages:a,isFirstPhoto:p,onClick:y})}const M=e&&e.isVerified||t&&t.isVerified;return n.a.createElement("div",{className:"ProfileInfo",dir:v.isRtl?"rtl":void 0},n.a.createElement("div",{className:"photo-wrapper"},function(){if(!(a||!O||O.length<=1))return n.a.createElement("div",{className:"photo-dashes"},O.map((e,t)=>n.a.createElement("span",{className:"photo-dash "+(t===g?"current":"")})))}(),n.a.createElement(ae.a,{activeKey:g,name:j,className:"profile-slide-container"},w),!p&&n.a.createElement("button",{type:"button",className:"navigation prev","aria-label":v("AccDescrPrevious"),onClick:C}),!I&&n.a.createElement("button",{type:"button",className:"navigation next","aria-label":v("Next"),onClick:E})),n.a.createElement("div",{className:"info",dir:v.isRtl?"rtl":"auto"},a?n.a.createElement("div",{className:"title"},n.a.createElement("h3",{dir:"auto"},v("SavedMessages"))):n.a.createElement("div",{className:"title"},n.a.createElement("h3",{dir:"auto"},u&&Object(tt.a)(u)),M&&n.a.createElement(ec.a,null)),!a&&(e?n.a.createElement("div",{className:"status "+(Object(m.xb)(e)?"online":"")},n.a.createElement("span",{className:"user-status",dir:"auto"},Object(m.ab)(v,e))):n.a.createElement("span",{className:"status",dir:"auto"},Object(m.jb)(t)?v("Subscribers",t.membersCount,"i"):v("Members",t.membersCount,"i")))))}));var cc=Object(n.h)(Object(s.h)((e,{chatOrUserId:t})=>{const{lastSyncTime:a}=e,s=t?Object(o.f)(e,t):void 0;return{lastSyncTime:a,chat:s,user:Object(m.lb)(t)?Object(o.Gb)(e,t):void 0,canInviteUsers:s&&(!Object(m.jb)(s)&&!Object(m.yb)(s,"inviteUsers")||Object(m.q)(s,"inviteUsers"))}},(e,t)=>Object(d.l)(t,["loadFullUser","updateChatMutedState","showNotification"]))(({lastSyncTime:e,user:t,chat:a,forceShowSelf:s,canInviteUsers:c,loadFullUser:r,showNotification:o,updateChatMutedState:i})=>{const{id:l,fullInfo:d,username:b,phoneNumber:u,isSelf:h}=t||{},{id:O,isMuted:j,username:g}=a||{},f=Object(ce.a)();Object(n.n)(()=>{e&&l&&r({userId:l})},[r,l,e]);const p=Object(n.m)(()=>{i({chatId:O,isMuted:!j})},[O,j,i]);if(!a||a.isRestricted||h&&!s)return;function I(e,t){Object(E.c)(e),o({message:t+" was copied"})}const v=u&&Object(Oa.c)(u),y=Object(m.h)(a),C=0===y.indexOf("http")?y:"http://"+y,w=b||g,M=d&&d.bio||Object(m.g)(a);return n.a.createElement("div",{className:"ChatExtra"},v&&!!v.length&&n.a.createElement(Zs.a,{icon:"phone",multiline:!0,narrow:!0,ripple:!0,onClick:()=>I(v,f("Phone"))},n.a.createElement("span",{className:"title",dir:"auto"},v),n.a.createElement("span",{className:"subtitle"},f("Phone"))),w&&n.a.createElement(Zs.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>I("@"+w,f("Username"))},n.a.createElement("span",{className:"title",dir:"auto"},Object(tt.a)(w)),n.a.createElement("span",{className:"subtitle"},f("Username"))),M&&!!M.length&&n.a.createElement(Zs.a,{icon:"info",multiline:!0,narrow:!0,isStatic:!0},n.a.createElement("span",{className:"title",dir:"auto"},Object(tt.a)(M,["br","links","emoji"])),n.a.createElement("span",{className:"subtitle"},f(l?"UserBio":"Info"))),c&&!w&&!!y.length&&n.a.createElement(Zs.a,{icon:"mention",multiline:!0,narrow:!0,ripple:!0,onClick:()=>I(y,f("SetUrlPlaceholder"))},n.a.createElement("div",{className:"title"},n.a.createElement(wa.a,{url:C,className:"title",text:y})),n.a.createElement("span",{className:"subtitle"},f("SetUrlPlaceholder"))),n.a.createElement(Zs.a,{icon:"unmute",ripple:!0,onClick:p},n.a.createElement("span",null,f("Notifications")),n.a.createElement(de,{id:"group-notifications",label:l?"Toggle User Notifications":"Toggle Chat Notifications",checked:!j,inactive:!0})))})),nc=a(165),rc=a(185),oc=a(118);a(249);const ic=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"}];function lc(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > div.active > .${e}-list > .scroll-item`].join(", ")}var dc=Object(n.h)(Object(s.h)((e,{chatId:t,userId:a})=>{const s=Object(o.f)(e,t),c=Object(o.m)(e,a||t),{currentType:n,resultsByType:r}=Object(o.v)(e)||{},{foundIds:i}=r&&n&&r[n]||{},{byId:l}=e.users,d=s&&Object(m.kb)(s),b=s&&Object(m.jb)(s),u=d||b&&Object(m.gb)(s),h=s&&s.fullInfo&&s.fullInfo.members,O=u&&s&&s.fullInfo&&!s.fullInfo.canViewMembers;let j;return a?j=a:Object(m.lb)(t)&&(j=t),{isChannel:b,resolvedUserId:j,chatMessages:c,foundIds:i,mediaSearchType:n,hasMembersTab:u,areMembersHidden:O,...u&&h&&{members:h,usersById:l},isRightColumnShown:Object(o.W)(e),isRestricted:s&&s.isRestricted,lastSyncTime:e.lastSyncTime}},(e,t)=>Object(d.l)(t,["setLocalMediaSearchType","loadMoreMembers","searchMediaMessagesLocal","openMediaViewer","openAudioPlayer","openUserInfo","focusMessage","loadProfilePhotos"]))(({chatId:e,profileState:t,onProfileStateChange:a,isChannel:s,resolvedUserId:r,chatMessages:o,foundIds:d,mediaSearchType:b,hasMembersTab:u,areMembersHidden:m,members:O,usersById:j,isRightColumnShown:g,isRestricted:f,lastSyncTime:p,setLocalMediaSearchType:I,loadMoreMembers:v,searchMediaMessagesLocal:y,openMediaViewer:C,openAudioPlayer:E,openUserInfo:w,focusMessage:M,loadProfilePhotos:S})=>{const k=Object(n.q)(null),N=Object(n.q)(null),P=Object(ce.a)(),[T,A]=Object(n.r)(0),x=Object(n.p)(()=>[...u?[{type:"members",title:s?"ChannelSubscribers":"GroupMembers"}]:[],...ic],[u,s]),R=x[T].type,[L,F,D,B]=Ws(0,v,y,R,b,O,j,o,d,0,p),U=x.findIndex(({type:e})=>e===L),{handleScroll:H}=function(e,t,a,s){Object(Qs.a)(([a])=>{if(a&&a!==t){const a=e.current,c=a.querySelector(".TabList");a.scrollTop{Xs=!1},350))}},[t,s]),Object(Qs.a)(([t])=>{if(a!==l.k.Profile||a===t)return;const c=e.current;if(!c)return;const n=c.querySelector(".TabList");!n||n.offsetTop>c.scrollTop||(Xs=!0,Object(vt.a)(c,c.firstElementChild,"start",void 0,2*c.offsetHeight),setTimeout(()=>{Xs=!1},350),s(a))},[a]);const c=Object(n.m)(()=>{const a=e.current;if(!a)return;const c=a.querySelector(".TabList");if(!c)return;let n=l.k.Profile;a.scrollTop>=c.offsetTop&&(n="members"===t?l.k.MemberList:l.k.SharedMedia),s(n)},[e,s,t]);return Object(n.n)(()=>{Xs||c()},[c,t]),{handleScroll:Object(n.m)(()=>{Xs||Ys(c)},[c])}}(k,R,t,a),{applyTransitionFix:G,releaseTransitionFix:q}=function(e,t=".Transition.shared-media-transition"){return Object(n.n)(()=>{function a(){const a=e.current,s=a.querySelector(t),c=a.querySelector(".TabList");s&&c&&(s.style.minHeight=a.offsetHeight-c.offsetHeight+"px")}return a(),window.addEventListener("resize",a,!1),()=>{window.removeEventListener("resize",a,!1)}},[e,t]),{applyTransitionFix:Object(n.m)(()=>{const t=e.current;if("hidden"!==t.style.overflowY){const e=t.offsetWidth-t.clientWidth;t.style.overflowY="hidden",t.style.marginRight=e+"px"}},[e]),releaseTransitionFix:Object(n.m)(()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"},[e])}}(k),[_,V]=(()=>{const[e,t]=Object(n.r)(!1);return[e,Object(n.m)(()=>{t(e=>!e)},[])]})(),$=Object(n.m)(()=>{q(),V()},[q,V]);Object(n.n)(()=>{I({mediaType:R})},[I,R]);const z=r||e;Object(n.n)(()=>{p&&S({profileId:z})},[S,z,p]);const W=Object(n.m)(e=>{C({chatId:z,threadId:i.MAIN_THREAD_ID,messageId:e,origin:l.h.SharedMedia})},[z,C]),K=Object(n.m)(e=>{E({chatId:z,messageId:e})},[z,E]),Q=Object(n.m)(e=>{w({id:e})},[w]),Y=Object(n.m)(e=>{M({chatId:z,messageId:e})},[z,M]);let X;Object(n.n)(()=>{if(N.current&&h.l)return Object(Oe.b)(N.current,{onSwipe:(e,t)=>{t===Oe.a.Left?A(Math.min(T+1,x.length-1)):t===Oe.a.Right&&A(Math.max(0,T-1))}})},[T,x.length]);const J="members"===L||!u&&"media"===L;J?X=g?0:1e3:F||(X=c.pb);const Z=Object(Es.a)([e,L],X);function ee(){if(!F||!Z||!o){const e=J&&F&&!Z;return n.a.createElement("div",{className:"content empty-list"},!e&&n.a.createElement(me.a,null))}if(!F.length){let e;switch(L){case"members":e=m?"You have no access to group members list.":"No members found";break;case"documents":e=P("lng_media_file_empty_search");break;case"links":e=P("lng_media_link_empty_search");break;case"audio":e=P("lng_media_song_empty_search");break;default:e=P("SharedMedia.EmptyTitle")}return n.a.createElement("div",{className:"content empty-list"},n.a.createElement(oc.a,{text:e}))}return n.a.createElement("div",{className:`content ${L}-list`,dir:P.isRtl&&"media"===L?"rtl":void 0,teactFastList:!0},"media"===L?F.map(e=>o[e]&&n.a.createElement(nc.a,{key:e,message:o[e],onClick:W})):"documents"===L?F.map(e=>o[e]&&n.a.createElement(zt.a,{key:e,message:o[e],withDate:!0,smaller:!0,className:"scroll-item",onDateClick:Y})):"links"===L?F.map(e=>o[e]&&n.a.createElement(rc.a,{key:e,message:o[e],onMessageClick:Y})):"audio"===L?F.map(e=>o[e]&&n.a.createElement(Wt.a,{key:e,renderingFor:"sharedMedia",message:o[e],date:o[e].date,lastSyncTime:p,className:"scroll-item",onPlay:K,onDateClick:Y})):"members"===L?F.map((e,t)=>n.a.createElement(Zs.a,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item",onClick:()=>Q(e)},n.a.createElement(Ye.a,{userId:e,forceShowSelf:!0}))):void 0)}return n.a.createElement(Js.a,{ref:k,className:"Profile custom-scroll",itemSelector:lc(L),items:Z?F:void 0,cacheBuster:_,sensitiveArea:c.fb,preloadBackwards:Z?"members"===L?c.R:c.ob:0,noScrollRestoreOnTop:!0,noFastList:!0,onLoadMore:D,onScroll:H},!B&&function(e,t){return n.a.createElement("div",{className:"profile-info"},n.a.createElement(sc,{userId:t||e,forceShowSelf:t!==e}),n.a.createElement(cc,{chatOrUserId:t||e,forceShowSelf:t!==e}))}(e,r),!f&&n.a.createElement("div",{className:"shared-media"},n.a.createElement(ae.a,{ref:N,name:P.isRtl?"slide-reversed":"slide",activeKey:U,renderCount:x.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:G,onStop:$},ee),n.a.createElement(pe.a,{big:!0,activeTab:T,tabs:x,onSwitchTab:A})))}));var bc=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"RightSearch");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)});var uc=Object(n.h)(e=>{const t=Object(Ce.a)(ye.a.Extra,"Management");return t?n.a.createElement(t,e):n.a.createElement(Ee.a,null)});var mc=Object(n.h)(()=>{const e=Object(Ce.a)(ye.a.Extra,"StickerSearch");return e?n.a.createElement(e,null):n.a.createElement(Ee.a,null)});var hc=Object(n.h)(()=>{const e=Object(Ce.a)(ye.a.Extra,"GifSearch");return e?n.a.createElement(e,null):n.a.createElement(Ee.a,null)});var Oc=Object(n.h)(()=>{const e=Object(Ce.a)(ye.a.Extra,"PollResults");return e?n.a.createElement(e,null):n.a.createElement(Ee.a,null)});a(250);const jc=Object.keys(l.l).length/2,gc=Object.keys(l.g).length/2;function fc(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}var pc=Object(n.h)(Object(s.h)(e=>{const{chatId:t,threadId:a}=Object(o.y)(e)||{},s=Object(o.d)(e);return{contentKey:Object(o.nb)(e),chatId:t,threadId:a,currentProfileUserId:e.users.selectedId,isChatSelected:Boolean(t&&s)}},(e,t)=>Object(d.l)(t,["openUserInfo","toggleChatInfo","toggleManagement","closeLocalTextSearch","setStickerSearchQuery","setGifSearchQuery","closePollResults"]))(({contentKey:e,chatId:t,threadId:a,currentProfileUserId:s,isChatSelected:r,toggleChatInfo:o,toggleManagement:i,openUserInfo:d,closeLocalTextSearch:b,setStickerSearchQuery:u,setGifSearchQuery:m,closePollResults:h})=>{var O;const{width:j}=_e(),[g,f]=Object(n.r)(l.k.Profile),[p,I]=Object(n.r)(l.g.Initial),[v,y]=Object(n.r)(),[C,E]=Object(n.r)(),w=g!==l.k.Profile,M=void 0!==e,S=e===l.l.ChatInfo||e===l.l.UserInfo,k=e===l.l.Search,N=e===l.l.Management,P=e===l.l.StickerSearch,T=e===l.l.GifSearch,A=e===l.l.PollResults,x=j<=c.ab,[R,L]=Object(n.r)(!M),F=null!==(O=Object(Ke.a)(e,!0,!r))&&void 0!==O?O:-1,D=Object(n.m)(()=>{switch(e){case l.l.ChatInfo:if(w){f(l.k.Profile);break}o();break;case l.l.UserInfo:if(w){f(l.k.Profile);break}d({id:void 0});break;case l.l.Management:switch(p){case l.g.Initial:i();break;case l.g.ChatPrivacyType:case l.g.Discussion:case l.g.GroupPermissions:case l.g.GroupType:case l.g.ChatAdministrators:case l.g.ChannelSubscribers:case l.g.GroupMembers:I(l.g.Initial);break;case l.g.GroupUserPermissionsCreate:case l.g.GroupRemovedUsers:case l.g.GroupUserPermissions:I(l.g.GroupPermissions),y(void 0),E(void 0);break;case l.g.ChatAdminRights:case l.g.GroupRecentActions:I(l.g.ChatAdministrators)}break;case l.l.Search:fc(),b();break;case l.l.StickerSearch:case l.l.GifSearch:fc(),u({query:void 0}),m({query:void 0});break;case l.l.PollResults:h()}},[e,w,o,d,h,p,i,b,u,m]),B=Object(n.m)((e,t)=>{y(e),E(t)},[]);function U(){if(-1!==F)switch(F){case l.l.ChatInfo:case l.l.UserInfo:return n.a.createElement(dc,{key:s||t,chatId:t,userId:s,profileState:g,onProfileStateChange:f});case l.l.Search:return n.a.createElement(bc,{chatId:t,threadId:a});case l.l.Management:return n.a.createElement(uc,{chatId:t,currentScreen:p,isPromotedByCurrentUser:C,selectedChatMemberId:v,onScreenSelect:I,onChatMemberSelect:B});case l.l.StickerSearch:return n.a.createElement(mc,null);case l.l.GifSearch:return n.a.createElement(hc,null);case l.l.PollResults:return n.a.createElement(Oc,null)}}return Object(n.n)(()=>M?Object(te.a)(D):void 0,[M,D]),Object(n.n)(()=>{setTimeout(()=>{L(!M)},300)},[M]),Object(n.n)(()=>{M&&x&&D()},[x]),Object(Ot.a)(([a,s])=>{(a===l.l.ChatInfo&&e===l.l.UserInfo||a===l.l.UserInfo&&e===l.l.ChatInfo||s!==t)&&(f(l.k.Profile),I(l.g.Initial))},[e,t]),n.a.createElement("div",{id:"RightColumn-wrapper",className:r?void 0:"is-hidden"},x&&n.a.createElement("div",{className:"overlay-backdrop",onClick:D}),n.a.createElement("div",{id:"RightColumn"},n.a.createElement($s,{chatId:t,isColumnOpen:M,isProfile:S,isSearch:k,isManagement:N,isStickerSearch:P,isGifSearch:T,isPollResults:A,profileState:g,managementScreen:p,onClose:D}),n.a.createElement(ae.a,{name:R?"none":"zoom-fade",renderCount:jc+gc,activeKey:N?jc+p:F},U)))}));var Ic=Object(n.h)(({isOpen:e})=>{const t=Object(Ce.a)(ye.a.Extra,"MediaViewer",!e);return t?n.a.createElement(t,null):void 0});var vc=Object(n.h)(({isOpen:e})=>{const t=Object(Ce.a)(ye.a.Extra,"Notifications",!e);return t?n.a.createElement(t,null):void 0});var yc=Object(n.h)(({isOpen:e})=>{const t=Object(Ce.a)(ye.a.Extra,"Errors",!e);return t?n.a.createElement(t,null):void 0});var Cc=Object(n.h)(e=>{const{isOpen:t}=e,a=Object(Ce.a)(ye.a.Extra,"ForwardPicker",!t);return a?n.a.createElement(a,e):void 0});var Ec=Object(n.h)(e=>{const{url:t}=e,a=Object(Ce.a)(ye.a.Extra,"SafeLinkModal",!t);return a?n.a.createElement(a,e):void 0});a(251);let wc,Mc,Sc=!1;function kc(e){document.querySelectorAll('link[rel="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")})}var Nc=Object(n.h)(Object(s.h)(e=>{const{chatId:t,messageId:a}=e.audioPlayer,s=t&&a?Object(o.k)(e,t,a):void 0;return{animationLevel:e.settings.byKey.animationLevel,lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:Object(o.W)(e),isMediaViewerOpen:Object(o.T)(e),isForwardModalOpen:Object(o.R)(e),hasNotifications:Boolean(e.notifications.length),hasErrors:Boolean(e.errors.length),audioMessage:s,safeLinkModalUrl:e.safeLinkModalUrl}},(e,t)=>Object(d.l)(t,["loadAnimatedEmojis"]))(({lastSyncTime:e,loadAnimatedEmojis:t,isLeftColumnShown:a,isRightColumnShown:r,isMediaViewerOpen:i,isForwardModalOpen:l,animationLevel:d,hasNotifications:b,hasErrors:u,audioMessage:m,safeLinkModalUrl:h})=>{c.p&&!Sc&&(Sc=!0,console.log(">>> RENDER MAIN")),Object(n.n)(()=>{e&&t()},[e,t]);const{transitionClassNames:O}=Object(Z.a)(!a,void 0,!0),{transitionClassNames:j}=Object(Z.a)(r,void 0,!0),g=Object(J.a)(O.replace(/([\w-]+)/g,"middle-column-$1"),j.replace(/([\w-]+)/g,"right-column-$1"));function f(e){e.preventDefault(),e.stopPropagation()}return Object(n.n)(()=>{document.body.classList.toggle("is-middle-column-open",g.includes("middle-column-open")),document.body.classList.toggle("is-right-column-shown",g.includes("right-column-open"))},[g]),Object(n.n)(()=>{d>0&&(document.body.classList.add("animating-right-column"),Object(X.b)(350+c.c),wc&&(clearTimeout(wc),wc=void 0),wc=window.setTimeout(()=>{document.body.classList.remove("animating-right-column"),wc=void 0},350+c.c))},[d,r]),Object(ee.a)(()=>{const e=Object(o.q)(Object(s.e)());let t=0;clearInterval(Mc),Mc=window.setInterval(()=>{if(document.title.includes(c.D))kc(!1);else{if(t%2==0){const t=Object(o.q)(Object(s.e)())-e;t>0&&(document.title=`${t} notification${t>1?"s":""}`,kc(!0))}else document.title=c.eb,kc(!1);t++}},1e3)},()=>{clearInterval(Mc),Mc=void 0,document.title.includes(c.D)||(document.title=c.eb),kc(!1)}),n.a.createElement("div",{id:"Main",className:g,onDrop:f,onDragOver:f},n.a.createElement(Be,null),n.a.createElement(qs,null),n.a.createElement(pc,null),n.a.createElement(Ic,{isOpen:i}),n.a.createElement(Cc,{isOpen:l}),n.a.createElement(vc,{isOpen:b}),n.a.createElement(yc,{isOpen:u}),m&&n.a.createElement(mt,{key:m.id,message:m,noUi:!0}),n.a.createElement(Ec,{url:h}))}));c.p&&console.log(">>> FINISH LOAD MAIN BUNDLE"),Object(s.e)().connectionState||Object(s.d)().initApi()},197:function(e,t,a){},198:function(e,t,a){},199:function(e,t,a){},210:function(e,t,a){},211:function(e,t,a){},212:function(e,t,a){},215:function(e,t,a){},216:function(e,t,a){},217:function(e,t,a){},221:function(e,t,a){},222:function(e,t,a){},224:function(e,t,a){},227:function(e,t,a){},228:function(e,t,a){},229:function(e,t,a){},230:function(e,t,a){},231:function(e,t,a){},232:function(e,t,a){},233:function(e,t,a){},234:function(e,t,a){},235:function(e,t,a){},236:function(e,t,a){},237:function(e,t,a){},239:function(e,t,a){},240:function(e,t,a){},241:function(e,t,a){},242:function(e,t,a){},243:function(e,t,a){},244:function(e,t,a){},245:function(e,t,a){},249:function(e,t,a){},250:function(e,t,a){},251:function(e,t,a){}}]); -//# sourceMappingURL=4.92917cccdb4999ea7d20.js.map \ No newline at end of file diff --git a/dist/4.92917cccdb4999ea7d20.js.map b/dist/4.92917cccdb4999ea7d20.js.map deleted file mode 100644 index 59bed917..00000000 --- a/dist/4.92917cccdb4999ea7d20.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///./src/modules/actions/ui/chats.ts","webpack:///./src/modules/actions/ui/messages.ts","webpack:///./src/modules/actions/ui/globalSearch.ts","webpack:///./src/modules/actions/ui/localSearch.ts","webpack:///./src/modules/actions/ui/stickerSearch.ts","webpack:///./src/modules/actions/ui/users.ts","webpack:///./src/modules/actions/ui/settings.ts","webpack:///./src/modules/actions/ui/misc.ts","webpack:///./src/modules/actions/ui/payments.ts","webpack:///./src/modules/actions/api/chats.ts","webpack:///./src/modules/actions/api/messages.ts","webpack:///./src/modules/actions/api/symbols.ts","webpack:///./src/modules/actions/api/globalSearch.ts","webpack:///./src/modules/actions/api/sync.ts","webpack:///./src/modules/actions/api/localSearch.ts","webpack:///./src/modules/actions/api/management.ts","webpack:///./src/modules/actions/api/users.ts","webpack:///./src/modules/actions/api/settings.ts","webpack:///./src/modules/actions/api/bots.ts","webpack:///./src/modules/actions/api/twoFaSettings.ts","webpack:///./src/modules/actions/api/payments.ts","webpack:///./src/util/requestQuery.ts","webpack:///./src/modules/actions/apiUpdaters/chats.ts","webpack:///./src/modules/actions/apiUpdaters/messages.ts","webpack:///./src/modules/actions/apiUpdaters/users.ts","webpack:///./src/modules/actions/apiUpdaters/symbols.ts","webpack:///./src/modules/actions/apiUpdaters/misc.ts","webpack:///./src/modules/actions/apiUpdaters/settings.ts","webpack:///./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack:///./src/components/ui/Switcher.tsx","webpack:///./src/components/left/main/LeftMainHeader.tsx","webpack:///./src/components/left/ConnectionState.tsx","webpack:///./src/hooks/useThrottledMemo.ts","webpack:///./src/hooks/useThrottle.ts","webpack:///./src/components/left/main/ChatFolders.tsx","webpack:///./src/components/left/search/LeftSearch.async.tsx","webpack:///./src/components/left/main/ContactList.async.tsx","webpack:///./src/components/left/NewChatButton.tsx","webpack:///./src/components/left/main/LeftMain.tsx","webpack:///./src/components/left/settings/Settings.async.tsx","webpack:///./src/components/left/newChat/NewChat.async.tsx","webpack:///./src/components/left/ArchivedChats.async.tsx","webpack:///./src/components/left/LeftColumn.tsx","webpack:///./src/hooks/useWindowSize.ts","webpack:///./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack:///./src/components/middle/HeaderMenuContainer.async.tsx","webpack:///./src/components/middle/HeaderActions.tsx","webpack:///./src/hooks/useWebpThumbnail.ts","webpack:///./src/components/middle/PinnedMessageNavigation.tsx","webpack:///./src/components/middle/HeaderPinnedMessage.tsx","webpack:///./src/components/middle/AudioPlayer.tsx","webpack:///./src/components/middle/MiddleHeader.tsx","webpack:///./src/components/middle/helpers/groupMessages.ts","webpack:///./src/components/middle/hooks/useStickyDates.ts","webpack:///./src/hooks/useDebounce.ts","webpack:///./src/components/middle/MessageScroll.tsx","webpack:///./src/components/middle/message/helpers/buildContentClassName.ts","webpack:///./src/components/middle/message/helpers/mediaDimensions.ts","webpack:///./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack:///./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack:///./src/components/middle/message/hooks/useFocusMessage.ts","webpack:///./src/components/middle/message/ContextMenuContainer.async.tsx","webpack:///./src/components/middle/ActionMessage.tsx","webpack:///./src/components/common/EmbeddedMessage.tsx","webpack:///./src/components/middle/message/MessageMeta.tsx","webpack:///./src/components/middle/message/Sticker.tsx","webpack:///./src/components/middle/message/hooks/useBlurredMediaThumbRef.ts","webpack:///./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack:///./src/components/middle/message/Photo.tsx","webpack:///./src/hooks/useHeavyAnimationCheckForVideo.ts","webpack:///./src/components/middle/message/hooks/usePauseOnInactive.ts","webpack:///./src/components/middle/message/Video.tsx","webpack:///./src/components/middle/message/Contact.tsx","webpack:///./src/components/ui/CheckboxGroup.tsx","webpack:///./src/components/middle/message/PollOption.tsx","webpack:///./src/components/middle/message/Poll.tsx","webpack:///./src/components/middle/message/WebPage.tsx","webpack:///./src/components/middle/message/Invoice.tsx","webpack:///./src/components/middle/message/hocs/withSelectControl.tsx","webpack:///./src/components/middle/message/Album.tsx","webpack:///./src/components/middle/message/RoundVideo.tsx","webpack:///./src/components/middle/message/InlineButtons.tsx","webpack:///./src/components/middle/message/CommentButton.tsx","webpack:///./src/components/middle/message/Message.tsx","webpack:///./src/components/middle/MessageList.tsx","webpack:///./src/components/middle/ScrollDownButton.tsx","webpack:///./src/components/middle/composer/helpers/buildAttachment.ts","webpack:///./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack:///./src/util/voiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack:///./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack:///./src/components/middle/composer/hooks/useDraft.ts","webpack:///./src/components/common/DeleteMessageModal.async.tsx","webpack:///./src/components/ui/ResponsiveHoverButton.tsx","webpack:///./src/components/middle/composer/AttachMenu.async.tsx","webpack:///./src/components/middle/composer/SymbolMenu.async.tsx","webpack:///./src/components/middle/composer/MentionTooltip.async.tsx","webpack:///./src/components/middle/composer/CustomSendMenu.async.tsx","webpack:///./src/components/middle/composer/StickerTooltip.async.tsx","webpack:///./src/components/middle/composer/BotKeyboardMenu.async.tsx","webpack:///./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack:///./src/components/middle/composer/AttachmentModal.async.tsx","webpack:///./src/components/middle/composer/PollModal.async.tsx","webpack:///./src/components/middle/composer/DropArea.async.tsx","webpack:///./src/components/middle/composer/WebPagePreview.tsx","webpack:///./src/components/common/CalendarModal.async.tsx","webpack:///./src/components/payment/PaymentModal.async.tsx","webpack:///./src/components/payment/ReceiptModal.async.tsx","webpack:///./src/components/middle/composer/Composer.tsx","webpack:///./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack:///./src/components/middle/composer/hooks/useStickerTooltip.ts","webpack:///./src/util/insertHtmlInSelection.ts","webpack:///./src/util/deleteLastCharacterOutsideSelection.ts","webpack:///./src/components/middle/composer/hooks/useEditing.ts","webpack:///./src/components/middle/MobileSearch.async.tsx","webpack:///./src/components/middle/MessageSelectToolbar.async.tsx","webpack:///./src/components/common/UnpinAllMessagesModal.async.tsx","webpack:///./src/components/middle/MiddleColumn.tsx","webpack:///./src/hooks/useCustomBackground.ts","webpack:///./src/components/right/RightHeader.tsx","webpack:///./src/components/right/hooks/useProfileViewportIds.ts","webpack:///./src/components/right/hooks/useProfileState.ts","webpack:///./src/components/right/ProfilePhoto.tsx","webpack:///./src/components/right/ProfileInfo.tsx","webpack:///./src/components/right/hooks/usePhotosPreload.ts","webpack:///./src/components/right/ChatExtra.tsx","webpack:///./src/components/right/Profile.tsx","webpack:///./src/components/right/hooks/useTransitionFixes.ts","webpack:///./src/hooks/useCacheBuster.ts","webpack:///./src/components/right/RightSearch.async.tsx","webpack:///./src/components/right/management/Management.async.tsx","webpack:///./src/components/right/StickerSearch.async.tsx","webpack:///./src/components/right/GifSearch.async.tsx","webpack:///./src/components/right/PollResults.async.tsx","webpack:///./src/components/right/RightColumn.tsx","webpack:///./src/components/mediaViewer/MediaViewer.async.tsx","webpack:///./src/components/main/Notifications.async.tsx","webpack:///./src/components/main/Errors.async.tsx","webpack:///./src/components/main/ForwardPicker.async.tsx","webpack:///./src/components/main/SafeLinkModal.async.tsx","webpack:///./src/components/main/Main.tsx","webpack:///./src/bundles/main.ts"],"names":["window","addEventListener","e","state","chatId","id","threadId","messageListType","type","getDispatch","openChat","noPushState","addReducer","global","actions","payload","currentMessageList","selectCurrentMessageList","exitMessageSelectMode","messages","contentToBeScheduled","undefined","forwardMessages","toChatId","setGlobal","history","pushState","updateCurrentMessageList","isChatInfoShown","chatCreation","blurTimeout","scrollOffset","replaceThreadParam","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","targetIndexDelta","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","indexOf","toString","length","Number","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","audioPlayer","selectIsRightColumnShown","pollResults","voters","setTimeout","newGlobal","getGlobal","noHighlight","groupedId","groupedChatId","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","Static","includes","direction","Down","Up","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","isPollModalOpen","query","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","filter","unshift","pop","content","updateGlobalSearchContent","updateLocalTextSearch","replaceLocalTextSearchResults","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","replaceSettings","theme","settings","replaceThemeSettings","management","byChatId","isActive","IS_MOBILE_SCREEN","isLeftColumnShown","action","emoji","recentEmojis","newEmojis","sticker","recent","hash","newStickers","s","notification","newNotifications","notifications","existingNotificationIndex","findIndex","n","message","splice","push","error","getReadableErrorText","newErrors","errors","existingErrorIndex","err","url","safeLinkModalUrl","payment","isPaymentModalOpen","clearPayment","closeInvoice","runThrottledForLoadChats","throttle","cb","runThrottledForLoadTopChats","runDebouncedForLoadFullChat","debounce","async","loadChats","listType","offsetDate","result","callApi","limit","CHAT_LIST_LOAD_SLICE","archived","withPinned","orderedPinnedIds","chatIds","shift","addUsers","buildCollectionByKey","users","updateChats","updateChatListIds","updateChatListSecondaryInfo","draftsById","map","forEach","replyingToById","isFullyLoaded","loadFullChat","fullInfo","updateChat","openChatByUsername","username","channelPostId","localChat","selectChatByUsername","isMin","previousChat","showNotification","preloadedChatIds","i","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","pause","byId","listIds","active","currentChatId","pinnedChats","otherChats","prepareChatList","chatToPreload","find","currentUserId","hasUnreadMark","toggleChatUnread","isChatSummaryOnly","requestChatUpdate","user","selectUser","selectThreadTopMessageId","requestThreadInfoUpdate","selectSupportChat","TIPS_USERNAME","oldestChat","selectIsChatPinned","sort","chat1","chat2","date","force","isMuted","title","about","photo","memberIds","progress","ChatCreationProgress","InProgress","createdChannel","channelId","accessHash","Complete","Error","createChannel","createdChat","createGroupChat","folderId","folder","selectChatFolder","shouldBePinned","pinnedChatIds","includedChatIds","newPinnedIds","pinnedId","newIncludedChatIds","folderUpdate","selectChatListType","isPinned","ARCHIVED_FOLDER_ID","isChatArchived","chatFolders","loadChatFolders","recommendedChatFolders","recommended","loadRecommendedChatFolders","emoticon","orderedIds","maxId","recommendedId","description","newFolder","createChatFolder","Math","max","apply","deleteChatFolder","unreadCount","match","RE_TME_INVITE_LINK","exec","RE_TME_LINK","isEnabled","isChatBasicGroup","bannedRights","userId","chatAfterUpdate","members","kickedMembers","isBanned","viewMessages","isUnblocked","m","adminRights","customTitle","adminMembers","isDismissed","updateManagementProgress","ManagementProgress","Promise","all","groups","addedById","reduce","group","addChats","forDiscussionIds","channel","fullChat","isPreHistoryHidden","linkedChatId","activeChatFolder","offset","uploadProgressCallbacks","Map","runThrottledForMarkRead","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","Backwards","Around","round","MESSAGE_LIST_SLICE","Forwards","selectThreadOriginChat","threadInfos","addChatMessagesById","updateOutlyingIds","updateListedIds","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","findClosestIndex","indexForDirection","from","to","slice","areSomeLocal","areAllLocal","sendMessage","params","localId","progressCallback","attachment","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","rafPromise","delete","isRestricted","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","scheduledAt","clearWebPagePreview","value","noWebPage","selectNoWebPage","isSingle","attachments","isGrouped","restParams","text","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","apiUpdate","draft","replyToMsgId","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","webPagePreview","loadWebPagePreview","options","option","shouldResetVoters","v","a","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","b","scheduledMessages","historyHash","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","loadPinnedMessages","copyTextToClipboard","link","searchThrottled","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","featured","featuredStickers","loadFeaturedStickers","stickerSetAccessHash","stickerSet","selectStickerSet","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","selectEmojiKeywords","isLoading","emojiKeywords","fromVersion","version","keywords","setsById","searchWords","searchStickers","updateStickersForEmoji","loadStickersForEmoji","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","loadAndReplaceArchivedChats","updateUsers","replaceChatListIds","loadAndUpdateUsers","userIds","contactIds","contactList","updatedUsers","localChats","localUsers","globalChats","globalUsers","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","searchMessagesByDate","updateManagement","isUsernameAvailable","afterSyncCallback","DEBUG","console","log","savedUsers","savedPrivateChatIds","savedChats","selectedChat","isChatPrivate","selectedChatUser","replaceChats","loadAndReplaceChats","areMessagesLoaded","draftsByChatId","acc","lastReadInboxMessageId","newCurrentChatId","currentMessageListInfo","threadsById","Array","prototype","concat","replaceUsers","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","sync","afterSync","runDebouncedForFetchFullUser","buildInputPrivacyRules","visibility","allowedIds","deniedIds","usersById","chatsById","rules","collectUsers","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","lastRequestedAt","topPeers","usersHash","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","updateChatMutedState","phone","phoneNumber","updateUser","updateContact","deleteUser","profileId","isPrivate","photos","button","sendBotCommand","command","openTelegramLink","toggleSafeLinkModal","data","alert","isError","showError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bio","profileEdit","ProfileEditProgress","currentUser","Idle","loadedWallpapers","wallpapers","file","previewBlobUrl","URL","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","document","fileName","size","mimeType","wallpaper","firstWallpaper","withLocalMedia","blocked","blockedIds","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","peerType","shouldShowPreviews","updateNotifySettings","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","Shipping","PaymentInfo","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","ShippingInfo","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","join","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","Checkout","sendStipeCredentials","shippingOptionId","saveCredentials","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","runThrottledForUpdateAppBadge","update","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","selectCountNotMutedUnread","updateAppBadge","isNotJoined","listId","typingStatus","senderId","isFromScheduled","isActiveChat","hasUnreadMention","unreadMentionsCount","showNewMessageNotification","messageUpdate","selectCommonBoxChatId","targetChat","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","updateChatListType","chatFoldersById","newChatFoldersById","pick","newOrderedIds","orderedId","folders","replacedMembers","addedMember","deletedMemberId","shouldUpdate","some","deleteIndex","isOwner","isAdmin","membersCount","updateWithLocalMedia","isScheduled","currentMessage","video","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","updateScheduledMessage","updateListedAndViewportIds","firstUnreadId","selectFirstUnreadId","addViewportId","firstMessageId","selectThreadByMessage","isMessageLocal","updateChatLastMessage","currentLastMessage","findLastMessage","isDeleting","deleteMessages","newLastMessage","threadIdsToUpdate","unique","deleteChatMessages","chatsIdsToUpdate","commonBoxChatId","updateThreadInfo","newMessage","isMessageInCurrentMessageList","isOutgoing","scheduledIds","selectScheduledIds","selectScheduledMessages","deleteChatScheduledMessages","currentPinnedIds","selectPinnedIds","newTheadInfo","messagesById","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","poll","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","newResults","targetOption","targetOptionIndex","updatedOption","votersCount","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","key","addNotifyException","twoFaSettings","memo","name","label","checked","disabled","inactive","noAnimation","onChange","onCheck","handleChange","useCallback","currentTarget","className","buildClassName","ANIMATION_LEVEL_OPTIONS","withGlobal","searchQuery","animationLevel","byKey","globalSearchChatId","searchDate","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","setGlobalSearchChatId","onReset","openTipsChat","setGlobalSearchDate","setSettingOption","lang","useLang","hasMenu","LeftColumnContent","ChatList","clearedDateSearchParam","clearedChatSearchParam","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","MainButton","onTrigger","isOpen","Button","ripple","color","onClick","ariaLabel","handleSearchFocus","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","switchTheme","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","GlobalSearch","Contacts","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","APP_VERSION","MenuItem","icon","toLowerCase","href","FEEDBACK_URL","localStorage","setItem","JSON","stringify","SearchInput","inputId","parentContainerClassName","focused","placeholder","autoComplete","canClose","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","connectionState","dir","isRtl","Spinner","resolverFn","ms","dependencies","valueRef","useRef","runThrottled","useThrottle","forceUpdate","useForceUpdate","useOnChange","isSync","current","orderedFolderIds","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","setActiveChatFolder","transitionRef","useEffect","displayedFolders","folderCountersById","useThrottledMemo","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","folderTabs","handleSwitchTab","IS_TOUCH_ENV","captureEvents","onSwipe","SwipeDirection","Left","min","Right","isNotInAllTabRef","captureEscKeyListener","handleKeyDown","metaKey","startsWith","digit","preventDefault","removeEventListener","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","folderType","noChatsText","TabList","tabs","activeTab","onSwitchTab","Transition","ref","activeKey","renderCount","props","LeftSearch","useModuleLoader","Bundles","Extra","Loading","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","useState","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isMouseInside","handleSelectSettings","Settings","handleSelectContacts","handleSelectNewChannel","NewChannelStep1","handleSelectNewGroup","NewGroupStep1","handleSelectArchived","Archived","autoCloseTimeout","NewChat","ContentType","ArchivedChats","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setContent","settingsScreen","setSettingsScreen","SettingsScreens","Main","setContactsFilter","lastResetTime","setLastResetTime","contentType","NewChannelStep2","NewChannel","NewGroupStep2","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","EditProfile","Folders","General","Notifications","Privacy","Language","GeneralChatBackground","GeneralChatBackgroundColor","PrivacyPhoneNumber","PrivacyLastSeen","PrivacyProfilePhoto","PrivacyForwarding","PrivacyGroupChats","PrivacyActiveSessions","PrivacyBlockedUsers","TwoFaDisabled","TwoFaEnabled","TwoFaCongratulations","PrivacyPhoneNumberAllowedContacts","PrivacyPhoneNumberDeniedContacts","PrivacyLastSeenAllowedContacts","PrivacyLastSeenDeniedContacts","PrivacyProfilePhotoAllowedContacts","PrivacyProfilePhotoDeniedContacts","PrivacyForwardingAllowedContacts","PrivacyForwardingDeniedContacts","PrivacyGroupChatsAllowedContacts","PrivacyGroupChatsDeniedContacts","TwoFaNewPassword","TwoFaNewPasswordConfirm","TwoFaNewPasswordHint","TwoFaNewPasswordEmail","TwoFaNewPasswordEmailCode","TwoFaChangePasswordCurrent","TwoFaTurnOff","TwoFaRecoveryEmailCurrentPassword","TwoFaChangePasswordNew","TwoFaChangePasswordConfirm","TwoFaChangePasswordHint","TwoFaRecoveryEmail","TwoFaRecoveryEmailCode","FoldersCreateFolder","FoldersEditFolder","handleSearchQuery","currentScreen","onScreenSelect","isChannel","setSize","windowSize","handleResize","calculateMiddleFooterTransforms","windowWidth","canPost","sidePadding","MOBILE_SCREEN_MAX_WIDTH","messageListWidth","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","leftColumnWidth","rightColumnWidth","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","HeaderMenuContainer","isChatChannel","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canMute","canSelect","selectIsInSelectMode","canLeave","joinChannel","openLocalTextSearch","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleSearchClick","querySelector","focus","searchInput","fluid","anchor","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","width","height","radius","count","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","style","transform","svg","div","defs","innerHTML","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","useFlag","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","thumbDataUri","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","sender","selectSender","noUi","senderName","getSenderTitle","mediaData","mediaLoader","playPause","isPlaying","useAudioPlayer","getMessageKey","getMediaDuration","handleClick","handleClose","audio","getMessageAudio","performer","renderAudio","subtitle","renderVoice","audioMessage","originChat","messagesCount","pinnedIds","isSelectModeActive","originChatId","isChatWithBot","selectIsChatWithBot","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","openChatWithInfo","pinMessage","toggleLeftColumn","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","chatTitleLength","getChatTitle","topMessageTitle","useEnsureMessage","useWindowSize","isLeftColumnHideable","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","cycleRestrict","handleAllPinnedClick","handleBackClick","messageInput","EDITABLE_INPUT_ID","currentChat","selectIsChatMuted","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","shouldUseStackedToolsClass","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","useCurrentOrPrev","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessageTitle","canRevealTools","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","asClose","unreadCountInfo","formatIntegerCompact","componentEl","add","remove","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDatetime","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","useStickyDates","isScrolled","markIsScrolled","runDebounced","shouldRunFirst","shouldRunLast","updateStickyDates","container","hasTools","contains","fastRaf","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","scrollTop","el","offsetTop","offsetHeight","top","findStuckDate","areToolsFrozen","MessageScroll","focusingId","loadMoreForwards","loadMoreBackwards","isViewportNewest","onFabToggle","onNotchToggle","children","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","toggleScrollTools","scrollHeight","scrollBottom","isAtBottom","observe","observeIntersection","freeze","freezeForLoadMore","unfreeze","unfreezeForLoadMore","useIntersectionObserver","rootRef","margin","MESSAGE_LIST_SENSITIVE_AREA","entries","triggerEntry","isIntersecting","target","resetScroll","useOnIntersect","observeIntersectionForFab","freezeForFab","unfreezeForFab","observeIntersectionForNotch","teactFastList","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","calculateMediaDimensions","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","AlbumRectPart","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","album","ratios","proportions","ratio","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","REM","getMaxWidth","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","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","createElement","font","whiteSpace","position","left","opacity","appendChild","offsetWidth","useFocusMessage","elementRef","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainer","targetUserId","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","isEmbedded","appearanceOrder","isLastInList","noAppearanceAnimation","markShown","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","data-message-id","onMouseDown","onContextMenu","EmbeddedMessage","customText","useIsIntersecting","pictogramId","isRoundVideo","getMessageRoundVideo","senderTitle","outgoingStatus","signature","views","isEdited","formatTime","MessageOutgoingStatus","Sticker","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","shouldRenderFullMedia","useTransitionForMedia","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","inSelectMode","isSelected","img","Image","onload","canvas","ctx","getContext","drawImage","getImageData","getAppendixColorFromImage","Photo","shouldAutoLoad","isInSelectMode","uploadProgress","nonInteractive","shouldAffectAppendix","onCancelUpload","localBlobUrl","isDownloadAllowed","setIsDownloadAllowed","shouldDownload","downloadProgress","useMediaWithDownloadProgress","thumbRef","isUploading","isTransferring","transferProgress","getMediaTransferState","wasDownloadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderThumb","isAllowed","contentEl","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useHeavyAnimationCheckForVideo","playerRef","shouldPlayRef","safePlay","useHeavyAnimationCheck","isPlayAllowed","wasPlaying","isFrozen","freezePlaying","paused","unfreezePlaying","unfreezePlayingOnRaf","hasFocus","useBackgroundMode","Video","shouldAutoPlay","videoRef","canPlayInline","canMessagePlayVideoInline","setIsPlayAllowed","isInline","isBuffered","bufferingHandlers","useBuffering","playProgress","setPlayProgress","handleTimeUpdate","currentTime","usePauseOnInactive","useVideoCleanup","videoClassName","shouldRenderInlineVideo","shouldRenderHqPreview","shouldRenderPlayButton","shouldRenderDownloadButton","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","duration","contact","openUserInfo","Avatar","formatPhoneNumberWithCode","selected","loadingOptions","setValues","event","newValues","Checkbox","subLabel","getPercentage","toFixed","PollOption","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","floor","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","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","hasDocument","truncatedDescription","trimText","data-initial","SafeLink","getMessageInvoice","photoUrl","withSelectControl","WrapedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","shiftKey","newProps","PhotoWithSelect","VideoWithSelect","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","currentOnRelease","RoundVideo","playingProgressRef","shouldSpinnerRender","isActivated","setIsActivated","setProgress","playerEl","playingProgressEl","stopPlaying","requestAnimationFrame","capturePlaying","onRelease","ROUND_VIDEO_DIMENSIONS","onEnded","InlineButtons","recentReplierIds","recentRepliers","hasUnread","data-cnt","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","forceSenderName","isAnonymousOwnMessage","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","selectOutgoingStatus","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","shouldAutoLoadMedia","selectShouldAutoLoadMedia","shouldAutoPlayMedia","selectShouldAutoPlayMedia","shouldLoopStickers","selectShouldLoopStickers","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","clickInlineButton","bottomMarkerRef","appendixRef","hasReply","isReplyMessage","hasThread","asForwarded","isLinkedChannelPost","isInDocumentGroup","voice","getMessageCustomShape","textParts","renderMessageText","containerClassName","contentClassName","hasComments","classNames","isMediaWithNoText","isViaBot","isRound","buildContentClassName","avatarPeer","senderPeer","adminTitle","withCommentButton","withAppendix","handleGroupDocumentMessagesSelect","handleContainerDoubleClick","handleContentDoubleClick","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","MediaViewerOrigin","ScheduledInline","Inline","handleAudioPlay","handleAlbumMediaClick","albumMessageId","ScheduledAlbum","Album","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","fromMessageId","calculatedWidth","noMediaCorners","extraPadding","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","onDoubleClick","data-last-message-id","data-has-unread-mention","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","Audio","isSelectable","onPlay","onReadMedia","Document","renderContent","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","withLastMessageWhenPreloading","botDescription","chatBot","selectChatBot","isChatLoaded","isChannelChat","threadFirstMessageId","selectFirstMessageId","hasLinkedChat","markMessageListRead","setScrollOffset","scrollOffsetRef","selectScrollOffset","anchorIdRef","anchorTopRef","listItemElementsRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","hasFocusing","setHasFocusing","onTickEnd","freezeForMedia","unfreezeForMedia","throttleMs","observeIntersectionForReading","freezeForReading","unfreezeForReading","mentionIds","entry","dataset","messageGroups","listedMessages","orderBy","loadMoreAround","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","windowHeight","normalHeight","String","clientHeight","preservedItemElements","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","shouldForceScroll","lastItemElement","lastItemHeight","newScrollTop","hasFirstMessageChanged","hasLastMessageChanged","isAlreadyFocusing","isResized","unreadDivider","isAnimatingScroll","dispatchHeavyAnimationEvent","ANIMATION_END_DELAY","withUsers","onScroll","currentAnchorIdRef","isSchedule","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","originalId","getMessageOriginalId","SCHEDULED_WHEN_ONLINE","formatHumanDate","renderMessages","focusLastMessage","messageElements","lastMessageElement","buildAttachment","filename","blob","isQuick","quick","preloadImage","newBlob","toBlob","squeezeImage","revokeObjectURL","videoWidth","videoHeight","preloadVideo","createPosterForVideo","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","startedAt","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","volume","subscribeToAnalyzer","stop","reject","onstop","Blob","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","formattedText","currentThreadId","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenu","SymbolMenu","MentionTooltip","CustomSend","StickerTooltipAsync","StickerTooltip","BotKeyboardMenu","forwardMessageIds","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","AttachmentModal","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","parseMessageInput","linkEntity","ApiMessageEntityTypes","TextUrl","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModal","PaymentModal","MainButtonState","ReceiptModal","chatUser","selectChatUser","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","editingMessage","canScheduleUntilOnline","wasOnline","withScheduledButton","shouldSchedule","botKeyboardMessageId","canSuggestMembers","isChatGroup","stickersForEmoji","groupChatMembers","isReceiptModalOpen","shouldSuggestStickers","dropAreaState","onDropHide","editMessage","saveDraft","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","closePaymentModal","clearReceipt","addRecentEmoji","loadEmojiKeywords","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","htmlRef","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","IS_IOS","voiceRecording","tickVolume","boxShadow","useVoiceRecording","mainButtonState","Edit","IS_VOICE_RECORDING_SUPPORTED","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","mentionFilter","closeMentionTooltip","insertMention","mentionFilteredMembers","useMentionTooltip","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","canSendStickers","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","selection","getSelection","newHtml","replace","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","execCommand","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","prevChatId","handleEditComplete","editedMessage","hasMessageMedia","useEditing","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","tagName","EDITABLE_INPUT_MODAL_ID","items","media","getAsFile","pastedText","getData","substring","useClipboardPaste","handleFileSelect","files","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleStickerSelect","handleGifSelect","gif","handlePollSend","handleSilentSend","handleMessageSchedule","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","Portal","DropAreaState","None","withQuick","QuickFile","onHide","onFileSelect","caption","onCaptionUpdate","onSend","onFileAppend","onClear","onInsertUserName","filteredChatMembers","canAttachEmbedLinks","faded","MessageInput","innerWidth","shouldSetFocus","shouldSupressFocus","shouldSupressTextFormatter","onUpdate","onSupressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","selectedAt","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","CLOSE_ANIMATION_DURATION","canBeQuicklyUploaded","kind","CONTENT_TYPES_FOR_QUICK_UPLOAD","isBlurred","isBackgroundBlurred","background","customBackground","backgroundColor","patternColor","themes","isMobileSearchActive","getCanPostInChat","isBotNotStarted","isPinnedMessageList","messageSendingRestrictionReason","getMessageSendingRestrictionReason","hasPinnedOrAudioMessage","loadUser","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanPost","renderingHasTools","renderingIsFabShown","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","customBackgroundValue","settingValue","setValue","cacheApi","CUSTOM_BG_CACHE_NAME","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","footerClassName","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","ANIMATION_LEVEL_MAX","shouldCleanup","onUnpin","runDebouncedForSearch","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canManage","isCreator","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","profileState","managementScreen","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","backButtonRef","handleMessageSearchQueryChange","handleJumpToDate","valueOf","handleStickerSearchQueryChange","handleGifSearchQueryChange","shouldSkipTransition","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","ManagementScreens","Initial","ManageInitial","ChatPrivacyType","ManageChatPrivacyType","Discussion","ManageDiscussion","ChannelSubscribers","ManageChannelSubscribers","GroupPermissions","ManageGroupPermissions","ChatAdministrators","ManageChatAdministrators","GroupRemovedUsers","ManageGroupRemovedUsers","GroupUserPermissionsCreate","ManageGroupUserPermissionsCreate","GroupUserPermissions","ManageGroupUserPermissions","GroupRecentActions","ManageGroupRecentActions","ChatAdminRights","ManageGroupAdminRights","GroupMembers","ManageGroupMembers","renderingContentKey","renderHeaderContent","isBackButton","buttonClassName","isPastMode","submitButtonLabel","useProfileViewportIds","loadMoreMembers","searchMessages","tabType","mediaSearchType","resultType","sortUserIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","currentResultType","handleLoadMore","getMore","useInfiniteScroll","MEMBERS_SLICE","isOnTop","useInfiniteScrollForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","useInfiniteScrollForSharedMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","noProfileInfo","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","isFirstPhoto","isSavedMessages","isDeleted","isDeletedUser","getMediaHash","forceAvatar","getChatAvatarHash","imageHash","ApiMediaFormat","BlobUrl","avatarThumbnailData","useBlurSync","dataUri","imageSrc","prevImageSrc","decoding","userFullName","getUserFullName","getFirstLetters","fullClassName","forceShowSelf","loadFullUser","fullName","slideAnimation","currentPhotoIndex","setCurrentPhotoIndex","isFirst","isLast","profile","currentIndex","usePhotosPreload","handleProfilePhotoClick","ProfileAvatar","selectPreviousMedia","selectNextMedia","excludedClosestSelector","renderPhoto","isVerifiedIconShown","isVerified","renderPhotoTabs","aria-label","VerifiedIcon","isUserOnline","getUserStatus","canInviteUsers","isUserRightBanned","getHasAdminRight","currentIsMuted","chatUsername","handleNotificationChange","copy","entity","formattedNumber","getChatLink","printedUsername","getChatDescription","ListItem","multiline","narrow","isStatic","TABS","buildInfiniteScrollItemSelector","isGroup","hasMembersTab","areMembersHidden","canViewMembers","resolvedUserId","onProfileStateChange","setLocalMediaSearchType","searchMediaMessagesLocal","loadProfilePhotos","setActiveTab","useEffectWithPrevDeps","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","renderingFor","teactOrderKey","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","renderProfileInfo","shouldRestoreHeight","onStart","onStop","big","RightSearch","Management","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closeLocalTextSearch","closePollResults","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","ChatInfo","UserInfo","isOverlaying","close","GroupType","handleSelectChatMember","memberId","isPromoted","onChatMemberSelect","prevContentKey","MediaViewer","Errors","ForwardPicker","SafeLinkModal","rightColumnAnimationTimeout","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasErrors","middleColumnTransitionClassNames","rightColumnTransitionClassNames","stopEvent","initialUnread","clearInterval","setInterval","INACTIVE_MARKER","newUnread","PAGE_TITLE","onDrop","onDragOver","initApi"],"mappings":"uLAOAA,OAAOC,iBAAiB,WAAaC,IACnC,IAAKA,EAAEC,MACL,OAGF,MAAQC,OAAQC,EAAV,SAAcC,EAAUC,gBAAiBC,GAASN,EAAEC,MAE1DM,cAAcC,SAAS,CACrBL,KAAIC,WAAUE,OAAMG,aAAa,MAIrCC,YAAW,WAAY,CAACC,EAAQC,EAASC,KACvC,MAAM,GACJV,EADI,SACAC,GAAW,EADX,KACeE,EAAO,SADtB,YACgCG,GAClCI,EAEEC,EAAqBC,YAAyBJ,GA4BpD,OA1BKG,GAEDA,EAAmBZ,SAAWC,GAC3BW,EAAmBV,WAAaA,GAChCU,EAAmBR,OAASA,IAEjCK,EAASK,YAAsBL,GAE/BA,EAAS,IACJA,EACHM,SAAU,IACLN,EAAOM,SACVC,0BAAsBC,MAEpBhB,IAAOQ,EAAOS,gBAAgBC,UAAY,CAC5CD,gBAAiB,KAIrBE,YAAUX,GAELF,GACHX,OAAOyB,QAAQC,UAAU,CAAEtB,OAAQC,EAAIC,WAAUC,gBAAiBC,GAAQ,KAIvEmB,YAAyBd,EAAQR,EAAIC,EAAUE,KAGxDI,YAAW,mBAAoB,CAACC,EAAQC,EAASC,KAC/CS,YAAU,IACLX,EACHe,iBAAiB,IAGnBd,EAAQJ,SAASK,KAGnBH,YAAW,oBAAsBC,IACxB,IACFA,EACHgB,kBAAcR,K,0BCrClB,IAAIS,EAEJlB,YAAW,kBAAmB,CAACC,EAAQC,EAASC,KAC9C,MAAM,OAAEX,EAAF,SAAUE,EAAV,aAAoByB,GAAiBhB,EAE3C,OAAOiB,YAAmBnB,EAAQT,EAAQE,EAAU,eAAgByB,KAGtEnB,YAAW,kBAAmB,CAACC,EAAQC,EAASC,KAC9C,MAAM,UAAEkB,GAAclB,EAChBC,EAAqBC,YAAyBJ,GACpD,IA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nB,MAAMk2E,EAAY39D,YAA0BnqB,eAAe0nF,EACvDI,EAAY,IACdrkE,SAAS1Y,MAAS,GAAE+8E,iBAAyBA,EAAY,EAAI,IAAM,KACnEf,IAAW,SAGbtjE,SAAS1Y,MAAQg9E,KACjBhB,IAAW,GAGbn1E,MA7FwB,MA+FzB,KACD+1E,cAAcd,IACdA,QAAuBnqF,EAElB+mB,SAAS1Y,MAAMnK,SAASinF,OAC3BpkE,SAAS1Y,MAAQg9E,MAGnBhB,IAAW,KASX,yBAAKrrF,GAAG,OAAOy1B,UAAWA,EAAW62D,OAAQP,EAAWQ,WAAYR,GAClE,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,MACA,kBAAC,GAAD,CAAap0D,OAAQ4zD,IACrB,kBAAC,GAAD,CAAe5zD,OAAQ8zD,IACvB,kBAAC,GAAD,CAAe9zD,OAAQg0D,IACvB,kBAAC,GAAD,CAAQh0D,OAAQi0D,IACfv8C,GAAgB,kBAAC,GAAD,CAAa3a,IAAK2a,EAAarvC,GAAI6J,QAASwlC,EAAclB,MAAI,IAC/E,kBAAC,GAAD,CAAe7jC,IAAKC,QCtKtByX,KAEFC,QAAQC,IAAI,+BAGT5d,cAAYq2B,iBACfv6B,cAAcosF,W","file":"4.92917cccdb4999ea7d20.js","sourcesContent":["import { addReducer, getDispatch, setGlobal } from '../../../lib/teact/teactn';\nimport {\n exitMessageSelectMode,\n updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\n\nwindow.addEventListener('popstate', (e) => {\n if (!e.state) {\n return;\n }\n\n const { chatId: id, threadId, messageListType: type } = e.state;\n\n getDispatch().openChat({\n id, threadId, type, noPushState: true,\n });\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', noPushState,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = exitMessageSelectMode(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n\n if (!noPushState) {\n window.history.pushState({ chatId: id, threadId, messageListType: type }, '');\n }\n }\n\n return updateCurrentMessageList(global, id, threadId, type);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\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, selectIsViewportNewest, selectReplyingToId,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\n\nconst FOCUS_DURATION = 2000;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('replyToNextMessage', (global, actions, payload) => {\n const { targetIndexDelta } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return;\n }\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const isLatest = selectIsViewportNewest(global, chatId, threadId);\n\n let messageId: number | undefined;\n\n if (!isLatest || !replyingToId) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n messageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n messageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n } else {\n const chatMessageKeys = Object.keys(chatMessages);\n const indexOfCurrent = chatMessageKeys.indexOf(replyingToId.toString());\n const newIndex = indexOfCurrent + targetIndexDelta;\n messageId = newIndex <= chatMessageKeys.length + 1 && newIndex >= 0\n ? Number(chatMessageKeys[newIndex])\n : undefined;\n }\n actions.setReplyingToId({ messageId });\n actions.focusMessage({\n chatId, threadId, messageId,\n });\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {},\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat && chat.lastMessage ? chat.lastMessage.id : undefined;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo ? threadInfo.lastMessageId : undefined;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids && 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 }, FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight);\n global = updateFocusDirection(global, undefined);\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n actions.exitMessageSelectMode();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n return toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n});\n\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\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';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n});\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global, actions, payload) => {\n if (!IS_MOBILE_SCREEN) {\n return undefined;\n }\n\n const { id } = payload!;\n\n return {\n ...global,\n isLeftColumnShown: id === undefined,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: 0,\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global) => {\n const newNotifications = [...global.notifications];\n\n newNotifications.pop();\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showError', (global, actions, payload) => {\n const { error } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if (!getReadableErrorText(error)) {\n return global;\n }\n\n const newErrors = [...global.errors];\n const existingErrorIndex = newErrors.findIndex((err) => err.message === error.message);\n if (existingErrorIndex !== -1) {\n newErrors.splice(existingErrorIndex, 1);\n }\n\n newErrors.push(error);\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('dismissError', (global) => {\n const newErrors = [...global.errors];\n\n newErrors.pop();\n\n return {\n ...global,\n errors: newErrors,\n };\n});\n\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\nimport {\n clearPayment, closeInvoice,\n} from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiUser, ApiChatFolder, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { ChatCreationProgress, ManagementProgress } from '../../../types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n ARCHIVED_FOLDER_ID,\n TOP_CHAT_MESSAGES_PRELOAD_LIMIT,\n CHAT_LIST_LOAD_SLICE,\n RE_TME_INVITE_LINK,\n RE_TME_LINK,\n TIPS_USERNAME,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n addChats,\n addUsers,\n replaceThreadParam,\n updateChatListIds,\n updateChats,\n updateChat,\n updateChatListSecondaryInfo,\n updateManagementProgress,\n} from '../../reducers';\nimport {\n selectChat,\n selectCurrentChat,\n selectUser,\n selectChatListType,\n selectIsChatPinned,\n selectChatFolder,\n selectSupportChat,\n selectChatByUsername,\n selectThreadTopMessageId,\n selectCurrentMessageList,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce, pause, throttle } from '../../../util/schedulers';\nimport {\n isChatSummaryOnly, isChatArchived, prepareChatList, isChatBasicGroup,\n} from '../../helpers';\n\nconst TOP_CHATS_PRELOAD_PAUSE = 100;\n// We expect this ID does not exist\nconst TMP_CHAT_ID = -1;\n\nconst runThrottledForLoadChats = throttle((cb) => cb(), 1000, true);\nconst runThrottledForLoadTopChats = throttle((cb) => cb(), 3000, true);\nconst runDebouncedForLoadFullChat = debounce((cb) => cb(), 500, false, true);\n\naddReducer('preloadTopChatMessages', (global, actions) => {\n (async () => {\n const preloadedChatIds: number[] = [];\n\n for (let i = 0; i < TOP_CHAT_MESSAGES_PRELOAD_LIMIT; i++) {\n await pause(TOP_CHATS_PRELOAD_PAUSE);\n\n const {\n byId,\n listIds: { active: listIds },\n orderedPinnedIds: { active: orderedPinnedIds },\n } = getGlobal().chats;\n if (!listIds) {\n return;\n }\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const { pinnedChats, otherChats } = prepareChatList(byId, listIds, orderedPinnedIds);\n const topChats = [...pinnedChats, ...otherChats];\n const chatToPreload = topChats.find(({ id }) => id !== currentChatId && !preloadedChatIds.includes(id));\n if (!chatToPreload) {\n return;\n }\n\n preloadedChatIds.push(chatToPreload.id);\n\n actions.loadViewportMessages({ chatId: chatToPreload.id, threadId: MAIN_THREAD_ID });\n }\n })();\n});\n\naddReducer('openChat', (global, actions, payload) => {\n const { id, threadId } = payload!;\n const { currentUserId } = global;\n const chat = selectChat(global, id);\n\n if (chat && chat.hasUnreadMark) {\n actions.toggleChatUnread({ id });\n }\n\n if (!chat) {\n if (id === currentUserId) {\n void callApi('fetchChat', { type: 'self' });\n } else {\n const user = selectUser(global, id);\n if (user) {\n void callApi('fetchChat', { type: 'user', user });\n }\n }\n } else if (isChatSummaryOnly(chat) && !chat.isMin) {\n actions.requestChatUpdate({ chatId: id });\n }\n\n if (threadId !== MAIN_THREAD_ID) {\n const topMessageId = selectThreadTopMessageId(global, id, threadId);\n if (!topMessageId) {\n actions.requestThreadInfoUpdate({ chatId: id, threadId });\n }\n }\n});\n\naddReducer('openSupportChat', (global, actions) => {\n const chat = selectSupportChat(global);\n\n actions.openChat({ id: chat ? chat.id : TMP_CHAT_ID });\n\n if (chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchChat', { type: 'support' });\n if (result) {\n actions.openChat({ id: result.chatId });\n }\n })();\n});\n\naddReducer('openTipsChat', (global, actions) => {\n actions.openChatByUsername({ username: TIPS_USERNAME });\n});\n\naddReducer('loadMoreChats', (global, actions, payload) => {\n const { listType = 'active' } = payload!;\n const listIds = global.chats.listIds[listType as ('active' | 'archived')];\n const isFullyLoaded = global.chats.isFullyLoaded[listType as ('active' | 'archived')];\n\n if (isFullyLoaded) {\n return;\n }\n\n const oldestChat = listIds\n ? listIds\n .map((id) => global.chats.byId[id])\n .filter((chat) => Boolean(chat && chat.lastMessage) && !selectIsChatPinned(global, chat.id))\n .sort((chat1, chat2) => (chat1.lastMessage!.date - chat2.lastMessage!.date))[0]\n : undefined;\n\n if (oldestChat) {\n runThrottledForLoadChats(() => loadChats(listType, oldestChat.id, oldestChat.lastMessage!.date));\n } else {\n runThrottledForLoadChats(() => loadChats(listType));\n }\n});\n\naddReducer('loadFullChat', (global, actions, payload) => {\n const { chatId, force } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n if (force) {\n loadFullChat(chat);\n } else {\n runDebouncedForLoadFullChat(() => loadFullChat(chat));\n }\n});\n\naddReducer('loadTopChats', () => {\n runThrottledForLoadTopChats(() => loadChats('active'));\n});\n\naddReducer('requestChatUpdate', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('requestChatUpdate', chat);\n});\n\naddReducer('updateChatMutedState', (global, actions, payload) => {\n const { chatId, isMuted } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void callApi('updateChatMutedState', { chat, isMuted });\n});\n\naddReducer('createChannel', (global, actions, payload) => {\n const {\n title, about, photo, memberIds,\n } = payload!;\n\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createChannel(title, members, about, photo);\n});\n\naddReducer('joinChannel', (global, actions, payload) => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n void callApi('joinChannel', { channelId, accessHash });\n }\n});\n\naddReducer('leaveChannel', (global, actions, payload) => {\n (async () => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n await callApi('leaveChannel', { channelId, accessHash });\n }\n\n actions.openChat({ id: undefined });\n })();\n});\n\naddReducer('deleteChannel', (global, actions, payload) => {\n (async () => {\n const { chatId } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const { id: channelId, accessHash } = chat;\n\n if (channelId && accessHash) {\n await callApi('deleteChannel', { channelId, accessHash });\n }\n\n actions.openChat({ id: undefined });\n })();\n});\n\naddReducer('createGroupChat', (global, actions, payload) => {\n const { title, memberIds, photo } = payload!;\n const members = (memberIds as number[])\n .map((id: number) => selectUser(global, id))\n .filter(Boolean as any);\n\n void createGroupChat(title, members, photo);\n});\n\naddReducer('toggleChatPinned', (global, actions, payload) => {\n const { id, folderId } = payload!;\n const chat = selectChat(global, id);\n if (!chat) {\n return;\n }\n\n if (folderId) {\n const folder = selectChatFolder(global, folderId);\n if (folder) {\n const shouldBePinned = !selectIsChatPinned(global, id, folderId);\n\n const { pinnedChatIds, includedChatIds } = folder;\n const newPinnedIds = shouldBePinned\n ? [id, ...(pinnedChatIds || [])]\n : (pinnedChatIds || []).filter((pinnedId) => pinnedId !== id);\n\n // With both Pin and Unpin we need to re-add a user to the included group\n const newIncludedChatIds = [id, ...includedChatIds];\n\n void callApi('editChatFolder', {\n id: folderId,\n folderUpdate: {\n ...folder,\n pinnedChatIds: newPinnedIds,\n includedChatIds: newIncludedChatIds,\n },\n });\n }\n } else {\n const listType = selectChatListType(global, id);\n const isPinned = selectIsChatPinned(global, id, listType === 'archived' ? ARCHIVED_FOLDER_ID : undefined);\n void callApi('toggleChatPinned', { chat, shouldBePinned: !isPinned });\n }\n});\n\naddReducer('toggleChatArchived', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n void callApi('toggleChatArchived', {\n chat,\n folderId: isChatArchived(chat) ? 0 : ARCHIVED_FOLDER_ID,\n });\n }\n});\n\naddReducer('loadChatFolders', () => {\n void loadChatFolders();\n});\n\naddReducer('loadRecommendedChatFolders', () => {\n void loadRecommendedChatFolders();\n});\n\naddReducer('editChatFolder', (global, actions, payload) => {\n const { id, folderUpdate } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void callApi('editChatFolder', {\n id,\n folderUpdate: {\n id,\n emoticon: folder.emoticon,\n pinnedChatIds: folder.pinnedChatIds,\n ...folderUpdate,\n },\n });\n }\n});\n\naddReducer('addChatFolder', (global, actions, payload) => {\n const { folder } = payload!;\n const { orderedIds } = global.chatFolders;\n const maxId = orderedIds && orderedIds.length ? Math.max.apply(Math.max, orderedIds) : ARCHIVED_FOLDER_ID;\n\n void createChatFolder(folder, maxId);\n});\n\naddReducer('deleteChatFolder', (global, actions, payload) => {\n const { id } = payload!;\n const folder = selectChatFolder(global, id);\n\n if (folder) {\n void deleteChatFolder(id);\n }\n});\n\naddReducer('toggleChatUnread', (global, actions, payload) => {\n const { id } = payload!;\n const chat = selectChat(global, id);\n if (chat) {\n if (chat.unreadCount) {\n void callApi('markMessageListRead', { chat, threadId: MAIN_THREAD_ID });\n } else {\n void callApi('toggleDialogUnread', {\n chat,\n hasUnreadMark: !chat.hasUnreadMark,\n });\n }\n }\n});\n\naddReducer('openTelegramLink', (global, actions, payload) => {\n const { url } = payload!;\n let match = RE_TME_INVITE_LINK.exec(url);\n\n if (match) {\n const hash = match[1];\n\n (async () => {\n const chat = await callApi('openChatByInvite', hash);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n })();\n } else {\n match = RE_TME_LINK.exec(url)!;\n\n const username = match[1];\n const channelPostId = match[2] ? Number(match[2]) : undefined;\n\n void openChatByUsername(actions, username, channelPostId);\n }\n});\n\naddReducer('openChatByUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n void openChatByUsername(actions, username);\n});\n\naddReducer('togglePreHistoryHidden', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n let chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n void callApi('togglePreHistoryHidden', { chat, isEnabled });\n })();\n});\n\naddReducer('updateChatDefaultBannedRights', (global, actions, payload) => {\n const { chatId, bannedRights } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('updateChatDefaultBannedRights', { chat, bannedRights });\n});\n\naddReducer('updateChatMemberBannedRights', (global, actions, payload) => {\n const { chatId, userId, bannedRights } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatMemberBannedRights', { chat, user, bannedRights });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { members, kickedMembers } = chatAfterUpdate.fullInfo;\n\n const isBanned = !!bannedRights.viewMessages;\n const isUnblocked = !Object.keys(bannedRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(members && isBanned && {\n members: members.filter((m) => m.userId !== userId),\n }),\n ...(members && !isBanned && {\n members: members.map((m) => (\n m.userId === userId\n ? { ...m, bannedRights }\n : m\n )),\n }),\n ...(isUnblocked && kickedMembers && {\n kickedMembers: kickedMembers.filter((m) => m.userId !== userId),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChatAdmin', (global, actions, payload) => {\n const {\n chatId, userId, adminRights, customTitle,\n } = payload!;\n let chat = selectChat(global, chatId);\n const user = selectUser(global, userId);\n\n if (!chat || !user) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n await callApi('updateChatAdmin', {\n chat, user, adminRights, customTitle,\n });\n\n const newGlobal = getGlobal();\n const chatAfterUpdate = selectChat(newGlobal, chatId);\n\n if (!chatAfterUpdate || !chatAfterUpdate.fullInfo) {\n return;\n }\n\n const { adminMembers } = chatAfterUpdate.fullInfo;\n\n const isDismissed = !Object.keys(adminRights).length;\n\n setGlobal(updateChat(newGlobal, chatId, {\n fullInfo: {\n ...chatAfterUpdate.fullInfo,\n ...(adminMembers && isDismissed && {\n adminMembers: adminMembers.filter((m) => m.userId !== userId),\n }),\n ...(adminMembers && !isDismissed && {\n adminMembers: adminMembers.map((m) => (\n m.userId === userId\n ? { ...m, adminRights, customTitle }\n : m\n )),\n }),\n },\n }));\n })();\n});\n\naddReducer('updateChat', (global, actions, payload) => {\n const {\n chatId, title, about, photo,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n await Promise.all([\n chat.title !== title\n ? callApi('updateChatTitle', chat, title)\n : undefined,\n chat.fullInfo && chat.fullInfo.about !== about\n ? callApi('updateChatAbout', chat, about)\n : undefined,\n photo\n ? callApi('editChatPhoto', { chatId, accessHash: chat.accessHash, photo })\n : undefined,\n ]);\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n })();\n});\n\naddReducer('toggleSignatures', (global, actions, payload) => {\n const { chatId, isEnabled } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('toggleSignatures', { chat, isEnabled });\n});\n\naddReducer('loadGroupsForDiscussion', () => {\n (async () => {\n const groups = await callApi('fetchGroupsForDiscussion');\n if (!groups) {\n return;\n }\n\n const addedById = groups.reduce((result, group) => {\n if (group) {\n result[group.id] = group;\n }\n\n return result;\n }, {} as Record);\n\n const global = addChats(getGlobal(), addedById);\n setGlobal({\n ...global,\n chats: {\n ...global.chats,\n forDiscussionIds: Object.keys(addedById).map(Number),\n },\n });\n })();\n});\n\naddReducer('linkDiscussionGroup', (global, actions, payload) => {\n const { channelId, chatId } = payload!;\n\n const channel = selectChat(global, channelId);\n let chat = selectChat(global, chatId);\n if (!channel || !chat) {\n return;\n }\n\n (async () => {\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n let { fullInfo } = chat;\n if (!fullInfo) {\n const fullChat = await callApi('fetchFullChat', chat);\n if (!fullChat) {\n return;\n }\n\n fullInfo = fullChat.fullInfo;\n }\n\n if (fullInfo.isPreHistoryHidden) {\n await callApi('togglePreHistoryHidden', { chat, isEnabled: false });\n }\n\n void callApi('setDiscussionGroup', { channel, chat });\n })();\n});\n\naddReducer('unlinkDiscussionGroup', (global, actions, payload) => {\n const { channelId } = payload!;\n\n const channel = selectChat(global, channelId);\n if (!channel) {\n return;\n }\n\n let chat: ApiChat | undefined;\n if (channel.fullInfo && channel.fullInfo.linkedChatId) {\n chat = selectChat(global, channel.fullInfo.linkedChatId);\n }\n\n (async () => {\n await callApi('setDiscussionGroup', { channel });\n if (chat) {\n loadFullChat(chat);\n }\n })();\n});\n\n\naddReducer('setActiveChatFolder', (global, actions, payload) => {\n return {\n ...global,\n chatFolders: {\n ...global.chatFolders,\n activeChatFolder: payload,\n },\n };\n});\n\naddReducer('loadMoreMembers', (global) => {\n (async () => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n if (!chat || isChatBasicGroup(chat)) {\n return;\n }\n\n const offset = (chat.fullInfo && chat.fullInfo.members && chat.fullInfo.members.length) || undefined;\n const result = await callApi('fetchMembers', chat.id, chat.accessHash!, 'recent', offset);\n if (!result) {\n return;\n }\n\n const { members, users } = result;\n if (!members || !members.length) {\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateChat(global, chat.id, {\n fullInfo: {\n ...chat.fullInfo,\n members: [\n ...((chat.fullInfo || {}).members || []),\n ...(members || []),\n ],\n },\n });\n setGlobal(global);\n })();\n});\n\nasync function loadChats(listType: 'active' | 'archived', offsetId?: number, offsetDate?: number) {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n offsetDate,\n archived: listType === 'archived',\n withPinned: getGlobal().chats.orderedPinnedIds[listType] === undefined,\n });\n\n if (!result) {\n return;\n }\n\n const { chatIds } = result;\n\n if (chatIds.length > 0 && chatIds[0] === offsetId) {\n chatIds.shift();\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChatListIds(global, listType, chatIds);\n global = updateChatListSecondaryInfo(global, listType, result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n\n if (chatIds.length === 0 && !global.chats.isFullyLoaded[listType]) {\n global = {\n ...global,\n chats: {\n ...global.chats,\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [listType]: true,\n },\n },\n };\n }\n\n setGlobal(global);\n}\n\nasync function loadFullChat(chat: ApiChat) {\n const result = await callApi('fetchFullChat', chat);\n if (!result) {\n return;\n }\n\n const { users, fullInfo } = result;\n\n let global = getGlobal();\n if (users) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n global = updateChat(global, chat.id, { fullInfo });\n\n setGlobal(global);\n}\n\nasync function createChannel(title: string, users: ApiUser[], about?: string, photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChannel = await callApi('createChannel', { title, about, users });\n if (!createdChannel) {\n return;\n }\n\n const { id: channelId, accessHash } = createdChannel;\n\n let global = getGlobal();\n global = updateChat(global, channelId, createdChannel);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChannel ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: channelId });\n\n if (channelId && accessHash && photo) {\n await callApi('editChatPhoto', { chatId: channelId, accessHash, photo });\n }\n}\n\nasync function createGroupChat(title: string, users: ApiUser[], photo?: File) {\n setGlobal({\n ...getGlobal(),\n chatCreation: {\n progress: ChatCreationProgress.InProgress,\n },\n });\n\n const createdChat = await callApi('createGroupChat', { title, users });\n if (!createdChat) {\n return;\n }\n\n const { id: chatId } = createdChat;\n\n let global = getGlobal();\n global = updateChat(global, chatId, createdChat);\n global = {\n ...global,\n chatCreation: {\n ...global.chatCreation,\n progress: createdChat ? ChatCreationProgress.Complete : ChatCreationProgress.Error,\n },\n };\n setGlobal(global);\n getDispatch().openChat({ id: chatId });\n\n if (chatId && photo) {\n await callApi('editChatPhoto', { chatId, photo });\n }\n}\n\nasync function loadChatFolders() {\n const chatFolders = await callApi('fetchChatFolders');\n\n if (chatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n ...chatFolders,\n },\n });\n }\n}\n\nasync function loadRecommendedChatFolders() {\n const recommendedChatFolders = await callApi('fetchRecommendedChatFolders');\n\n if (recommendedChatFolders) {\n const global = getGlobal();\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommendedChatFolders,\n },\n });\n }\n}\n\nasync function createChatFolder(folder: ApiChatFolder, maxId: number) {\n // Clear fields from recommended folders\n const { id: recommendedId, description, ...newFolder } = folder;\n\n await callApi('editChatFolder', {\n id: maxId + 1,\n folderUpdate: {\n id: maxId + 1,\n ...newFolder,\n },\n });\n\n if (!description) {\n return;\n }\n\n const global = getGlobal();\n const { recommended } = global.chatFolders;\n\n if (recommended) {\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: recommended.filter(({ id }) => id !== recommendedId),\n },\n });\n }\n}\n\nasync function deleteChatFolder(id: number) {\n await callApi('deleteChatFolder', id);\n}\n\nasync function openChatByUsername(\n actions: GlobalActions,\n username: string,\n channelPostId?: number,\n) {\n const global = getGlobal();\n const localChat = selectChatByUsername(global, username);\n if (localChat && !localChat.isMin) {\n if (channelPostId) {\n actions.focusMessage({ chatId: localChat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: localChat.id });\n }\n return;\n }\n\n const previousChat = selectCurrentChat(global);\n // Open temporary empty chat to make the click response feel faster\n actions.openChat({ id: TMP_CHAT_ID });\n\n const chat = await callApi('getChatByUsername', username);\n if (!chat) {\n if (previousChat) {\n actions.openChat({ id: previousChat.id });\n }\n\n actions.showNotification({ message: 'User does not exist' });\n\n return;\n }\n\n setGlobal(updateChat(getGlobal(), chat.id, chat));\n\n if (channelPostId) {\n actions.focusMessage({ chatId: chat.id, messageId: channelPostId });\n } else {\n actions.openChat({ id: chat.id });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE } from '../../../config';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport { areSortedArraysIntersecting, buildCollectionByKey, split } 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} 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} from '../../selectors';\nimport { rafPromise, throttle } from '../../../util/schedulers';\nimport { copyTextToClipboard } from '../../../util/clipboard';\n\nconst uploadProgressCallbacks = new Map();\n\nconst runThrottledForMarkRead = throttle((cb) => cb(), 1000, true);\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const { chatId, messageId, replyOriginForId } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void loadMessage(chat, messageId, replyOriginForId);\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n };\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { 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),\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', draft);\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n return replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n (async () => {\n const { chatId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const maxId = chat.lastMessage && chat.lastMessage.id;\n\n await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n\n actions.openChat({ id: undefined });\n })();\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n const { maxId } = payload!;\n\n runThrottledForMarkRead(() => {\n void callApi('markMessageListRead', { chat, threadId, maxId });\n });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global) => {\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 && messages.length) {\n void forwardMessages(fromChat, toChat, messages);\n }\n});\n\naddReducer('loadScheduledHistory', (global) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { hash } = global.scheduledMessages.byChatId[chat.id] || {};\n\n void loadScheduledHistory(chat, hash);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\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 (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;\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;\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\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}) {\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) {\n await rafPromise();\n }\n\n const global = getGlobal();\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\nfunction forwardMessages(\n fromChat: ApiChat,\n toChat: ApiChat,\n messages: ApiMessage[],\n) {\n callApi('forwardMessages', {\n fromChat,\n toChat,\n messages,\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\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 const isUnique = (v: number, i: number, a: number[]) => a.indexOf(v) === i;\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]: [\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ].filter(isUnique),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadMessageLink', (global, actions, payload) => {\n const { messageId, chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectChatMessage(global, chatId, messageId);\n\n if (!chat || !message) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchMessageLink', { chat, message });\n\n if (result) {\n copyTextToClipboard(result.link);\n }\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat, historyHash?: number) {\n const result = await callApi('fetchScheduledHistory', { chat, hash: historyHash });\n if (!result) {\n return;\n }\n\n const { hash, 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, hash);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { LangCode } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectEmojiKeywords, selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 500;\nconst ADDED_SETS_THROTTLE_CHUNK = 50;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\naddReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n let currentEmojiKeywords = selectEmojiKeywords(global, language);\n\n if (currentEmojiKeywords && currentEmojiKeywords.isLoading) {\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\n (async () => {\n const emojiKeywords = await callApi('fetchEmojiKeywords', {\n language,\n fromVersion: currentEmojiKeywords ? currentEmojiKeywords.version : 0,\n });\n\n global = getGlobal();\n currentEmojiKeywords = selectEmojiKeywords(global, language);\n\n if (!emojiKeywords) {\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n });\n\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n isLoading: false,\n version: emojiKeywords.version,\n keywords: {\n ...(currentEmojiKeywords && currentEmojiKeywords.keywords),\n ...emojiKeywords.keywords,\n },\n },\n },\n });\n })();\n});\n\nasync function loadStickerSets(hash = 0) {\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 = 0) {\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 = 0) {\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 = 0) {\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) {\n const stickerSet = await callApi('fetchStickers', { stickerSetId, accessHash });\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\nasync function searchStickers(query: string, hash = 0) {\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 = 0) {\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 = 0) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const { nextOffsetId } = (resultsByType && resultsByType[type as ApiGlobalMessageSearchType]) || {};\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: globalUsers.map(({ id }) => id),\n userIds: globalChats.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n updateUsers,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n} from '../../reducers';\nimport {\n selectUser, selectChat, selectCurrentMessageList, selectDraft, selectChatMessage,\n} from '../../selectors';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', (global, actions) => {\n void afterSync(actions);\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync(actions: GlobalActions) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n actions.loadFavoriteStickers();\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n });\n if (!result) {\n return undefined;\n }\n\n let global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isChatPrivate(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n },\n };\n\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId],\n );\n });\n\n Object.keys(result.replyingToById).map(Number).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n });\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId).map(Number);\n const draftsByChatId = draftChatIds.reduce>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n return draft ? { ...acc, [chatId]: draft } : acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const byId = buildCollectionByKey(result.messages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n [currentChatId]: {\n byId,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfo && currentMessageListInfo.threadsById[MAIN_THREAD_ID]),\n listedIds,\n viewportIds: listedIds,\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).map(Number).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getDispatch().closeAudioPlayer();\n }\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter(Boolean as any);\n\n const updatedUsers = await callApi('fetchUsers', { users });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results ? results.nextOffsetId : undefined;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo ? threadInfo.topMessageId : undefined;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults ? currentResults.nextOffsetId : undefined;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce } from '../../../util/schedulers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, updateChat, updateManagementProgress, updateUser, updateUsers,\n} from '../../reducers';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60000; // 1 min\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const updatedUsers = await callApi('fetchUsers', { users: [user] });\n if (!updatedUsers) {\n return;\n }\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { hash, lastRequestedAt } = global.topPeers;\n\n if (!lastRequestedAt || Date.now() - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers(hash);\n }\n});\n\naddReducer('loadContactList', (global) => {\n const { hash } = global.contactList || {};\n void loadContactList(hash);\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteUser', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteUser(userId);\n});\n\nasync function loadTopUsers(usersHash?: number) {\n const result = await callApi('fetchTopUsers', { hash: usersHash });\n if (!result) {\n return;\n }\n\n const { hash, 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 hash,\n userIds: ids,\n lastRequestedAt: Date.now(),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList(hash?: number) {\n const contactList = await callApi('fetchContactList', { hash });\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 hash: contactList.hash,\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: number,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n const result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteUser(userId: number) {\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('deleteUser', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isChatPrivate(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, IInputPrivacyRules, IInputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n} from '../../reducers';\nimport { isChatPrivate } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers', 0);\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users && result.users.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats && result.chats.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isChatPrivate(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationExceptions', () => {\n callApi('fetchNotificationExceptions');\n});\n\naddReducer('loadNotificationSettings', () => {\n (async () => {\n const result = await callApi('fetchNotificationSettings');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: number[];\n deniedIds: number[];\n}): IInputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: IInputPrivacyRules = {\n visibility,\n };\n let users: IInputPrivacyContact[];\n let chats: IInputPrivacyContact[];\n\n const collectUsers = (userId: number) => {\n if (!isChatPrivate(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: number) => {\n if (isChatPrivate(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 IInputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\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 IInputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as IInputPrivacyContact[];\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","import { addReducer, getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiChat } from '../../../api/types';\n\nimport { RE_TME_INVITE_LINK, RE_TME_LINK } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChatMessage, selectCurrentChat } from '../../selectors';\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_INVITE_LINK) || button.value.match(RE_TME_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 '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({ messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n if (!currentUserId || !chat) {\n return;\n }\n\n void sendBotCommand(chat, currentUserId, command);\n});\n\nasync function sendBotCommand(chat: ApiChat, currentUserId: number, command: string) {\n await callApi('sendMessage', {\n chat,\n text: command,\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 || !result.message) {\n return;\n }\n\n const { message, alert: isError } = result;\n\n if (isError) {\n getDispatch().showError({ error: { message } });\n } else {\n getDispatch().showNotification({ message });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types/index';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n} from '../../selectors';\n\nimport { getStripeError } from '../../helpers/payments';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const messageId = selectPaymentMessageId(global);\n if (!messageId) {\n return;\n }\n validateRequestedInfo(messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', { messageId, requestInfo, shouldSave });\n if (!result) {\n return;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { messageId } = payload;\n if (!messageId) {\n return;\n }\n getPaymentForm(messageId);\n});\n\n\nasync function getPaymentForm(messageId: number) {\n const result = await callApi('getPaymentForm', { messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n if (!messageId || !receiptMessageId || !chatId) {\n return;\n }\n getReceipt(messageId, receiptMessageId, chatId);\n});\n\nasync function getReceipt(messageId: number, receiptMessageId: number, chatId: number) {\n const result = await callApi('getReceipt', receiptMessageId);\n if (!result) {\n return;\n }\n let global = getGlobal();\n const message = selectChatMessage(global, chatId, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n sendStipeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const messageId = selectPaymentMessageId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!messageId || !publishableKey) {\n return;\n }\n sendPaymentForm(messageId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStipeCredentials(data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n},\npublishableKey: string) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n messageId: number,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n messageId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { showNewMessageNotification } from '../../../util/notifications';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n updateChat,\n replaceChatListIds,\n updateChatListIds,\n updateChatListType,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n selectCountNotMutedUnread,\n} from '../../selectors';\nimport { throttle } from '../../../util/schedulers';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1000;\nconst runThrottledForUpdateAppBadge = throttle((cb) => cb(), CURRENT_CHAT_UNREAD_DELAY, true);\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!update.noTopChatsRequest && !selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n const newGlobal = updateChat(global, update.id, update.chat, update.newProfilePhoto);\n setGlobal(newGlobal);\n\n const unreadCount = selectCountNotMutedUnread(newGlobal);\n runThrottledForUpdateAppBadge(() => updateAppBadge(unreadCount));\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== update.id));\n }\n\n global = updateChat(global, update.id, { isNotJoined: true });\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n const isActiveChat = (\n messageListType === 'thread'\n && threadId === MAIN_THREAD_ID\n && update.chatId === currentChatId\n );\n\n if (isActiveChat) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n const unreadCount = selectCountNotMutedUnread(getGlobal());\n updateAppBadge(unreadCount);\n showNewMessageNotification({ chat, message, isActiveChat });\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = 'channelId' in update ? update.channelId : selectCommonBoxChatId(global, id);\n const chat = selectChat(global, chatId);\n if (chat && chat.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo && targetChat.fullInfo.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat && chat.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n} from '../../selectors';\nimport { getMessageContent, isChatPrivate, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const { chatId, id, message } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content && 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 });\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 (!message.isOutgoing) {\n setTimeout(() => {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n 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, 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 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 && !isChatPrivate(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 ids = Object.keys(global.messages.byChatId[chatId].byId).map(Number);\n\n deleteMessages(chatId, ids, actions, global);\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 && 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});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: number, 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 updateListedAndViewportIds(global: GlobalState, message: ApiMessage) {\n const { id, chatId } = message;\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n // Always keep the first uread message in the viewport list\n const firstUnreadId = selectFirstUnreadId(global, chatId, MAIN_THREAD_ID);\n const newGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(newGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = newGlobal;\n }\n }\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!firstMessageId && isMessageLocal(message)) {\n return global;\n }\n\n if (threadInfo) {\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 if (!threadInfo.lastMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n });\n }\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: number,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId] && 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: number) {\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: number | 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 const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: number[] = [];\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: number | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteUser, 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: [number, ApiUserStatus][] = [];\n\nfunction scheduleStatusUpdate(userId: number, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates.push([userId, statusUpdate]);\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n let global = getGlobal();\n pendingStatusUpdates.forEach(([userId, statusUpdate]) => {\n global = updateUser(global, userId, {\n status: statusUpdate,\n });\n });\n setGlobal(global);\n\n pendingStatusUpdates = [];\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteUser': {\n return deleteUser(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n hash: 0,\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.shouldShowPreviews);\n }\n\n case 'updateNotifyExceptions': {\n const {\n id, isMuted, isSilent, shouldShowPreviews,\n } = update;\n const chat = global.chats.byId[id];\n\n if (chat) {\n global = updateChat(global, id, { isMuted });\n }\n\n setGlobal(addNotifyException(global, id, { isMuted, isSilent, shouldShowPreviews }));\n break;\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Switcher.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n checked?: boolean;\n disabled?: boolean;\n inactive?: boolean;\n noAnimation?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Switcher: FC = ({\n id,\n name,\n value,\n label,\n checked = false,\n disabled,\n inactive,\n noAnimation,\n onChange,\n onCheck,\n}) => {\n const handleChange = useCallback((e: ChangeEvent) => {\n if (onChange) {\n onChange(e);\n }\n\n if (onCheck) {\n onCheck(e.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Switcher',\n disabled && 'disabled',\n inactive && 'inactive',\n noAnimation && 'no-animation',\n );\n\n return (\n \n );\n};\n\nexport default memo(Switcher);\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport { APP_NAME, APP_VERSION, FEEDBACK_URL } from '../../../config';\nimport { IS_MOBILE_SCREEN } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { pick } from '../../../util/iteratees';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: number;\n globalSearchChatId?: number;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst LEGACY_VERSION_URL = 'https://web.telegram.org/?legacy=1';\nconst WEBK_VERSION_URL = 'https://web.telegram.org/k/';\nconst PERMANENT_VERSION_KEY = 'kz_version';\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n setGlobalSearchChatId,\n onReset,\n searchQuery,\n isLoading,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption,\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 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]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId });\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 switchTheme(newTheme, animationLevel > 0);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const handleSwitchToWebK = () => {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify('K'));\n };\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 \n Switch to K Version\n \n \n Switch to Old Version\n \n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { theme, 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,\n animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n 'openTipsChat',\n 'setGlobalSearchDate',\n 'setGlobalSearchChatId',\n 'setSettingOption',\n ]),\n)(LeftMainHeader));\n","import React, { FC } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalState } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = ({ connectionState }) => {\n const lang = useLang();\n\n const isConnecting = connectionState === 'connectionStateConnecting';\n\n return isConnecting && (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(ConnectionState);\n","import { useRef } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useForceUpdate from './useForceUpdate';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const valueRef = useRef();\n const runThrottled = useThrottle(ms);\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n let isSync = true;\n runThrottled(() => {\n valueRef.current = resolverFn();\n\n if (!isSync) {\n forceUpdate();\n }\n });\n isSync = false;\n }, dependencies);\n\n return valueRef.current;\n};\n","import { useMemo } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\n\nexport default (ms: number) => {\n return useMemo(() => {\n return throttle((cb) => cb(), ms);\n }, [ms]);\n};\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\nimport { NotifyException, NotifySettings } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { buildCollectionByKey, pick } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../modules/selectors';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype StateProps = {\n chatsById: Record;\n usersById: Record;\n chatFoldersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: number;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\n chatsById,\n usersById,\n chatFoldersById,\n notifySettings,\n notifyExceptions,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const chatIds = Object.keys(chatsById).map(Number);\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(chatsById, usersById, folder, chatIds, notifySettings, notifyExceptions) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, chatsById, usersById, notifySettings, notifyExceptions]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: lang('FilterAllChats') },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById && folderCountersById[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById, lang]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveChatFolder(index);\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 onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveChatFolder(Math.min(activeChatFolder + 1, folderTabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveChatFolder(Math.max(0, activeChatFolder - 1));\n }\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 useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.metaKey && 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 });\n return;\n }\n\n const folder = Number(digit) - 1;\n if (folder > folderTabs.length - 1) return;\n\n setActiveChatFolder(folder);\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(({ title }) => title === folderTabs![activeChatFolder].title);\n\n if (!activeFolder || activeChatFolder === 0) {\n return ;\n }\n\n return (\n \n );\n }\n\n return (\n
\n {folderTabs && folderTabs.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n } = global;\n\n return {\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n activeChatFolder,\n currentUserId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadChatFolders',\n 'setActiveChatFolder',\n 'openChat',\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, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n {lang('NewMessageTitle')}\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, memo, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\n\nimport { LeftColumnContent } from '../../../types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onReset: () => void;\n};\n\ntype StateProps = {};\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n onSearchQuery,\n onContentChange,\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 return (\n \n \n \n \n {(isActive) => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n \n
\n );\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, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\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};\n\ntype DispatchProps = Pick;\n\nenum ContentType {\n Main,\n // eslint-disable-next-line 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 setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n}) => {\n const [content, setContent] = useState(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\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 (\n content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\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.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n 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, setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId, resetChatCreation,\n settingsScreen,\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, setGlobalSearchQuery, searchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || activeChatFolder === 0\n ? captureEscKeyListener(() => handleReset())\n : undefined),\n [activeChatFolder, content, handleReset],\n );\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n return (\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\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n globalSearch: {\n query,\n date,\n },\n chatFolders: {\n activeChatFolder,\n },\n } = global;\n return { searchQuery: query, searchDate: date, activeChatFolder };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setGlobalSearchQuery', 'setGlobalSearchChatId', 'resetChatCreation', 'setGlobalSearchDate',\n 'loadPasswordInfo', 'clearTwoFaError',\n ]),\n)(LeftColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { IDimensions } from '../modules/helpers';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\n\nconst THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, THROTTLE, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return size;\n};\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? : undefined;\n};\n\nexport default memo(HeaderMenuContainerAsync);\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { pick } from '../../util/iteratees';\nimport { isChatChannel, isChatSuperGroup } from '../../modules/helpers';\nimport {\n selectChat,\n selectIsChatBotNotStarted, selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canMute?: boolean;\n canSelect?: boolean;\n canLeave?: boolean;\n}\n\ntype DispatchProps = Pick;\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 canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n isRightColumnShown,\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\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 handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_MOBILE_SCREEN) {\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 const lang = useLang();\n\n return (\n
\n {!IS_MOBILE_SCREEN && canSubscribe && (\n \n {lang(isChannel ? 'Subscribe' : 'Join Group')}\n \n )}\n {!IS_MOBILE_SCREEN && canStartBot && (\n \n {lang('Start')}\n \n )}\n {!IS_MOBILE_SCREEN && canSearch && (\n \n \n \n )}\n {(IS_MOBILE_SCREEN || !canSubscribe) && (\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) {\n return {\n noMenu: true,\n };\n }\n\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 canStartBot = Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && chat && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canSelect = !selectIsInSelectMode(global);\n const canLeave = isMainThread && !canSubscribe;\n\n const noMenu = !(\n (IS_MOBILE_SCREEN && canSubscribe)\n || (IS_MOBILE_SCREEN && canSearch)\n || canMute\n || canSelect\n || canLeave\n );\n\n return {\n noMenu,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canSubscribe,\n canSearch,\n canMute,\n canSelect,\n canLeave,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'joinChannel', 'sendBotCommand', 'openLocalTextSearch',\n ]),\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbnail = message && getMessageMediaThumbDataUri(message);\n const { sticker } = (message && message.content) || {};\n const shouldDecodeThumbnail = thumbnail && sticker && !isWebpSupported() && thumbnail.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message && message.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbnail!)\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, thumbnail]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbnail;\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 && containerRef.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = ` ${clipPath} `;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n
\n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `\n \n `\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const lang = useLang();\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(lang, message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n return (\n
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser,\n} from '../../api/types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageAudio, getMessageKey, getMessageMediaHash, getSenderTitle,\n} from '../../modules/helpers';\nimport { selectSender } from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport renderText from '../common/helpers/renderText';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiChat | ApiUser;\n};\n\ntype DispatchProps = Pick;\n\nconst AudioPlayer: FC = ({\n message, className, noUi, sender, focusMessage, closeAudioPlayer,\n}) => {\n const lang = useLang();\n\n const senderName = sender ? getSenderTitle(lang, sender) : undefined;\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const { playPause, isPlaying } = useAudioPlayer(\n getMessageKey(message), getMediaDuration(message)!, mediaData, undefined, undefined, true,\n );\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 }, [closeAudioPlayer, isPlaying, playPause]);\n\n if (noUi) {\n return undefined;\n }\n\n const audio = getMessageAudio(message);\n\n return (\n
\n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\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\n return { sender };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage', 'closeAudioPlayer']),\n)(AudioPlayer);\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiTypingStatus,\n MAIN_THREAD_ID, ApiUser,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport {\n isChatPrivate,\n isChatArchived,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n selectIsChatMuted,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadOriginChat,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n selectNotifySettings,\n selectNotifyExceptions,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { pick } from '../../util/iteratees';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n pinnedMessageIds?: number[] | number;\n messagesById?: Record;\n canUnpin?: boolean;\n topMessageSender?: ApiChat | ApiUser;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatsById?: Record;\n originChatId: number;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst MiddleHeader: FC = ({\n chatId,\n threadId,\n messageListType,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageSender,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chat,\n chatsById,\n originChatId,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n notifySettings,\n notifyExceptions,\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n}) => {\n const lang = useLang();\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) ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : 0);\n const chatTitleLength = chat && getChatTitle(lang, chat).length;\n const topMessageTitle = topMessageSender ? getSenderTitle(lang, topMessageSender) : undefined;\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId]);\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 = windowWidth >= MOBILE_SCREEN_MAX_WIDTH && 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, 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 handleBackClick = useCallback(() => {\n if (IS_MOBILE_SCREEN) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread') {\n if (IS_MOBILE_SCREEN) {\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n return;\n }\n\n if (messageListType === 'scheduled' && isSelectModeActive) {\n exitMessageSelectMode();\n }\n openChat({ id: originChatId, threadId: MAIN_THREAD_ID });\n }, [openChat, originChatId, threadId, messageListType, toggleLeftColumn, isSelectModeActive, exitMessageSelectMode]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n let isActive = false;\n\n const totalCount = Object.values(chatsById).reduce((total, currentChat) => {\n if (isChatArchived(currentChat)) {\n return total;\n }\n\n const count = currentChat.unreadCount || 0;\n if (\n count && (!selectIsChatMuted(currentChat, notifySettings, notifyExceptions) || currentChat.unreadMentionsCount)\n ) {\n isActive = true;\n }\n\n return total + count;\n }, 0);\n\n if (!totalCount) {\n return undefined;\n }\n\n return {\n isActive,\n totalCount,\n };\n }, [isLeftColumnHideable, chatsById, notifySettings, notifyExceptions]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(pinnedMessage && !shouldRenderAudioPlayer);\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage);\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 function renderInfo() {\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n

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

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

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

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

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

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {isLeftColumnHideable && renderBackButton(shouldShowCloseButton, unreadCount)}\n
\n {isChatPrivate(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, unreadCountInfo?: typeof unreadCount) {\n return (\n
\n \n
\n \n {unreadCountInfo && (\n
\n {formatIntegerCompact(unreadCountInfo.totalCount)}\n
\n )}\n
\n );\n }\n\n return (\n
\n \n {renderInfo}\n \n\n
\n {shouldRenderPinnedMessage && renderingPinnedMessage && !shouldRenderAudioPlayer && (\n \n )}\n {shouldRenderAudioPlayer && renderingAudioMessage && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n const originChat = selectThreadOriginChat(global, chatId, threadId);\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds && pinnedIds.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds && scheduledIds.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (threadInfo) {\n messagesCount = threadInfo.messagesCount;\n }\n }\n\n const state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chat,\n chatsById,\n originChatId: originChat ? originChat.id : chatId,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\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 && 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 (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChatWithInfo',\n 'pinMessage',\n 'focusMessage',\n 'openChat',\n 'loadPinnedMessages',\n 'toggleLeftColumn',\n 'exitMessageSelectMode',\n ]),\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDatetime = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDatetime) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDatetime,\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 ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport { debounce } from '../util/schedulers';\n\nexport default function useDebounce(ms: number, shouldRunFirst?: boolean, shouldRunLast?: boolean) {\n return useMemo(() => {\n return debounce((cb) => cb(), ms, shouldRunFirst, shouldRunLast);\n }, [ms, shouldRunFirst, shouldRunLast]);\n}\n","import { MutableRefObject } from 'react';\nimport React, {\n FC, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\n\nimport { MESSAGE_LIST_SENSITIVE_AREA } from '../../config';\nimport resetScroll from '../../util/resetScroll';\nimport { useIntersectionObserver, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\n\ntype OwnProps = {\n containerRef: MutableRefObject;\n className: string;\n messageIds: number[];\n focusingId?: number;\n loadMoreForwards?: NoneToVoidFunction;\n loadMoreBackwards?: NoneToVoidFunction;\n isViewportNewest?: boolean;\n firstUnreadId?: number;\n onFabToggle: AnyToVoidFunction;\n onNotchToggle: AnyToVoidFunction;\n children: any;\n};\n\nconst FAB_THRESHOLD = 50;\nconst TOOLS_FREEZE_TIMEOUT = 100;\n\n// Local flag is used because `freeze/unfreeze` methods are controlled by heavy animation\nlet areToolsFrozen = false;\n\nconst MessageScroll: FC = ({\n containerRef,\n className,\n messageIds,\n focusingId,\n loadMoreForwards,\n loadMoreBackwards,\n isViewportNewest,\n firstUnreadId,\n onFabToggle,\n onNotchToggle,\n children,\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 const toggleScrollTools = useCallback(() => {\n if (areToolsFrozen) {\n return;\n }\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n onNotchToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n onNotchToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = scrollHeight - scrollTop - offsetHeight;\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom <= 0;\n\n onFabToggle(firstUnreadId ? !isAtBottom : !isNearBottom);\n onNotchToggle(!isAtBottom);\n }, [messageIds, isViewportNewest, containerRef, onFabToggle, firstUnreadId, onNotchToggle]);\n\n const {\n observe: observeIntersection,\n freeze: freezeForLoadMore,\n unfreeze: unfreezeForLoadMore,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\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 resetScroll(containerRef.current!);\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger') {\n resetScroll(containerRef.current!);\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,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n const {\n observe: observeIntersectionForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\n\n // Do not load more and show FAB when focusing\n useOnChange(() => {\n if (focusingId) {\n freezeForLoadMore();\n freezeForFab();\n } else {\n unfreezeForFab();\n unfreezeForLoadMore();\n }\n }, [focusingId]);\n\n // Workaround for FAB and notch flickering with tall incoming message\n useOnChange(() => {\n areToolsFrozen = true;\n\n setTimeout(() => {\n areToolsFrozen = false;\n }, TOOLS_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n // Workaround for stuck FAB when many unread messages\n useEffect(toggleScrollTools, [firstUnreadId]);\n\n return (\n
\n
\n {children}\n \n \n
\n );\n};\n\nexport default MessageScroll;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMediaWithNoText = (photo || video) && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video && video.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo) {\n classNames.push('media');\n }\n }\n\n if (asForwarded && !customShape) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_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 : MIN_MEDIA_WIDTH;\n}\n\nexport function calculateMediaDimensions(message: ApiMessage) {\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)\n : calculateVideoDimensions(video!, isOwn, isForwarded);\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 } from '../../../../api/types';\nimport { IDimensions } from '../../../../modules/helpers';\n\nimport { MOBILE_SCREEN_MAX_WIDTH } from '../../../../config';\nimport { REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nconst MAX_WIDTH_MOBILE_VW = 69;\nconst MAX_WIDTH_DESK_OWN_REM = 30;\nconst MAX_WIDTH_DESK_REM = 29;\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: IDimensions;\n};\n\nfunction getMaxWidth(isOwn: boolean, isForwarded: boolean, windowWidth: number) {\n if (windowWidth <= MOBILE_SCREEN_MAX_WIDTH) {\n return (windowWidth / 100) * MAX_WIDTH_MOBILE_VW - (isForwarded ? 1.625 : 0) * REM;\n }\n\n const maxWidth = isOwn ? MAX_WIDTH_DESK_OWN_REM : MAX_WIDTH_DESK_REM;\n\n return (maxWidth - (isForwarded ? 1.625 : 0)) * REM;\n}\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as IDimensions;\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: IDimensions = { 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 album: IAlbum,\n windowWidth: number,\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 = getMaxWidth(isOwn, isForwarded, windowWidth);\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\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","let element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n element.style.font = '400 12px Roboto, \"Helvetica Neue\", \"Apple Color Emoji\", 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 { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\nimport { FocusDirection } from '../../../../types';\n\n// This is the max scroll offset within existing viewport.\nconst FOCUS_MAX_OFFSET = 1500;\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: number,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: 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' : 'center',\n FOCUS_MARGIN,\n focusDirection === undefined ? FOCUS_MAX_OFFSET : RELOCATED_FOCUS_OFFSET,\n focusDirection,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight]);\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, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n isLastInList?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiUser | ApiChat;\n targetUser?: ApiUser;\n targetMessage?: ApiMessage;\n targetChatId?: number;\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 sender,\n targetUser,\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 content = renderActionMessageText(\n lang,\n message,\n sender,\n targetUser,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n if (isEmbedded) {\n return {renderText(content as string)};\n }\n\n const className = buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n isLastInList && 'last-in-list',\n transitionClassNames,\n );\n\n return (\n \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message }): StateProps => {\n const userId = message.senderId;\n const { targetUserId, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n sender,\n ...(targetUserId && { targetUser: selectUser(global, targetUserId) }),\n targetChatId,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n getMessageRoundVideo,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC = ({\n className,\n message,\n sender,\n title,\n customText,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n const isRoundVideo = Boolean(message && getMessageRoundVideo(message));\n\n const lang = useLang();\n\n const senderTitle = sender && getSenderTitle(lang, sender);\n\n return (\n \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl, isRoundVideo)}\n
\n

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

\n
{renderText(senderTitle || title || NBSP)}
\n
\n
\n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n isRoundVideo?: boolean,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \n );\n}\n\nexport default EmbeddedMessage;\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: () => void;\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000)}\n \n {outgoingStatus && (\n \n )}\n \n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport useMedia from '../../../hooks/useMedia';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const { shouldRenderFullMedia, transitionClassNames } = useTransitionForMedia(isMediaReady, 'slow');\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n
\n {!isMediaReady && (\n \n )}\n {!isAnimated && shouldRenderFullMedia && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { IS_CANVAS_FILTER_SUPPORTED, IS_MOBILE_SCREEN } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useCanvasBlur from '../../../../hooks/useCanvasBlur';\n\nexport default function useBlurredMediaThumbRef(message: ApiMessage, fullMediaData?: string) {\n return useCanvasBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_MOBILE_SCREEN && !IS_CANVAS_FILTER_SUPPORTED,\n );\n}\n","const SELECTED_APPENDIX_BACKGROUND = 'rgba(255,255,255,1)';\n\nexport default async (src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean) => {\n return isSelected ? SELECTED_APPENDIX_BACKGROUND : 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 { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport usePrevious from '../../../hooks/usePrevious';\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 shouldAutoLoad?: 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 onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n nonInteractive,\n shouldAffectAppendix,\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 [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = isDownloadAllowed && isIntersecting;\n const {\n mediaData, downloadProgress,\n } = useMediaWithDownloadProgress(getMessageMediaHash(message, size), !shouldDownload);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbRef = useBlurredMediaThumbRef(message, fullMediaData);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(message, uploadProgress || downloadProgress, shouldDownload && !fullMediaData);\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled, 'slow');\n const {\n shouldRenderThumb, shouldRenderFullMedia, transitionClassNames,\n } = useTransitionForMedia(fullMediaData, 'slow');\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsDownloadAllowed((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).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]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message);\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 {shouldRenderThumb && (\n \n )}\n {shouldRenderFullMedia && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!fullMediaData && !isDownloadAllowed && (\n \n )}\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n \n );\n};\n\nexport default Photo;\n","import { RefObject } from 'react';\nimport { useCallback, useRef } from '../lib/teact/teact';\n\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport safePlay from '../util/safePlay';\n\nexport default function useHeavyAnimationCheckForVideo(playerRef: RefObject, shouldPlay: boolean) {\n const shouldPlayRef = useRef();\n shouldPlayRef.current = shouldPlay;\n\n const pause = useCallback(() => {\n if (playerRef.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const play = useCallback(() => {\n if (playerRef.current && shouldPlayRef.current) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n useHeavyAnimationCheck(pause, play);\n}\n","import { useCallback, useRef } from '../../../../lib/teact/teact';\nimport { fastRaf } from '../../../../util/schedulers';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport safePlay from '../../../../util/safePlay';\n\nexport default (playerRef: { current: HTMLVideoElement | null }, isPlayAllowed = false) => {\n const wasPlaying = useRef(false);\n const isFrozen = useRef(false);\n\n const freezePlaying = useCallback(() => {\n isFrozen.current = true;\n\n if (!isPlayAllowed || !playerRef.current) {\n return;\n }\n\n if (!wasPlaying.current) {\n wasPlaying.current = !playerRef.current.paused;\n }\n\n playerRef.current.pause();\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n // At this point HTMLVideoElement can be unmounted from the DOM\n if (isPlayAllowed && playerRef.current && wasPlaying.current && document.body.contains(playerRef.current)) {\n safePlay(playerRef.current);\n }\n\n wasPlaying.current = false;\n isFrozen.current = false;\n }, [isPlayAllowed, playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n if (!document.hasFocus()) {\n freezePlaying();\n }\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\n};\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { 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 canMessagePlayVideoInline,\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\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 shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC = ({\n id,\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\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 = message.content.video!;\n const localBlobUrl = video.blobUrl;\n const canPlayInline = Boolean(localBlobUrl) || canMessagePlayVideoInline(video);\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(shouldAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(canPlayInline && isIntersecting && fullMediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering(!shouldAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || downloadProgress,\n shouldDownload && (canPlayInline && !isBuffered),\n );\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(fullMediaData, 'slow');\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 isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded);\n\n useHeavyAnimationCheckForVideo(videoRef, Boolean(isInline && shouldAutoPlay));\n\n usePauseOnInactive(videoRef, isPlayAllowed);\n\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (canPlayInline && !fullMediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n } else if (canPlayInline && fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, canPlayInline, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n const shouldRenderInlineVideo = isInline;\n const shouldRenderHqPreview = !canPlayInline && mediaData;\n const shouldRenderPlayButton = !canPlayInline || (isDownloadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n const shouldRenderDownloadButton = canPlayInline && !isDownloadAllowed;\n\n return (\n \n {(!isInline || shouldRenderThumb)\n && (\n \n )}\n {previewBlobUrl && (\n \n )}\n\n {shouldRenderInlineVideo && (\n \n \n \n )}\n {shouldRenderHqPreview && (\n \n )}\n {shouldRenderPlayButton && (\n \n )}\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && (\n \n )}\n {isTransferring && !canPlayInline ? (\n {Math.round(transferProgress * 100)}%\n ) : isTransferring && canPlayInline ? (\n ...\n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(video.duration - playProgress)}\n
\n )}\n \n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiUser, ApiContact } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n};\n\ntype DispatchProps = Pick;\n\nconst Contact: FC = ({\n contact, user, openUserInfo,\n}) => {\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\n (global, { contact }): StateProps => {\n return {\n user: selectUser(global, contact.userId),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n ]),\n)(Contact);\n","import { ChangeEvent } from 'react';\nimport React, {\n FC, useCallback, memo, useState,\n} from '../../lib/teact/teact';\n\nimport Checkbox from './Checkbox';\n\ntype IRadioOption = {\n label: string;\n subLabel?: string;\n value: string;\n};\n\ntype OwnProps = {\n id?: string;\n options: IRadioOption[];\n selected?: string[];\n disabled?: boolean;\n round?: boolean;\n loadingOptions?: string[];\n onChange: (value: string[]) => void;\n};\n\nconst CheckboxGroup: FC = ({\n id,\n options,\n selected = [],\n disabled,\n round,\n loadingOptions,\n onChange,\n}) => {\n const [values, setValues] = useState([]);\n\n const handleChange = useCallback((event: ChangeEvent) => {\n const { value, checked } = event.currentTarget;\n let newValues: string[];\n if (checked) {\n newValues = [...values, value];\n } else {\n newValues = values.filter((v) => v !== value);\n }\n\n setValues(newValues);\n onChange(newValues);\n }, [onChange, values]);\n\n return (\n
\n {options.map((option) => (\n \n ))}\n
\n );\n};\n\nexport default memo(CheckboxGroup);\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 && 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 { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record;\n};\n\ntype DispatchProps = Pick;\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 loadMessage,\n onSendVote,\n openPollResults,\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), 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)}
\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 { byId: usersById } = global.users;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadMessage', 'openPollResults']),\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n shouldAutoLoad?: boolean;\n inPreview?: boolean;\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n inPreview,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage && webPage.photo) {\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 } = webPage;\n\n const isMediaInteractive = photo && onMediaClick && !isSquarePhoto && !webPage.hasDocument;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n photo\n ? (isSquarePhoto && 'with-square-photo')\n : (!inPreview && 'without-photo'),\n );\n\n return (\n \n {photo && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

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

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

\n )}\n
\n
\n );\n};\n\nexport default memo(WebPage);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageInvoice } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\n\nimport './Invoice.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n};\n\nconst Invoice: FC = ({\n message,\n}) => {\n const invoice = getMessageInvoice(message);\n\n const {\n title,\n text,\n description,\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 {description && (\n

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

\n )}\n
\n
\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport { GlobalActions } from '../../../../global/types';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\nimport { pick } from '../../../../util/iteratees';\n\ntype OwnProps = PhotoProps & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nexport default function withSelectControl(WrapedComponent: FC) {\n const Component: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n toggleMessageSelection,\n dimensions,\n } = props;\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e && e.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n (setGlobal, actions) => pick(actions, [\n 'toggleMessageSelection',\n ]),\n )(Component));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { withGlobal } from '../../../lib/teact/teactn';\nimport { pick } from '../../../util/iteratees';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\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 shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n};\n\ntype DispatchProps = Pick;\n\nconst Album: FC = ({\n album,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n albumLayout,\n onMediaClick,\n uploadsById,\n cancelSendingMessage,\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 ? fileUpload.progress : undefined;\n const { dimensions, sides } = albumLayout.layout[index];\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): StateProps => {\n return {\n uploadsById: global.fileUploads.byMessageLocalId,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'cancelSendingMessage',\n ]),\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS } from '../../common/helpers/mediaDimensions';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithDownloadProgress from '../../../hooks/useMediaWithDownloadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useTransitionForMedia from '../../../hooks/useTransitionForMedia';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport buildClassName from '../../../util/buildClassName';\nimport useHeavyAnimationCheckForVideo from '../../../hooks/useHeavyAnimationCheckForVideo';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport usePauseOnInactive from './hooks/usePauseOnInactive';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport safePlay from '../../../util/safePlay';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n shouldAutoLoad?: boolean;\n shouldAutoPlay?: boolean;\n lastSyncTime?: number;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC = ({\n message,\n observeIntersection,\n shouldAutoLoad,\n shouldAutoPlay,\n lastSyncTime,\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 [isDownloadAllowed, setIsDownloadAllowed] = useState(shouldAutoLoad && shouldAutoPlay);\n const shouldDownload = Boolean(isDownloadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, downloadProgress } = useMediaWithDownloadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldDownload,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = isDownloadAllowed && !isBuffered;\n const wasDownloadDisabled = usePrevious(isDownloadAllowed) === false;\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasDownloadDisabled);\n const { shouldRenderThumb, transitionClassNames } = useTransitionForMedia(mediaData, 'slow');\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 circumference = 94 * 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 } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n requestAnimationFrame(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useHeavyAnimationCheckForVideo(playerRef, shouldPlay);\n\n usePauseOnInactive(playerRef, Boolean(mediaData));\n\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsDownloadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n } else {\n playerEl.pause();\n }\n } else {\n capturePlaying();\n playerEl.currentTime = 0;\n setIsActivated(true);\n }\n }, [capturePlaying, isActivated, mediaData]);\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 {shouldRenderThumb && (\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 && !isDownloadAllowed && (\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 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 return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {button.text}\n {button.type === 'url' && }\n \n ))}\n
\n ))}\n
\n );\n};\n\nexport default InlineButtons;\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiMessage, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\nimport { GlobalActions } from '../../../global/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { isChatPrivate } from '../../../modules/helpers';\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectThreadInfo } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n disabled?: boolean;\n};\n\ntype StateProps = {\n threadInfo: ApiThreadInfo;\n usersById?: Record;\n chatsById?: Record;\n};\n\ntype DispatchProps = Pick;\n\nconst CommentButton: FC = ({\n disabled, threadInfo, usersById, chatsById, openChat,\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 if (messagesCount === undefined) {\n return undefined;\n }\n\n const recentRepliers = recentReplierIds && recentReplierIds.map((peerId) => {\n return isChatPrivate(peerId) ? usersById![peerId] : chatsById![peerId];\n }).filter(Boolean);\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(withGlobal(\n (global, { message }) => {\n const { threadId, chatId } = message.threadInfo!;\n\n const threadInfo = selectThreadInfo(global, chatId, threadId) || message.threadInfo!;\n const { byId: usersById } = global.users;\n const { byId: chatsById } = global.chats;\n\n return {\n threadInfo,\n usersById,\n chatsById,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat',\n ]),\n)(CommentButton));\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { FocusDirection, IAlbum, MediaViewerOrigin } from '../../../types';\n\nimport { pick } from '../../../util/iteratees';\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 selectShouldAutoLoadMedia,\n selectShouldAutoPlayMedia, selectShouldLoopStickers,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isChatPrivate,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji, getSenderTitle, getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS } 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 useFocusMessage from './hooks/useFocusMessage';\nimport useWindowSize from '../../../hooks/useWindowSize';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n} & MessagePositionProperties;\n\ntype StateProps = {\n forceSenderName?: boolean;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isChannel?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n shouldAutoLoadMedia?: boolean;\n shouldAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = '';\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = '';\nconst APPEARANCE_DELAY = 10;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\n\nconst Message: FC = ({\n message,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n shouldAutoLoadMedia,\n shouldAutoPlayMedia,\n shouldLoopStickers,\n focusMessage,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n openChat,\n cancelSendingMessage,\n markMessagesRead,\n sendPollVote,\n toggleMessageSelection,\n setReplyingToId,\n openForwardMenu,\n clickInlineButton,\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 appendixRef = useRef(null);\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const { width: windowWidth } = useWindowSize();\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref, false, true);\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 { chatId, id: messageId, threadInfo } = message;\n\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 { forwardInfo, viaBotId } = message;\n const asForwarded = forwardInfo && !isChatWithSelf && !forwardInfo.isLinkedChannelPost;\n const isInDocumentGroup = !!message.groupedId && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const customShape = getMessageCustomShape(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\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 transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: message.threadInfo && message.threadInfo.messagesCount > 0,\n });\n const avatarPeer = forwardInfo && (isChatWithSelf || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n const signature = (\n (isChannel && message.adminTitle) || (forwardInfo && !asForwarded && forwardInfo.adminTitle) || undefined\n );\n const withCommentButton = message.threadInfo && (!isInDocumentGroup || isLastInDocumentGroup)\n && messageListType === 'thread' && !noComments;\n const withAppendix = contentClassName.includes('has-appendix');\n\n useEnsureMessage(chatId, hasReply ? message.replyToMessageId : undefined, replyMessage, message.id);\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight);\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = isOwn ? APPENDIX_OWN : APPENDIX_NOT_OWN;\n }, [isOwn, withAppendix]);\n\n const handleGroupDocumentMessagesSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n\n toggleMessageSelection({\n messageId,\n groupedId: message.groupedId,\n });\n }, [messageId, message.groupedId, toggleMessageSelection]);\n\n const handleMessageSelect = useCallback((e?: ReactMouseEvent) => {\n const params = isAlbum && album && album.messages\n ? {\n messageId,\n childMessageIds: album.messages.map(({ id }) => id),\n withShift: e && e.shiftKey,\n }\n : { messageId, withShift: e && e.shiftKey };\n toggleMessageSelection(params);\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const handleContainerDoubleClick = useCallback(() => {\n setReplyingToId({ messageId });\n }, [setReplyingToId, messageId]);\n\n const handleContentDoubleClick = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n }, []);\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isChatPrivate(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n return;\n }\n\n if (isChatPrivate(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [senderPeer, openUserInfo, openChat]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({ chatId, threadId, messageId: message.replyToMessageId });\n }, [focusMessage, chatId, threadId, message.replyToMessageId]);\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: message.groupedId });\n }, [openForwardMenu, chatId, message.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: message.groupedId, groupedChatId: chatId,\n });\n return;\n }\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }, [focusMessage, forwardInfo, message, chatId, isInDocumentGroup]);\n\n const lang = useLang();\n\n let style = '';\n let calculatedWidth;\n let noMediaCorners = false;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), album!, windowWidth) : undefined;\n }, [isAlbum, windowWidth, isOwn, asForwarded, 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).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS;\n } else {\n width = calculateMediaDimensions(message).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), width);\n if (calculatedWidth - width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), albumLayout.containerStyle.width);\n if (calculatedWidth - albumLayout.containerStyle.width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isChatPrivate(avatarPeer.id);\n const avatarUser = avatarPeer && isAvatarPeerUser ? avatarPeer as ApiUser : undefined;\n const avatarChat = avatarPeer && !isAvatarPeerUser ? avatarPeer as ApiChat : undefined;\n const hiddenName = !avatarPeer && forwardInfo ? forwardInfo.hiddenUserName : undefined;\n\n return (\n \n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && !customShape && 'forwarded-message',\n hasReply && 'reply-message',\n noMediaCorners && 'no-media-corners',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n const shouldInlineMeta = !webPage && !animatedEmoji && textParts;\n\n return (\n
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts && (\n

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

\n )}\n {webPage && (\n \n )}\n {invoice && (\n \n )}\n
\n );\n }\n\n function renderSenderName() {\n const shouldRender = !customShape && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer) {\n senderTitle = getSenderTitle(lang, senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo && 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 && forwardInfo.isLinkedChannelPost ? (\n {lang('DiscussChannel')}\n ) : message.adminTitle && !isChannel ? (\n {message.adminTitle}\n ) : undefined}\n
\n );\n }\n\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = canShowActionButton && isChannel && !isScheduled;\n const canFocus = canShowActionButton && (\n (forwardInfo && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn)) && forwardInfo.fromMessageId)\n || isPinnedList\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 {withAppendix && (
)}\n {asForwarded && !customShape && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && !(!webPage && !animatedEmoji && textParts) && (\n \n )}\n {canForward ? (\n \n \n \n ) : canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {contentClassName.includes('has-appendix') &&
}\n
\n {message.inlineButtons && (\n \n )}\n
\n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToMessageId, isOutgoing,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isChannel = chat && isChatChannel(chat);\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = canShowSender ? selectSender(global, message) : undefined;\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, 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 { direction: focusDirection, noHighlight: noFocusHighlight } = (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 && album.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n return {\n forceSenderName,\n sender,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n isForwarding,\n isChatWithSelf,\n isChannel,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isPinnedList: messageListType === 'pinned',\n shouldAutoLoadMedia: chat ? selectShouldAutoLoadMedia(global, message, chat, sender) : undefined,\n shouldAutoPlayMedia: selectShouldAutoPlayMedia(global, message),\n shouldLoopStickers: selectShouldLoopStickers(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'focusMessage',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'cancelSendingMessage',\n 'openUserInfo',\n 'openChat',\n 'markMessagesRead',\n 'sendPollVote',\n 'toggleMessageSelection',\n 'setReplyingToId',\n 'openForwardMenu',\n 'clickInlineButton',\n ]),\n)(Message));\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, MESSAGE_LIST_SLICE, SCHEDULED_WHEN_ONLINE } from '../../config';\nimport { IS_ANDROID, IS_MOBILE_SCREEN } from '../../util/environment';\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, selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n getMessageOriginalId,\n isActionMessage,\n isChatChannel,\n isChatPrivate,\n isOwnMessage,\n} from '../../modules/helpers';\nimport {\n compact,\n flatten,\n orderBy,\n pick,\n} from '../../util/iteratees';\nimport {\n fastRaf, debounce, onTickEnd,\n} from '../../util/schedulers';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages, MessageDateGroup, isAlbum } from './helpers/groupMessages';\nimport { ObserveFn, useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll from '../../util/resetScroll';\nimport fastSmoothScroll, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang, { LangFn } from '../../hooks/useLang';\nimport useWindowSize from '../../hooks/useWindowSize';\n\nimport Loading from '../ui/Loading';\nimport MessageScroll from './MessageScroll';\nimport Message from './message/Message';\nimport ActionMessage from './ActionMessage';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n type: MessageListType;\n canPost: boolean;\n onFabToggle: (shouldShow: boolean) => void;\n onNotchToggle: (shouldShow: boolean) => void;\n hasTools?: boolean;\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n isChatWithSelf?: 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};\n\ntype DispatchProps = Pick;\n\nconst BOTTOM_THRESHOLD = 100;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_MOBILE_SCREEN ? 300 : 500;\nconst FOCUSING_DURATION = 1000;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst FOCUSING_FADE_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 canPost,\n isChatWithSelf,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n animationLevel,\n loadViewportMessages,\n markMessageListRead,\n markMessagesRead,\n setScrollOffset,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\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 memoUnreadDividerBeforeIdRef = useRef();\n // Updated every time (to be used from intersection callback closure)\n const memoFirstUnreadIdRef = useRef();\n const memoFocusingIdRef = useRef();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(!messageIds);\n\n const [containerHeight, setContainerHeight] = useState();\n const [hasFocusing, setHasFocusing] = useState(Boolean(focusingId));\n\n const areMessagesLoaded = Boolean(messageIds);\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 useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n\n // Updated only once (to preserve divider even after messages are read)\n if (!memoUnreadDividerBeforeIdRef.current) {\n memoUnreadDividerBeforeIdRef.current = firstUnreadId;\n }\n }, [firstUnreadId]);\n\n const {\n observe: observeIntersectionForMedia, freeze: freezeForMedia, unfreeze: unfreezeForMedia,\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 }, (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 useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n\n if (focusingId) {\n freezeForMedia();\n freezeForReading();\n } else {\n unfreezeForReading();\n unfreezeForMedia();\n }\n }, [focusingId]);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n useEffect(() => {\n if (focusingId) {\n setHasFocusing(true);\n } else {\n setTimeout(() => {\n setHasFocusing(false);\n }, FOCUSING_FADE_ANIMATION_DURATION);\n }\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const [loadMoreBackwards, loadMoreForwards, loadMoreAround] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\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 useEffect(() => {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }, [windowHeight]);\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Remember scroll position before repositioning it\n useOnChange(() => {\n if (!messageIds || !listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n // This should match deps for `useLayoutEffectWithPrevDeps` below\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll('.message-list-item'));\n\n // During animation\n if (!container.offsetParent) {\n return;\n }\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 && (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 }, FOCUSING_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 // If two messages come at once (e.g. via Quiz Bot) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes.\n // To workaround that, we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n const isAtBottom = isViewportNewest && prevIsViewportNewest && (\n scrollOffset - (prevContainerHeight || offsetHeight) - lastItemHeight <= BOTTOM_THRESHOLD\n );\n\n let newScrollTop!: number;\n\n const hasFirstMessageChanged = messageIds && prevMessageIds && messageIds[0] !== prevMessageIds[0];\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n const isAlreadyFocusing = messageIds && memoFocusingIdRef.current === messageIds[messageIds.length - 1];\n\n if (isAtBottom && hasLastMessageChanged && !hasFirstMessageChanged && !isAlreadyFocusing) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n undefined,\n undefined,\n undefined,\n true,\n );\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(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 const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP);\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, newScrollTop);\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(scrollHeight - newScrollTop, offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n // This should match deps for `useOnChange` above\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffect(() => {\n if (!animationLevel || animationLevel > 0) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isChatPrivate(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf);\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n !withUsers && 'no-avatars',\n isChannelChat && 'no-avatars',\n !canPost && 'no-composer',\n type === 'pinned' && 'type-pinned',\n isSelectModeActive && 'select-mode-active',\n hasFocusing && 'has-focusing',\n isScrolled && 'scrolled',\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 ) : messageIds && !messageGroups ? (\n
{lang('NoMessages')}
\n ) : ((messageIds && messageGroups) || lastMessage) ? (\n \n {renderMessages(\n lang,\n messageGroups || groupMessages([lastMessage!]),\n observeIntersectionForReading,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n withUsers,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n threadId,\n type,\n threadTopMessageId,\n threadFirstMessageId,\n hasLinkedChat,\n messageGroups ? type === 'scheduled' : false,\n !messageGroups || !shouldAnimateAppearanceRef.current,\n )}\n \n ) : (\n \n )}\n
\n );\n};\n\nfunction renderMessages(\n lang: LangFn,\n messageGroups: MessageDateGroup[],\n observeIntersectionForReading: ObserveFn,\n observeIntersectionForMedia: ObserveFn,\n observeIntersectionForAnimatedStickers: ObserveFn,\n withUsers: boolean,\n currentAnchorIdRef: { current: string | undefined },\n memoFirstUnreadIdRef: { current: number | undefined },\n threadId: number,\n type: MessageListType,\n threadTopMessageId?: number,\n threadFirstMessageId?: number,\n hasLinkedChat?: boolean,\n isSchedule = false,\n noAppearanceAnimation = false,\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 === memoFirstUnreadIdRef.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 && currentAnchorIdRef.current === `message${message.previousLocalId}`) {\n currentAnchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n message.id === memoFirstUnreadIdRef.current ? unreadDivider : undefined,\n ,\n message.id === threadTopMessageId && (\n
\n {lang('DiscussionStarted')}\n
\n ),\n ]);\n }));\n });\n\n return (\n \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 flatten(dateGroups);\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 let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n const chatBot = selectChatBot(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 isChatWithSelf: selectIsChatWithSelf(global, chatId),\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 animationLevel: global.settings.byKey.animationLevel,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadViewportMessages',\n 'markMessageListRead',\n 'markMessagesRead',\n 'setScrollOffset',\n ]),\n)(MessageList));\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport { pick } from '../../util/iteratees';\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};\n\ntype StateProps = {\n messageListType?: MessageListType;\n unreadCount?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC = ({\n isShown,\n canPost,\n messageListType,\n unreadCount,\n focusLastMessage,\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 focusLastMessage();\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, focusLastMessage]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\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 (setGlobal, actions): DispatchProps => pick(actions, ['focusLastMessage']),\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { preloadImage, preloadVideo, createPosterForVideo } from '../../../../util/files';\n\nconst MAX_QUICK_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\nconst MAX_QUICK_IMG_SIZE = 1280; // px\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 (mimeType.startsWith('image/')) {\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 newBlob = await squeezeImage(img);\n if (newBlob) {\n URL.revokeObjectURL(blobUrl);\n return buildAttachment(filename, newBlob, true, options);\n } else {\n return buildAttachment(filename, blob, false, options);\n }\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (mimeType.startsWith('video/')) {\n // Videos < 10 MB are always sent in quick mode (in other clients).\n // Quick mode for videos > 10 MB is not supported until client-side video squeezing is implemented.\n if (size < MAX_QUICK_VIDEO_SIZE) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n }\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\nfunction squeezeImage(img: HTMLImageElement): Promise {\n return new Promise((resolve) => {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n let { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE) {\n if (width >= height) {\n height *= MAX_QUICK_IMG_SIZE / width;\n width = MAX_QUICK_IMG_SIZE;\n } else {\n width *= MAX_QUICK_IMG_SIZE / height;\n height = MAX_QUICK_IMG_SIZE;\n }\n }\n\n canvas.width = width;\n canvas.height = height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);\n canvas.toBlob(resolve, 'image/jpeg', 100);\n });\n}\n","export default __webpack_public_path__ + \"8ccc0b555efcec3616377aea078dda16.js\";","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface OpusRecorder extends Omit {\n new(options: AnyLiteral): OpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: OpusRecorder }>;\nlet OpusRecorder: OpusRecorder;\nlet mediaRecorder: OpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: OpusRecorder, 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';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string, inputId?: string) => void,\n setAttachments: StateHookSetter,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && input.tagName === 'INPUT' && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items).find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type));\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n if (!file && !pastedText) {\n return;\n }\n\n e.preventDefault();\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText, input ? input.id : undefined);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\n}\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/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 '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: number | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: number,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n saveDraft: GlobalActions['saveDraft'],\n clearDraft: GlobalActions['clearDraft'],\n) => {\n const updateDraft = useCallback((draftChatId: number, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n // Subscribe and handle `window.blur`\n useEffect(() => {\n function handleBlur() {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }\n\n window.addEventListener('blur', handleBlur);\n\n return () => {\n window.removeEventListener('blur', handleBlur);\n };\n }, [chatId, threadId, updateDraft]);\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? : undefined;\n};\n\nexport default memo(DeleteMessageModalAsync);\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n \n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? : undefined;\n};\n\nexport default memo(AttachMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? : undefined;\n};\n\nexport default memo(SymbolMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const MentionTooltip = useModuleLoader(Bundles.Extra, 'MentionTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionTooltip ? : undefined;\n};\n\nexport default memo(MentionTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? : undefined;\n};\n\nexport default memo(CustomSendMenuAsync);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './StickerTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst StickerTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const StickerTooltip = useModuleLoader(Bundles.Extra, 'StickerTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerTooltip ? : undefined;\n};\n\nexport default StickerTooltipAsync;\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotKeyboardMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotKeyboardMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const BotKeyboardMenu = useModuleLoader(Bundles.Extra, 'BotKeyboardMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotKeyboardMenu ? : undefined;\n};\n\nexport default memo(BotKeyboardMenuAsync);\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport { pick } from '../../../util/iteratees';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isChatPrivate } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n}) => {\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isChatPrivate(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 (setGlobal, actions): DispatchProps => pick(actions, [\n 'setReplyingToId',\n 'setEditingId',\n 'focusMessage',\n 'exitForwardMode',\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 './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? : undefined;\n};\n\nexport default memo(PollModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? : undefined;\n};\n\nexport default memo(DropAreaAsync);\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage } from '../../../modules/selectors';\nimport { pick } from '../../../util/iteratees';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../../util/buildClassName';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageText: string;\n disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n};\ntype DispatchProps = Pick;\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC = ({\n chatId,\n threadId,\n messageText,\n disabled,\n webPagePreview,\n noWebPage,\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n}) => {\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = useCurrentOrPrev(webPagePreview);\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 webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadWebPagePreview', 'clearWebPagePreview', 'toggleMessageWebPage',\n ]),\n)(WebPagePreview));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? : undefined;\n};\n\nexport default memo(CalendarModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './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, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../../api/types';\nimport { LangCode } from '../../../types';\n\nimport { EDITABLE_INPUT_ID, SCHEDULED_WHEN_ONLINE } from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_MOBILE_SCREEN, IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport {\n selectChat,\n selectIsChatWithBot,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatUser,\n selectEmojiKeywords,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isChatGroup,\n isChatPrivate,\n isChatAdmin,\n} from '../../../modules/helpers';\nimport { formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from './helpers/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport { isSelectionInsideInput } from './helpers/selection';\n\nimport useFlag from '../../../hooks/useFlag';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useStickerTooltip from './hooks/useStickerTooltip';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport MentionTooltip from './MentionTooltip.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport StickerTooltip from './StickerTooltip.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu.async';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\nimport PaymentModal from '../../payment/PaymentModal.async';\nimport ReceiptModal from '../../payment/ReceiptModal.async';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: number;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps = {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n canSuggestMembers?: boolean;\n isPollModalOpen?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n botKeyboardMessageId?: number;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: number;\n usersById?: Record;\n recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n language: LangCode;\n emojiKeywords?: Record;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst 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 onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n canSuggestMembers,\n isPollModalOpen,\n isPaymentModalOpen,\n isReceiptModalOpen,\n botKeyboardMessageId,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n language,\n emojiKeywords,\n recentEmojis,\n sendMessage,\n editMessage,\n saveDraft,\n clearDraft,\n showError,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n closePaymentModal,\n openChat,\n clearReceipt,\n addRecentEmoji,\n loadEmojiKeywords,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n const [html, setHtml] = useState('');\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState();\n\n // Cache for frequently updated state\n const htmlRef = useRef(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID) {\n loadScheduledHistory();\n }\n }, [chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) {\n return;\n }\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = 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 const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, mentionFilter,\n closeMentionTooltip, insertMention,\n mentionFilteredMembers,\n } = useMentionTooltip(\n canSuggestMembers && !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n currentUserId,\n usersById,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n recentEmojis,\n undefined,\n setHtml,\n emojiKeywords,\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)) {\n if (IS_EMOJI_SUPPORTED) {\n // Insertion will trigger `onChange` in MessageInput, so no need to setHtml in state\n document.execCommand('insertText', false, text);\n } else {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n }\n return;\n }\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n if (!IS_MOBILE_SCREEN) {\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback(() => {\n setHtml('');\n setAttachments([]);\n closeStickerTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionTooltip();\n closeEmojiTooltip();\n\n if (IS_MOBILE_SCREEN) {\n // @perf\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeStickerTooltip, closeCalendar, closeMentionTooltip, closeEmojiTooltip, closeSymbolMenu]);\n\n // Handle chat change\n const prevChatId = usePrevious(chatId);\n useEffect(() => {\n if (!prevChatId || chatId === prevChatId) {\n return;\n }\n\n stopRecordingVoice();\n resetComposer();\n }, [chatId, prevChatId, resetComposer, stopRecordingVoice]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal, editMessage);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage, saveDraft, clearDraft);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleAppendFiles = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments([\n ...attachments,\n ...await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))),\n ]);\n }, [attachments]);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n if (currentAttachments.length && text && text.length > CAPTION_MAX_LENGTH) {\n const extraLength = text.length - CAPTION_MAX_LENGTH;\n showError({\n error: {\n message: 'CAPTION_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n },\n });\n return;\n }\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = Math.floor(Date.now() / 1000);\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 showError({\n error: {\n message: `A wait of ${secondsRemaining} seconds is required before sending another message in this chat`,\n isSlowMode: true,\n },\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\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 if (isForwarding) {\n forwardMessages();\n }\n\n lastMessageSendTimeSeconds.current = Math.floor(Date.now() / 1000);\n\n clearDraft({ chatId, localOnly: true });\n\n // Wait until message animation starts\n requestAnimationFrame(resetComposer);\n }, [\n activeVoiceRecording, attachments, connectionState, chatId, slowMode, isForwarding, isAdmin,\n sendMessage, stopRecordingVoice, resetComposer, clearDraft, showError, forwardMessages,\n ]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(resetComposer);\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(resetComposer);\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000));\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_MOBILE_SCREEN || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_MOBILE_SCREEN) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n handleSend();\n requestAnimationFrame(resetComposer);\n }\n break;\n case MainButtonState.Record:\n startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, resetComposer, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const lang = useLang();\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'SendMessage';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Conversation.DefaultRestrictedMedia'\n : 'AccDescrVoiceMessage';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n return (\n
\n {allowedAttachmentOptions.canAttachMedia && (\n \n \n \n )}\n \n \n \n \n {renderedEditedMessage && (\n \n )}\n \n
\n
\n \n \n
\n {IS_MOBILE_SCREEN ? (\n \n \n \n \n \n ) : (\n \n \n \n )}\n \n {withScheduledButton && (\n \n \n \n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {activeVoiceRecording && currentRecordTime && (\n \n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n \n )}\n \n \n \n {botKeyboardMessageId && (\n \n )}\n \n
\n
\n {activeVoiceRecording && (\n \n \n \n )}\n \n \n \n \n \n {canShowCustomSendMenu && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const isChatWithBot = chat ? selectIsChatWithBot(global, chat) : undefined;\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n const { language } = global.settings.byKey;\n const emojiKeywords = selectEmojiKeywords(global, language);\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: (\n !isChatWithSelf && !isChatWithBot\n && (chat && chatUser && isChatPrivate(chatId) && chatUser.status && Boolean(chatUser.status.wasOnline))\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds && scheduledIds.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId: messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined,\n isForwarding: chatId === global.forwardMessages.toChatId,\n canSuggestMembers: chat && isChatGroup(chat),\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat && chat.fullInfo && chat.fullInfo.members,\n currentUserId: global.currentUserId,\n usersById: global.users.byId,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n shouldSuggestStickers: global.settings.byKey.shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n language,\n emojiKeywords: emojiKeywords ? emojiKeywords.keywords : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'sendMessage',\n 'editMessage',\n 'saveDraft',\n 'clearDraft',\n 'showError',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'forwardMessages',\n 'openPollModal',\n 'closePollModal',\n 'closePaymentModal',\n 'clearReceipt',\n 'loadScheduledHistory',\n 'openChat',\n 'addRecentEmoji',\n 'loadEmojiKeywords',\n ]),\n)(Composer));\n","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_IOS } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState();\n const startRecordTimeRef = useRef();\n const [currentRecordTime, setCurrentRecordTime] = useState();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_IOS) {\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\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\n\nexport default function useStickerTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n) {\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(html) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({ emoji: html });\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]);\n\n return {\n isStickerTooltipOpen: hasStickers,\n closeStickerTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection && 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 selection.removeAllRanges();\n selection.addRange(range);\n }\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';\n\nimport { ApiMessage } from '../../../../api/types';\nimport { GlobalActions } from '../../../../global/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../helpers/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n editMessage: GlobalActions['editMessage'],\n) => {\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? : undefined;\n};\n\nexport default memo(MobileSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? : undefined;\n};\n\nexport default memo(MessageSelectToolbarAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? : undefined;\n};\n\nexport default memo(UnpinAllMessagesModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalActions, MessageListType } 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 CONTENT_TYPES_FOR_QUICK_UPLOAD,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n DARK_THEME_BG_COLOR,\n LIGHT_THEME_BG_COLOR,\n} from '../../config';\nimport { IS_MOBILE_SCREEN, IS_TOUCH_ENV, MASK_IMAGE_DISABLED } from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectPinnedIds,\n} from '../../modules/selectors';\nimport { getCanPostInChat, getMessageSendingRestrictionReason, isChatPrivate } from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevDuringAnimation from '../../hooks/usePrevDuringAnimation';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\nimport useLang from '../../hooks/useLang';\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';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: number;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n canPost?: boolean;\n messageSendingRestrictionReason?: string;\n hasPinnedOrAudioMessage?: boolean;\n pinnedMessagesCount?: number;\n theme: ThemeKey;\n customBackground?: string;\n backgroundColor?: string;\n patternColor?: string;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst CLOSE_ANIMATION_DURATION = IS_MOBILE_SCREEN ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction canBeQuicklyUploaded(item: DataTransferItem) {\n return item.kind === 'file' && item.type && CONTENT_TYPES_FOR_QUICK_UPLOAD.includes(item.type);\n}\n\nconst MiddleColumn: FC = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n canPost,\n messageSendingRestrictionReason,\n hasPinnedOrAudioMessage,\n pinnedMessagesCount,\n customBackground,\n theme,\n backgroundColor,\n patternColor,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n animationLevel,\n openChat,\n unpinAllMessages,\n loadUser,\n}) => {\n const { width: windowWidth } = useWindowSize();\n\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 = hasPinnedOrAudioMessage && (\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 renderingCanPost = usePrevDuringAnimation(canPost, CLOSE_ANIMATION_DURATION);\n const renderingHasTools = usePrevDuringAnimation(hasTools, CLOSE_ANIMATION_DURATION);\n const renderingIsFabShown = usePrevDuringAnimation(isFabShown, CLOSE_ANIMATION_DURATION);\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useEffect(() => {\n setDropAreaState(DropAreaState.None);\n setIsFabShown(undefined);\n setIsNotchShown(undefined);\n }, [chatId]);\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items).every(canBeQuicklyUploaded);\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 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 // 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 lang = useLang();\n\n const footerClassName = buildClassName(\n 'middle-column-footer',\n !renderingCanPost && 'no-composer',\n renderingCanPost && isNotchShown && !isSelectModeActive && 'with-notch',\n );\n\n return (\n \n \n
\n {renderingChatId && renderingThreadId && (\n <>\n
\n \n \n {() => (\n <>\n \n
\n {renderingCanPost && (\n \n )}\n {isPinnedMessageList && (\n
\n \n \n {lang('Chat.Pinned.UnpinAll', pinnedMessagesCount, 'i')}\n \n
\n )}\n {!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason && (\n
\n
\n \n {messageSendingRestrictionReason}\n \n
\n
\n )}\n \n
\n \n )}\n \n\n \n
\n {IS_MOBILE_SCREEN && }\n \n )}\n {chatId && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { theme } = global.settings.byKey;\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const currentMessageList = selectCurrentMessageList(global);\n const { chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_MOBILE_SCREEN && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n animationLevel: global.settings.byKey.animationLevel,\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const 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\n return {\n ...state,\n chatId,\n threadId,\n messageListType,\n isPrivate: isChatPrivate(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && (!isBotNotStarted || IS_MOBILE_SCREEN),\n isPinnedMessageList,\n messageSendingRestrictionReason: chat && getMessageSendingRestrictionReason(chat),\n hasPinnedOrAudioMessage: (\n threadId !== MAIN_THREAD_ID\n || Boolean(pinnedIds && pinnedIds.length)\n || Boolean(audioChatId && audioMessageId)\n ),\n pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openChat', 'unpinAllMessages', 'loadUser',\n ]),\n)(MiddleColumn));\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { ThemeKey } from '../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { preloadImage } from '../util/files';\n\nexport default (theme: ThemeKey, settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, theme, cacheApi.Type.Blob)\n .then((blob) => {\n const url = URL.createObjectURL(blob);\n preloadImage(url)\n .then(() => {\n setValue(`url(${url})`);\n });\n });\n }\n }, [settingValue, theme]);\n\n return settingValue ? value : undefined;\n};\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n} from '../../modules/selectors';\nimport { isChatAdmin, isChatChannel, isChatPrivate } from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport CalendarModal from '../common/CalendarModal.async';\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\n\ntype OwnProps = {\n chatId?: number;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canManage?: boolean;\n isChannel?: boolean;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupMembers,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nconst RightHeader: FC = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n profileState,\n managementScreen,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n searchMessagesByDate,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\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 handleJumpToDate = useCallback((date: Date) => {\n searchMessagesByDate({ timestamp: date.valueOf() / 1000 });\n closeCalendar();\n }, [closeCalendar, searchMessagesByDate]);\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 [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 ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : undefined // Never reached\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n \n \n \n \n );\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.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

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

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

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

{lang('GroupMembers')}

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

Profile

\n
\n {canManage && (\n \n \n \n )}\n
\n \n );\n }\n }\n\n const isBackButton = (\n IS_MOBILE_SCREEN\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n shouldSkipTransition && 'no-transition',\n );\n\n // Add class in the next AF to synchronize with animation with Transition components\n useEffect(() => {\n backButtonRef.current!.classList.toggle('state-back', isBackButton);\n }, [isBackButton]);\n\n return (\n
\n \n
\n \n \n {renderHeaderContent}\n \n {!IS_MOBILE_SCREEN && (\n \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\n const canManage = Boolean(\n !isManagement\n && isProfile\n && chat\n && !selectIsChatWithSelf(global, chat.id)\n // chat.isCreator is for Basic Groups\n && (isChatPrivate(chat.id) || ((isChatAdmin(chat) || chat.isCreator) && !chat.isNotJoined)),\n );\n\n return {\n canManage,\n isChannel,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalTextSearchQuery',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'searchTextMessagesLocal',\n 'toggleManagement',\n 'searchMessagesByDate',\n ]),\n)(RightHeader));\n","import { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport { ApiChatMember, ApiMessage, ApiUser } from '../../../api/types';\nimport { ProfileTabType, SharedMediaType } from '../../../types';\n\nimport { MEMBERS_SLICE, MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, sortUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n loadMoreMembers: AnyToVoidFunction,\n searchMessages: AnyToVoidFunction,\n tabType: ProfileTabType,\n mediaSearchType?: SharedMediaType,\n groupChatMembers?: ApiChatMember[],\n usersById?: Record,\n chatMessages?: Record,\n foundIds?: number[],\n chatId?: number,\n lastSyncTime?: number,\n) {\n const resultType = tabType === 'members' || !mediaSearchType ? tabType : mediaSearchType;\n\n const memberIds = useMemo(() => {\n if (!groupChatMembers || !usersById) {\n return undefined;\n }\n\n return sortUserIds(groupChatMembers.map(({ userId }) => userId), usersById);\n }, [groupChatMembers, usersById]);\n\n const [memberViewportIds, getMoreMembers, noProfileInfoForMembers] = useInfiniteScrollForMembers(\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 let viewportIds: number[] | 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 '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 }\n\n return [resultType, viewportIds, getMore, noProfileInfo] as const;\n}\n\nfunction useInfiniteScrollForMembers(\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n memberIds?: number[],\n) {\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n memberIds,\n undefined,\n MEMBERS_SLICE,\n );\n\n const isOnTop = !viewportIds || !memberIds || viewportIds[0] === memberIds[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n\nfunction useInfiniteScrollForSharedMedia(\n forSharedMediaType: SharedMediaType,\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n chatMessages?: Record,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef();\n\n useOnChange(() => {\n if (currentResultType === forSharedMediaType && chatMessages && foundIds) {\n messageIdsRef.current = getMessageContentIds(\n chatMessages,\n foundIds,\n forSharedMediaType,\n ).reverse();\n }\n }, [chatMessages, foundIds, currentResultType, forSharedMediaType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n messageIdsRef.current,\n undefined,\n forSharedMediaType === 'media' ? SHARED_MEDIA_SLICE : MESSAGE_SEARCH_SLICE,\n );\n\n const isOnTop = !viewportIds || !messageIdsRef.current || viewportIds[0] === messageIdsRef.current[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ProfileState } from '../../../types';\n\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport { throttle } from '../../../util/schedulers';\nimport useEffectWithPrevDeps from '../../../hooks/useEffectWithPrevDeps';\n\nconst TRANSITION_DURATION = 300;\nconst PROGRAMMATIC_SCROLL_TIMEOUT_MS = 350;\n\nconst runThrottledForScroll = throttle((cb) => cb(), 250, false);\n\nlet isScrollingProgrammatically = false;\n\nexport default function useProfileState(\n containerRef: { current: HTMLDivElement | null },\n tabType: string,\n profileState: ProfileState,\n onProfileStateChange: (state: ProfileState) => void,\n) {\n // Scroll to tabs if needed\n useEffectWithPrevDeps(([prevTabType]) => {\n if (prevTabType && prevTabType !== tabType) {\n const container = containerRef.current!;\n const tabsEl = container.querySelector('.TabList')!;\n if (container.scrollTop < tabsEl.offsetTop) {\n onProfileStateChange(tabType === 'members' ? ProfileState.MemberList : ProfileState.SharedMedia);\n isScrollingProgrammatically = true;\n fastSmoothScroll(container, tabsEl, 'start', undefined, undefined, undefined, TRANSITION_DURATION);\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n }\n }\n }, [tabType, onProfileStateChange]);\n\n // Scroll to top\n useEffectWithPrevDeps(([prevProfileState]) => {\n if (profileState !== ProfileState.Profile || profileState === prevProfileState) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl || tabListEl.offsetTop > container.scrollTop) {\n return;\n }\n\n isScrollingProgrammatically = true;\n fastSmoothScroll(\n container,\n container.firstElementChild as HTMLElement,\n 'start',\n undefined,\n container.offsetHeight * 2,\n );\n\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n\n onProfileStateChange(profileState);\n }, [profileState]);\n\n const determineProfileState = useCallback(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl) {\n return;\n }\n\n let state: ProfileState = ProfileState.Profile;\n if (container.scrollTop >= tabListEl.offsetTop) {\n state = tabType === 'members'\n ? ProfileState.MemberList\n : ProfileState.SharedMedia;\n }\n\n onProfileStateChange(state);\n }, [containerRef, onProfileStateChange, tabType]);\n\n // Determine profile state when switching tabs\n useEffect(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n determineProfileState();\n }, [determineProfileState, tabType]);\n\n // Determine profile state when scrolling\n const handleScroll = useCallback(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n runThrottledForScroll(determineProfileState);\n }, [determineProfileState]);\n\n return { handleScroll };\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport {\n ApiUser, ApiChat, ApiMediaFormat, ApiPhoto,\n} from '../../api/types';\n\nimport {\n getChatAvatarHash, isDeletedUser, getUserColorKey, getChatTitle, isChatPrivate, getUserFullName,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport buildClassName from '../../util/buildClassName';\nimport { getFirstLetters } from '../../util/textFormat';\nimport useMedia from '../../hooks/useMedia';\nimport useBlurSync from '../../hooks/useBlurSync';\nimport usePrevious from '../../hooks/usePrevious';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ProfilePhoto.scss';\n\ntype OwnProps = {\n chat?: ApiChat;\n user?: ApiUser;\n isFirstPhoto?: boolean;\n isSavedMessages?: boolean;\n photo?: ApiPhoto;\n lastSyncTime?: number;\n onClick: NoneToVoidFunction;\n};\n\nconst ProfilePhoto: FC = ({\n chat,\n user,\n photo,\n isFirstPhoto,\n isSavedMessages,\n lastSyncTime,\n onClick,\n}) => {\n const lang = useLang();\n const isDeleted = user && isDeletedUser(user);\n\n function getMediaHash(size: 'normal' | 'big' = 'big', forceAvatar?: boolean) {\n if (photo && !forceAvatar) {\n return `photo${photo.id}?size=c`;\n }\n\n let hash: string | undefined;\n if (!isSavedMessages && !isDeleted) {\n if (user) {\n hash = getChatAvatarHash(user, size);\n } else if (chat) {\n hash = getChatAvatarHash(chat, size);\n }\n }\n\n return hash;\n }\n\n const imageHash = getMediaHash();\n const fullMediaData = useMedia(imageHash, false, ApiMediaFormat.BlobUrl, lastSyncTime);\n const avatarThumbnailData = useMedia(\n !fullMediaData && isFirstPhoto ? getMediaHash('normal', true) : undefined,\n false,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n const thumbDataUri = useBlurSync(!fullMediaData && photo && photo.thumbnail && photo.thumbnail.dataUri);\n const imageSrc = fullMediaData || avatarThumbnailData || thumbDataUri;\n const prevImageSrc = usePrevious(imageSrc);\n\n let content: string | undefined = '';\n\n if (isSavedMessages) {\n content = ;\n } else if (isDeleted) {\n content = ;\n } else if (imageSrc) {\n content = \"\";\n } else if (!imageSrc && user) {\n const userFullName = getUserFullName(user);\n content = userFullName ? getFirstLetters(userFullName, 2) : undefined;\n } else if (!imageSrc && chat) {\n const title = getChatTitle(lang, chat);\n content = title && getFirstLetters(title, isChatPrivate(chat.id) ? 2 : 1);\n } else {\n content = (\n
\n \n
\n );\n }\n\n const fullClassName = buildClassName(\n 'ProfilePhoto',\n `color-bg-${getUserColorKey(user || chat)}`,\n isSavedMessages && 'saved-messages',\n isDeleted && 'deleted-account',\n (!isSavedMessages && !(imageSrc)) && 'no-photo',\n );\n\n return (\n
\n {prevImageSrc && imageSrc && prevImageSrc !== imageSrc && (\n \"\"\n )}\n {typeof content === 'string' ? renderText(content, ['hq_emoji']) : content}\n
\n );\n};\n\nexport default memo(ProfilePhoto);\n","import React, {\n FC, useEffect, useCallback, memo, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiChat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { MediaViewerOrigin } from '../../types';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getUserFullName, getUserStatus, isChatChannel, isUserOnline,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport usePhotosPreload from './hooks/usePhotosPreload';\nimport useLang from '../../hooks/useLang';\n\nimport VerifiedIcon from '../common/VerifiedIcon';\nimport ProfilePhoto from './ProfilePhoto';\nimport Transition from '../ui/Transition';\n\nimport './ProfileInfo.scss';\n\ntype OwnProps = {\n userId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n isSavedMessages?: boolean;\n animationLevel: 0 | 1 | 2;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst PrivateChatInfo: FC = ({\n user,\n chat,\n isSavedMessages,\n lastSyncTime,\n animationLevel,\n loadFullUser,\n openMediaViewer,\n}) => {\n const { id: userId } = user || {};\n const { id: chatId } = chat || {};\n const fullName = user ? getUserFullName(user) : (chat ? chat.title : '');\n const photos = (user ? user.photos : (chat ? chat.photos : undefined)) || [];\n const slideAnimation = animationLevel >= 1 ? 'slide' : 'none';\n\n const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);\n const isFirst = isSavedMessages || photos.length <= 1 || currentPhotoIndex === 0;\n const isLast = isSavedMessages || photos.length <= 1 || currentPhotoIndex === photos.length - 1;\n\n // Deleting the last profile photo may result in an error\n useEffect(() => {\n if (currentPhotoIndex > photos.length) {\n setCurrentPhotoIndex(Math.max(0, photos.length - 1));\n }\n }, [currentPhotoIndex, photos.length]);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [userId, loadFullUser, lastSyncTime]);\n\n usePhotosPreload(user || chat, photos, currentPhotoIndex);\n\n const handleProfilePhotoClick = useCallback(() => {\n openMediaViewer({\n avatarOwnerId: userId || chatId,\n profilePhotoIndex: currentPhotoIndex,\n origin: MediaViewerOrigin.ProfileAvatar,\n });\n }, [openMediaViewer, userId, chatId, currentPhotoIndex]);\n\n const selectPreviousMedia = useCallback(() => {\n if (isFirst) {\n return;\n }\n\n setCurrentPhotoIndex(currentPhotoIndex - 1);\n }, [currentPhotoIndex, isFirst]);\n\n const selectNextMedia = useCallback(() => {\n if (isLast) {\n return;\n }\n\n setCurrentPhotoIndex(currentPhotoIndex + 1);\n }, [currentPhotoIndex, isLast]);\n\n // Support for swipe gestures and closing on click\n useEffect(() => {\n const element = document.querySelector(\n '.profile-slide-container > .active, .profile-slide-container > .to',\n );\n if (!element) {\n return undefined;\n }\n\n return captureEvents(element, {\n excludedClosestSelector: '.navigation',\n onSwipe: IS_TOUCH_ENV ? (e, direction) => {\n if (direction === SwipeDirection.Right) {\n selectPreviousMedia();\n } else if (direction === SwipeDirection.Left) {\n selectNextMedia();\n }\n } : undefined,\n });\n }, [selectNextMedia, selectPreviousMedia]);\n\n if (!user && !chat) {\n return undefined;\n }\n\n function renderPhotoTabs() {\n if (isSavedMessages || !photos || photos.length <= 1) {\n return undefined;\n }\n\n return (\n
\n {photos.map((_, i) => (\n \n ))}\n
\n );\n }\n\n function renderPhoto() {\n const photo = !isSavedMessages && photos && photos.length > 0 ? photos[currentPhotoIndex] : undefined;\n\n return (\n \n );\n }\n\n function renderStatus() {\n if (user) {\n return (\n
\n {getUserStatus(lang, user)}\n
\n );\n }\n\n return (\n {\n isChatChannel(chat!)\n ? lang('Subscribers', chat!.membersCount, 'i')\n : lang('Members', chat!.membersCount, 'i')\n }\n \n );\n }\n\n const isVerifiedIconShown = (user && user.isVerified) || (chat && chat.isVerified);\n\n return (\n
\n
\n {renderPhotoTabs()}\n \n {renderPhoto}\n \n\n {!isFirst && (\n \n )}\n {!isLast && (\n \n )}\n
\n\n
\n {isSavedMessages ? (\n
\n

{lang('SavedMessages')}

\n
\n ) : (\n
\n

{fullName && renderText(fullName)}

\n {isVerifiedIconShown && }\n
\n )}\n {!isSavedMessages && renderStatus()}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId, forceShowSelf }): StateProps => {\n const { lastSyncTime } = global;\n const user = selectUser(global, userId);\n const chat = selectChat(global, userId);\n const isSavedMessages = !forceShowSelf && user && user.isSelf;\n const { animationLevel } = global.settings.byKey;\n\n return {\n lastSyncTime, user, chat, isSavedMessages, animationLevel,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadFullUser', 'openMediaViewer']),\n)(PrivateChatInfo));\n","import {\n ApiChat, ApiMediaFormat, ApiPhoto, ApiUser,\n} from '../../../api/types';\nimport { useEffect } from '../../../lib/teact/teact';\nimport * as mediaLoader from '../../../util/mediaLoader';\n\nconst PHOTOS_TO_PRELOAD = 4;\n\nexport default function usePhotosPreload(\n profile: ApiUser | ApiChat | undefined,\n photos: ApiPhoto[],\n currentIndex: number,\n) {\n useEffect(() => {\n photos.slice(currentIndex, currentIndex + PHOTOS_TO_PRELOAD).forEach((photo) => {\n const mediaData = mediaLoader.getFromMemory(`photo${photo.id}?size=c`);\n if (!mediaData) {\n mediaLoader.fetch(`photo${photo.id}?size=c`, ApiMediaFormat.BlobUrl);\n }\n });\n }, [currentIndex, photos]);\n}\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { selectChat, selectUser } from '../../modules/selectors';\nimport {\n getChatDescription, getChatLink, getHasAdminRight, isChatChannel, isChatPrivate, isUserRightBanned,\n} from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport { pick } from '../../util/iteratees';\nimport { copyTextToClipboard } from '../../util/clipboard';\nimport { formatPhoneNumberWithCode } from '../../util/phoneNumber';\nimport useLang from '../../hooks/useLang';\n\nimport SafeLink from '../common/SafeLink';\nimport ListItem from '../ui/ListItem';\nimport Switcher from '../ui/Switcher';\n\ntype OwnProps = {\n chatOrUserId: number;\n forceShowSelf?: boolean;\n};\n\ntype StateProps = {\n user?: ApiUser;\n chat?: ApiChat;\n canInviteUsers?: boolean;\n} & Pick;\n\ntype DispatchProps = Pick;\n\nconst ChatExtra: FC = ({\n lastSyncTime,\n user,\n chat,\n forceShowSelf,\n canInviteUsers,\n loadFullUser,\n showNotification,\n updateChatMutedState,\n}) => {\n const {\n id: userId,\n fullInfo,\n username,\n phoneNumber,\n isSelf,\n } = user || {};\n const {\n id: chatId,\n isMuted: currentIsMuted,\n username: chatUsername,\n } = chat || {};\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime && userId) {\n loadFullUser({ userId });\n }\n }, [loadFullUser, userId, lastSyncTime]);\n\n const handleNotificationChange = useCallback(() => {\n updateChatMutedState({ chatId, isMuted: !currentIsMuted });\n }, [chatId, currentIsMuted, updateChatMutedState]);\n\n if (!chat || chat.isRestricted || (isSelf && !forceShowSelf)) {\n return undefined;\n }\n\n function copy(text: string, entity: string) {\n copyTextToClipboard(text);\n showNotification({ message: `${entity} was copied` });\n }\n\n const formattedNumber = phoneNumber && formatPhoneNumberWithCode(phoneNumber);\n const link = getChatLink(chat);\n const url = link.indexOf('http') === 0 ? link : `http://${link}`;\n const printedUsername = username || chatUsername;\n const description = (fullInfo && fullInfo.bio) || getChatDescription(chat);\n\n return (\n
\n {formattedNumber && !!formattedNumber.length && (\n copy(formattedNumber, lang('Phone'))}>\n {formattedNumber}\n {lang('Phone')}\n \n )}\n {printedUsername && (\n copy(`@${printedUsername}`, lang('Username'))}\n >\n {renderText(printedUsername)}\n {lang('Username')}\n \n )}\n {description && !!description.length && (\n \n \n {renderText(description, ['br', 'links', 'emoji'])}\n \n {lang(userId ? 'UserBio' : 'Info')}\n \n )}\n {canInviteUsers && !printedUsername && !!link.length && (\n copy(link, lang('SetUrlPlaceholder'))}>\n
\n \n
\n {lang('SetUrlPlaceholder')}\n
\n )}\n \n {lang('Notifications')}\n \n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatOrUserId }): StateProps => {\n const { lastSyncTime } = global;\n\n const chat = chatOrUserId ? selectChat(global, chatOrUserId) : undefined;\n const user = isChatPrivate(chatOrUserId) ? selectUser(global, chatOrUserId) : undefined;\n\n const canInviteUsers = chat && (\n (!isChatChannel(chat) && !isUserRightBanned(chat, 'inviteUsers'))\n || getHasAdminRight(chat, 'inviteUsers')\n );\n\n return {\n lastSyncTime, chat, user, canInviteUsers,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'loadFullUser', 'updateChatMutedState', 'showNotification',\n ]),\n)(ChatExtra));\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { GlobalActions } from '../../global/types';\nimport {\n MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType,\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 isChatAdmin, isChatChannel, isChatGroup, isChatPrivate,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { pick } from '../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\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 './ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from './ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: number;\n userId?: number;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n isChannel?: boolean;\n resolvedUserId?: number;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n members?: ApiChatMember[];\n usersById?: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC = ({\n chatId,\n profileState,\n onProfileStateChange,\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n members,\n usersById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n setLocalMediaSearchType,\n loadMoreMembers,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\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\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ]), [hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n usersById, chatMessages, foundIds, chatId, lastSyncTime,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n // 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: number) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n }\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n
\n {!noSpinner && }\n
\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'documents':\n text = lang('lng_media_file_empty_search');\n break;\n case 'links':\n text = lang('lng_media_link_empty_search');\n break;\n case 'audio':\n text = lang('lng_media_song_empty_search');\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!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n viewportIds!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n viewportIds!.map((id, i) => (\n handleMemberClick(id)}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n
\n \n {renderSharedMedia}\n \n \n
\n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: number, resolvedUserId?: number) {\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 > div.active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById } = global.users;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat && chat.fullInfo && chat.fullInfo.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n\n let resolvedUserId;\n if (userId) {\n resolvedUserId = userId;\n } else if (isChatPrivate(chatId)) {\n resolvedUserId = chatId;\n }\n\n return {\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasMembersTab,\n areMembersHidden,\n ...(hasMembersTab && members && {\n members,\n usersById,\n }),\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat && chat.isRestricted,\n lastSyncTime: global.lastSyncTime,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setLocalMediaSearchType',\n 'loadMoreMembers',\n 'searchMediaMessagesLocal',\n 'openMediaViewer',\n 'openAudioPlayer',\n 'openUserInfo',\n 'focusMessage',\n 'loadProfilePhotos',\n ]),\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector(transitionElSelector);\n const tabsEl = container.querySelector('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\n};\n\nexport default memo(RightSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\n};\n\nexport default memo(ManagementAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? : ;\n};\n\nexport default memo(StickerSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? : ;\n};\n\nexport default memo(GifSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? : ;\n};\n\nexport default memo(PollResultsAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ManagementScreens, ProfileState, RightColumnContent } from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport { pick } from '../../util/iteratees';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: number;\n threadId?: number;\n currentProfileUserId?: number;\n isChatSelected: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n}) => {\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const 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(() => {\n switch (contentKey) {\n case RightColumnContent.ChatInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo();\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n // eslint-disable-next-line consistent-return\n function renderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'openUserInfo',\n 'toggleChatInfo',\n 'toggleManagement',\n 'closeLocalTextSearch',\n 'setStickerSearchQuery',\n 'setGifSearchQuery',\n 'closePollResults',\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","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 ErrorsAsync: FC = ({ isOpen }) => {\n const Errors = useModuleLoader(Bundles.Extra, 'Errors', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Errors ? : undefined;\n};\n\nexport default memo(ErrorsAsync);\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, useEffect, memo } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n ANIMATION_END_DELAY, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport { pick } from '../../util/iteratees';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport Notifications from './Notifications.async';\nimport Errors from './Errors.async';\nimport ForwardPicker from './ForwardPicker.async';\nimport SafeLinkModal from './SafeLinkModal.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n animationLevel: number;\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasErrors: boolean;\n audioMessage?: ApiMessage;\n safeLinkModalUrl?: string;\n};\n\ntype DispatchProps = Pick;\n\nconst ANIMATION_DURATION = 350;\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet rightColumnAnimationTimeout: number | undefined;\nlet notificationInterval: number | undefined;\n\nlet DEBUG_isLogged = false;\n\nconst Main: FC = ({\n lastSyncTime,\n loadAnimatedEmojis,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n animationLevel,\n hasNotifications,\n hasErrors,\n audioMessage,\n safeLinkModalUrl,\n}) => {\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n loadAnimatedEmojis();\n }\n }, [lastSyncTime, loadAnimatedEmojis]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n );\n\n useEffect(() => {\n // For animating Symbol Menu on mobile\n document.body.classList.toggle('is-middle-column-open', className.includes('middle-column-open'));\n // For animating components in portals (i.e. Notification)\n document.body.classList.toggle('is-right-column-shown', className.includes('right-column-open'));\n }, [className]);\n\n // Add `body` classes when toggling right column\n useEffect(() => {\n if (animationLevel > 0) {\n document.body.classList.add('animating-right-column');\n dispatchHeavyAnimationEvent(ANIMATION_DURATION + ANIMATION_END_DELAY);\n\n if (rightColumnAnimationTimeout) {\n clearTimeout(rightColumnAnimationTimeout);\n rightColumnAnimationTimeout = undefined;\n }\n\n rightColumnAnimationTimeout = window.setTimeout(() => {\n document.body.classList.remove('animating-right-column');\n rightColumnAnimationTimeout = undefined;\n }, ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [animationLevel, isRightColumnShown]);\n\n useBackgroundMode(() => {\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n document.title = `${newUnread} notification${newUnread > 1 ? 's' : ''}`;\n updateIcon(true);\n }\n } else {\n document.title = PAGE_TITLE;\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, () => {\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n document.title = PAGE_TITLE;\n }\n\n updateIcon(false);\n });\n\n function stopEvent(e: React.MouseEvent) {\n e.preventDefault();\n e.stopPropagation();\n }\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n \n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('link[rel=\"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\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n animationLevel: global.settings.byKey.animationLevel,\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 hasErrors: Boolean(global.errors.length),\n audioMessage,\n safeLinkModalUrl: global.safeLinkModalUrl,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['loadAnimatedEmojis']),\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/7.5f1b33007c02b15c2a4e.js b/dist/7.4b051a320886f1eac385.js similarity index 98% rename from dist/7.5f1b33007c02b15c2a4e.js rename to dist/7.4b051a320886f1eac385.js index 18135087..02381971 100644 --- a/dist/7.5f1b33007c02b15c2a4e.js +++ b/dist/7.4b051a320886f1eac385.js @@ -1,2 +1,2 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{134:function(t,e,i){"use strict";function s(t,e){return e-Math.floor(e/t)*t}i.d(e,"a",(function(){return s}))},192:function(t,e,i){"use strict";i.r(e);var s=i(309),n=i.n(s),r=i(7),a=i(28);function h(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class o{constructor(t){this.worker=t,h(this,"requestStates",new Map),h(this,"requestStatesByCallback",new Map),this.subscribe()}request(t){const{worker:e,requestStates:i,requestStatesByCallback:s}=this,n=Object(a.a)(i),r={type:"callMethod",messageId:n,...t},h={messageId:n},o=new Promise((t,e)=>{Object.assign(h,{resolve:t,reject:e})});if("function"==typeof r.args[r.args.length-1]){const t=r.args.pop();h.callback=t,s.set(t,h)}return i.set(n,h),o.catch(()=>{}).finally(()=>{i.delete(n),h.callback&&s.delete(h.callback)}),e.postMessage(r),o}cancelCallback(t){t.isCanceled=!0;const{messageId:e}=this.requestStatesByCallback.get(t)||{};e&&this.worker.postMessage({type:"cancelProgress",messageId:e})}subscribe(){const{worker:t,requestStates:e}=this;t.addEventListener("message",({data:t})=>{if("methodResponse"===t.type){const i=e.get(t.messageId);i&&(t.error?i.reject(t.error):i.resolve(t.response))}else if("methodCallback"===t.type){const i=e.get(t.messageId);i&&i.callback&&i.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}}var d=i(61),c=i(134);function u(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const m=r.g?.75:1,l=.75,p=r.j?2:4,g=new Array(4).fill(void 0).map(()=>new o(new n.a));let k=-1;e.default=class{constructor(t,e,i,s={},n){this.id=t,this.container=e,this.animationData=i,this.params=s,this.onLoad=n,u(this,"imgSize",void 0),u(this,"key",void 0),u(this,"msPerFrame",void 0),u(this,"reduceFactor",void 0),u(this,"cacheModulo",void 0),u(this,"chunkSize",void 0),u(this,"workerIndex",void 0),u(this,"chunks",[]),u(this,"framesCount",void 0),u(this,"chunksCount",void 0),u(this,"canvas",document.createElement("canvas")),u(this,"ctx",this.canvas.getContext("2d")),u(this,"isAnimating",!1),u(this,"isWaiting",!0),u(this,"isOnLoadFired",!1),u(this,"isDestroyed",!1),u(this,"approxFrameIndex",0),u(this,"prevFrameIndex",-1),u(this,"stopFrameIndex",0),u(this,"speed",1),u(this,"direction",1),u(this,"lastRenderAt",void 0),this.initContainer(),this.initConfig(),this.initRenderer()}isPlaying(){return this.isAnimating||this.isWaiting}play(){this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}pause(){this.isWaiting?this.stopFrameIndex=this.approxFrameIndex:this.isAnimating=!1;const t=this.getChunkIndex(this.approxFrameIndex);this.chunks=this.chunks.map((e,i)=>i===t?e:void 0)}goToAndPlay(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}goToAndStop(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(t/this.reduceFactor),this.direction=1,this.doPlay()}playSegment([t,e]){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(e/this.reduceFactor),this.direction=t{if(this.isDestroyed)return!1;if(!this.isAnimating&&this.isOnLoadFired)return!1;const t=Math.round(this.approxFrameIndex),e=this.getChunkIndex(t);if(!this.chunks[e])return this.requestChunk(e),this.isAnimating=!1,this.isWaiting=!0,!1;if(this.cacheModulo&&e%this.cacheModulo==0&&this.cleanupPrevChunk(e),this.requestNextChunk(e),t!==this.prevFrameIndex){const e=this.getFrame(t);if(!e)return this.isAnimating=!1,this.isWaiting=!0,!1;const i=new ImageData(new Uint8ClampedArray(e),this.imgSize,this.imgSize);this.ctx.putImageData(i,0,0),this.onLoad&&!this.isOnLoadFired&&(this.isOnLoadFired=!0,this.onLoad()),this.prevFrameIndex=t}const i=Date.now(),s=this.lastRenderAt?this.msPerFrame/(i-this.lastRenderAt):1,n=Math.min(1,this.direction*this.speed/s),r=Math.round(this.approxFrameIndex+n);if(this.lastRenderAt=i,n>0&&(t===this.framesCount-1||r>this.framesCount-1)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=0}else if(n<0&&(0===t||r<0)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=this.framesCount-1}else{if(void 0!==this.stopFrameIndex&&(t===this.stopFrameIndex||n>0&&r>this.stopFrameIndex||n<0&&r{Object.assign(h,{resolve:t,reject:e})});if("function"==typeof r.args[r.args.length-1]){const t=r.args.pop();h.callback=t,s.set(t,h)}return i.set(n,h),o.catch(()=>{}).finally(()=>{i.delete(n),h.callback&&s.delete(h.callback)}),e.postMessage(r),o}cancelCallback(t){t.isCanceled=!0;const{messageId:e}=this.requestStatesByCallback.get(t)||{};e&&this.worker.postMessage({type:"cancelProgress",messageId:e})}subscribe(){const{worker:t,requestStates:e}=this;t.addEventListener("message",({data:t})=>{if("methodResponse"===t.type){const i=e.get(t.messageId);i&&(t.error?i.reject(t.error):i.resolve(t.response))}else if("methodCallback"===t.type){const i=e.get(t.messageId);i&&i.callback&&i.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}}var d=i(61),c=i(134);function u(t,e,i){return e in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const m=r.g?.75:1,l=.75,p=r.j?2:4,g=new Array(4).fill(void 0).map(()=>new o(new n.a));let k=-1;e.default=class{constructor(t,e,i,s={},n){this.id=t,this.container=e,this.animationData=i,this.params=s,this.onLoad=n,u(this,"imgSize",void 0),u(this,"key",void 0),u(this,"msPerFrame",void 0),u(this,"reduceFactor",void 0),u(this,"cacheModulo",void 0),u(this,"chunkSize",void 0),u(this,"workerIndex",void 0),u(this,"chunks",[]),u(this,"framesCount",void 0),u(this,"chunksCount",void 0),u(this,"canvas",document.createElement("canvas")),u(this,"ctx",this.canvas.getContext("2d")),u(this,"isAnimating",!1),u(this,"isWaiting",!0),u(this,"isOnLoadFired",!1),u(this,"isDestroyed",!1),u(this,"approxFrameIndex",0),u(this,"prevFrameIndex",-1),u(this,"stopFrameIndex",0),u(this,"speed",1),u(this,"direction",1),u(this,"lastRenderAt",void 0),this.initContainer(),this.initConfig(),this.initRenderer()}isPlaying(){return this.isAnimating||this.isWaiting}play(){this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}pause(){this.isWaiting?this.stopFrameIndex=this.approxFrameIndex:this.isAnimating=!1;const t=this.getChunkIndex(this.approxFrameIndex);this.chunks=this.chunks.map((e,i)=>i===t?e:void 0)}goToAndPlay(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=void 0,this.direction=1,this.doPlay()}goToAndStop(t){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(t/this.reduceFactor),this.direction=1,this.doPlay()}playSegment([t,e]){this.approxFrameIndex=Math.floor(t/this.reduceFactor),this.stopFrameIndex=Math.floor(e/this.reduceFactor),this.direction=t{if(this.isDestroyed)return!1;if(!this.isAnimating&&this.isOnLoadFired)return!1;const t=Math.round(this.approxFrameIndex),e=this.getChunkIndex(t);if(!this.chunks[e])return this.requestChunk(e),this.isAnimating=!1,this.isWaiting=!0,!1;if(this.cacheModulo&&e%this.cacheModulo==0&&this.cleanupPrevChunk(e),this.requestNextChunk(e),t!==this.prevFrameIndex){const e=this.getFrame(t);if(!e)return this.isAnimating=!1,this.isWaiting=!0,!1;const i=new ImageData(new Uint8ClampedArray(e),this.imgSize,this.imgSize);this.ctx.putImageData(i,0,0),this.onLoad&&!this.isOnLoadFired&&(this.isOnLoadFired=!0,this.onLoad()),this.prevFrameIndex=t}const i=Date.now(),s=this.lastRenderAt?this.msPerFrame/(i-this.lastRenderAt):1,n=Math.min(1,this.direction*this.speed/s),r=Math.round(this.approxFrameIndex+n);if(this.lastRenderAt=i,n>0&&(t===this.framesCount-1||r>this.framesCount-1)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=0}else if(n<0&&(0===t||r<0)){if(this.params.noLoop)return this.isAnimating=!1,!1;this.approxFrameIndex=this.framesCount-1}else{if(void 0!==this.stopFrameIndex&&(t===this.stopFrameIndex||n>0&&r>this.stopFrameIndex||n<0&&r();\n\n private requestStatesByCallback = new Map();\n\n constructor(private worker: Worker) {\n this.subscribe();\n }\n\n request(messageData: { name: string; args: any }) {\n const { worker, requestStates, requestStatesByCallback } = this;\n\n const messageId = generateIdFor(requestStates);\n const payload: CallMethodData = {\n type: 'callMethod',\n messageId,\n ...messageData,\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 (typeof payload.args[payload.args.length - 1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n }\n\n cancelCallback(progressCallback: CancellableCallback) {\n progressCallback.isCanceled = true;\n\n const { messageId } = this.requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n this.worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n }\n\n private subscribe() {\n const { worker, requestStates } = this;\n\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n 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 const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n }\n}\n","import Worker from 'worker-loader!./rlottie.worker';\n\nimport {\n DPR,\n IS_MOBILE_SCREEN,\n IS_SAFARI,\n} from '../../util/environment';\nimport WorkerConnector from '../../util/WorkerConnector';\nimport { animate } from '../../util/animation';\nimport cycleRestrict from '../../util/cycleRestrict';\n\ninterface Params {\n noLoop?: boolean;\n size?: number;\n quality?: number;\n isLowPriority?: boolean;\n}\n\ntype Frames = ArrayBuffer[];\ntype Chunks = (Frames | undefined)[];\n\n// TODO Consider removing chunks\nconst CHUNK_SIZE = 1;\nconst MAX_WORKERS = 4;\nconst HIGH_PRIORITY_QUALITY = IS_MOBILE_SCREEN ? 0.75 : 1;\nconst LOW_PRIORITY_QUALITY = 0.75;\nconst HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\nconst HIGH_PRIORITY_CACHE_MODULO = IS_SAFARI ? 2 : 4;\nconst LOW_PRIORITY_CACHE_MODULO = 0;\n\nconst workers = new Array(MAX_WORKERS).fill(undefined).map(() => new WorkerConnector(new Worker()));\nlet lastWorkerIndex = -1;\n\nclass RLottie {\n // Config\n\n private imgSize!: number;\n\n private key!: string;\n\n private msPerFrame!: number;\n\n private reduceFactor!: number;\n\n private cacheModulo!: number;\n\n private chunkSize!: number;\n\n private workerIndex!: number;\n\n private chunks: Chunks = [];\n\n private framesCount?: number;\n\n private chunksCount?: number;\n\n // Container\n\n private canvas = document.createElement('canvas');\n\n private ctx = this.canvas.getContext('2d')!;\n\n // State\n\n private isAnimating = false;\n\n private isWaiting = true;\n\n private isOnLoadFired = false;\n\n private isDestroyed = false;\n\n private approxFrameIndex = 0;\n\n private prevFrameIndex = -1;\n\n private stopFrameIndex? = 0;\n\n private speed = 1;\n\n private direction: 1 | -1 = 1;\n\n private lastRenderAt?: number;\n\n constructor(\n private id: string,\n private container: HTMLDivElement,\n private animationData: AnyLiteral,\n private params: Params = {},\n private onLoad?: () => void,\n ) {\n this.initContainer();\n this.initConfig();\n this.initRenderer();\n }\n\n isPlaying() {\n return this.isAnimating || this.isWaiting;\n }\n\n play() {\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n pause() {\n if (this.isWaiting) {\n this.stopFrameIndex = this.approxFrameIndex;\n } else {\n this.isAnimating = false;\n }\n\n const currentChunkIndex = this.getChunkIndex(this.approxFrameIndex);\n this.chunks = this.chunks.map((chunk, i) => (i === currentChunkIndex ? chunk : undefined));\n }\n\n goToAndPlay(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n goToAndStop(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.direction = 1;\n this.doPlay();\n }\n\n playSegment([startFrameIndex, stopFrameIndex]: [number, number]) {\n this.approxFrameIndex = Math.floor(startFrameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(stopFrameIndex / this.reduceFactor);\n this.direction = startFrameIndex < stopFrameIndex ? 1 : -1;\n this.doPlay();\n }\n\n setSpeed(speed: number) {\n this.speed = speed;\n }\n\n destroy() {\n this.isDestroyed = true;\n this.pause();\n this.destroyRenderer();\n this.destroyContainer();\n }\n\n private initContainer() {\n if (!(this.container.parentNode instanceof HTMLElement)) {\n throw new Error('[RLottie] Container is not mounted');\n }\n\n let { size } = this.params;\n\n if (!size) {\n size = (\n this.container.offsetWidth\n || parseInt(this.container.style.width, 10)\n || this.container.parentNode.offsetWidth\n );\n\n if (!size) {\n throw new Error('[RLottie] Failed to detect width from container');\n }\n }\n\n this.canvas.style.width = `${size}px`;\n this.canvas.style.height = `${size}px`;\n\n const { isLowPriority, quality = isLowPriority ? LOW_PRIORITY_QUALITY : HIGH_PRIORITY_QUALITY } = this.params;\n // Reduced quality only looks acceptable on high DPR screens\n const imgSize = Math.round(size * Math.max(DPR * quality, 1));\n\n this.canvas.width = imgSize;\n this.canvas.height = imgSize;\n\n this.container.appendChild(this.canvas);\n\n this.imgSize = imgSize;\n }\n\n private initConfig() {\n this.key = `${this.id}_${this.imgSize}`;\n\n const { isLowPriority } = this.params;\n\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = this.animationData.fr || maxFps;\n this.reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n this.msPerFrame = 1000 / (sourceFps / this.reduceFactor);\n this.cacheModulo = isLowPriority ? LOW_PRIORITY_CACHE_MODULO : HIGH_PRIORITY_CACHE_MODULO;\n this.chunkSize = CHUNK_SIZE;\n }\n\n private destroyContainer() {\n this.canvas.remove();\n }\n\n private initRenderer() {\n this.workerIndex = cycleRestrict(MAX_WORKERS, ++lastWorkerIndex);\n\n workers[this.workerIndex].request({\n name: 'init',\n args: [\n this.key,\n this.animationData,\n this.imgSize,\n this.params.isLowPriority,\n this.reduceFactor,\n this.onRendererInit.bind(this),\n ],\n });\n }\n\n private destroyRenderer() {\n workers[this.workerIndex].request({\n name: 'destroy',\n args: [this.key],\n });\n }\n\n private onRendererInit(framesCount: number) {\n this.framesCount = framesCount;\n this.chunksCount = Math.ceil(framesCount / this.chunkSize);\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n\n private doPlay() {\n if (!this.framesCount) {\n return;\n }\n\n if (this.isDestroyed) {\n return;\n }\n\n if (this.isAnimating) {\n return;\n }\n\n if (!this.isWaiting) {\n this.lastRenderAt = undefined;\n }\n\n this.isAnimating = true;\n this.isWaiting = false;\n\n animate(() => {\n if (this.isDestroyed) {\n return false;\n }\n\n // Paused from outside\n if (!this.isAnimating && this.isOnLoadFired) {\n return false;\n }\n\n const frameIndex = Math.round(this.approxFrameIndex);\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n this.requestChunk(chunkIndex);\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n if (this.cacheModulo && chunkIndex % this.cacheModulo === 0) {\n this.cleanupPrevChunk(chunkIndex);\n }\n\n this.requestNextChunk(chunkIndex);\n\n if (frameIndex !== this.prevFrameIndex) {\n const frame = this.getFrame(frameIndex);\n if (!frame) {\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n const imageData = new ImageData(new Uint8ClampedArray(frame), this.imgSize, this.imgSize);\n this.ctx.putImageData(imageData, 0, 0);\n\n if (this.onLoad && !this.isOnLoadFired) {\n this.isOnLoadFired = true;\n this.onLoad();\n }\n\n this.prevFrameIndex = frameIndex;\n }\n\n const now = Date.now();\n const currentSpeed = this.lastRenderAt ? this.msPerFrame / (now - this.lastRenderAt) : 1;\n const delta = Math.min(1, (this.direction * this.speed) / currentSpeed);\n const expectedNextFrameIndex = Math.round(this.approxFrameIndex + delta);\n\n this.lastRenderAt = now;\n\n // Forward animation finished\n if (delta > 0 && (frameIndex === this.framesCount! - 1 || expectedNextFrameIndex > this.framesCount! - 1)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = 0;\n\n // Backward animation finished\n } else if (delta < 0 && (frameIndex === 0 || expectedNextFrameIndex < 0)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = this.framesCount! - 1;\n\n // Stop frame reached\n } else if (\n this.stopFrameIndex !== undefined\n && (frameIndex === this.stopFrameIndex\n || (\n (delta > 0 && expectedNextFrameIndex > this.stopFrameIndex)\n || (delta < 0 && expectedNextFrameIndex < this.stopFrameIndex)\n ))\n ) {\n this.stopFrameIndex = undefined;\n this.isAnimating = false;\n return false;\n\n // Preparing next frame\n } else {\n this.approxFrameIndex += delta;\n }\n\n const nextFrameIndex = Math.round(this.approxFrameIndex);\n\n if (!this.getFrame(nextFrameIndex)) {\n this.requestChunk(this.getChunkIndex(nextFrameIndex));\n this.isWaiting = true;\n this.isAnimating = false;\n return false;\n }\n\n return true;\n });\n }\n\n private getFrame(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const indexInChunk = this.getFrameIndexInChunk(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n return undefined;\n }\n\n return chunk[indexInChunk];\n }\n\n private getFrameIndexInChunk(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n return frameIndex - chunkIndex * this.chunkSize;\n }\n\n private getChunkIndex(frameIndex: number) {\n return Math.floor(frameIndex / this.chunkSize);\n }\n\n private requestChunk(chunkIndex: number) {\n if (this.chunks[chunkIndex]) {\n return;\n }\n\n this.chunks[chunkIndex] = [];\n\n const fromIndex = chunkIndex * this.chunkSize;\n const toIndex = Math.min(fromIndex + this.chunkSize - 1, this.framesCount! - 1);\n\n workers[this.workerIndex].request({\n name: 'renderFrames',\n args: [this.key, fromIndex, toIndex, this.onFrameLoad.bind(this)],\n });\n }\n\n private cleanupPrevChunk(chunkIndex: number) {\n if (this.chunksCount! < 3) {\n return;\n }\n\n const prevChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex - 1);\n this.chunks[prevChunkIndex] = undefined;\n }\n\n private requestNextChunk(chunkIndex: number) {\n if (this.chunksCount === 1) {\n return;\n }\n\n const nextChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex + 1);\n\n if (!this.chunks[nextChunkIndex]) {\n this.requestChunk(nextChunkIndex);\n }\n }\n\n private onFrameLoad(frameIndex: number, arrayBuffer: ArrayBuffer) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n // Frame can be skipped and chunk can be already cleaned up\n if (!chunk) {\n return;\n }\n\n chunk[this.getFrameIndexInChunk(frameIndex)] = arrayBuffer;\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n}\n\nexport default RLottie;\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"36ad5121226f8c2acd49.worker.js\");\n};"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///./src/util/cycleRestrict.ts","webpack:///./src/util/WorkerConnector.ts","webpack:///./src/lib/rlottie/RLottie.ts","webpack:///./src/lib/rlottie/rlottie.worker.ts"],"names":["cycleRestrict","length","index","Math","floor","WorkerConnector","constructor","worker","Map","this","subscribe","request","messageData","requestStates","requestStatesByCallback","messageId","generateIdFor","payload","type","requestState","promise","Promise","resolve","reject","Object","assign","args","callback","pop","set","catch","finally","delete","postMessage","cancelCallback","progressCallback","isCanceled","get","addEventListener","data","error","response","callbackArgs","HIGH_PRIORITY_QUALITY","IS_MOBILE_SCREEN","LOW_PRIORITY_QUALITY","HIGH_PRIORITY_CACHE_MODULO","IS_SAFARI","workers","Array","fill","undefined","map","Worker","lastWorkerIndex","RLottie","id","container","animationData","params","onLoad","document","createElement","canvas","getContext","initContainer","initConfig","initRenderer","isPlaying","isAnimating","isWaiting","play","stopFrameIndex","direction","doPlay","pause","approxFrameIndex","currentChunkIndex","getChunkIndex","chunks","chunk","i","goToAndPlay","frameIndex","reduceFactor","goToAndStop","playSegment","startFrameIndex","setSpeed","speed","destroy","isDestroyed","destroyRenderer","destroyContainer","parentNode","HTMLElement","Error","size","offsetWidth","parseInt","style","width","height","isLowPriority","quality","imgSize","round","max","DPR","appendChild","key","maxFps","sourceFps","fr","msPerFrame","cacheModulo","chunkSize","remove","workerIndex","name","onRendererInit","bind","framesCount","chunksCount","ceil","lastRenderAt","animate","isOnLoadFired","chunkIndex","requestChunk","cleanupPrevChunk","requestNextChunk","prevFrameIndex","frame","getFrame","imageData","ImageData","Uint8ClampedArray","ctx","putImageData","now","Date","currentSpeed","delta","min","expectedNextFrameIndex","noLoop","nextFrameIndex","indexInChunk","getFrameIndexInChunk","fromIndex","toIndex","onFrameLoad","prevChunkIndex","nextChunkIndex","arrayBuffer","module","exports"],"mappings":"0FAAe,SAASA,EAAcC,EAAgBC,GACpD,OAAOA,EAAQC,KAAKC,MAAMF,EAAQD,GAAUA,EAD9C,mC,qMCqDe,MAAMI,EAKnBC,YAAoBC,GAAgB,KAAhBA,SAAgB,uBAJZ,IAAIC,KAIQ,iCAFF,IAAIA,KAGpCC,KAAKC,YAGPC,QAAQC,GACN,MAAM,OAAEL,EAAF,cAAUM,EAAV,wBAAyBC,GAA4BL,KAErDM,EAAYC,YAAcH,GAC1BI,EAA0B,CAC9BC,KAAM,aACNH,eACGH,GAGCO,EAAe,CAAEJ,aAGjBK,EAAwB,IAAIC,QAAQ,CAACC,EAASC,KAClDC,OAAOC,OAAON,EAAc,CAAEG,UAASC,aAGzC,GAAqD,mBAA1CN,EAAQS,KAAKT,EAAQS,KAAKzB,OAAS,GAAmB,CAC/D,MAAM0B,EAAWV,EAAQS,KAAKE,MAC9BT,EAAaQ,SAAWA,EACxBb,EAAwBe,IAAIF,EAAUR,GAgBxC,OAbAN,EAAcgB,IAAId,EAAWI,GAC7BC,EACGU,MAAM,QACNC,QAAQ,KACPlB,EAAcmB,OAAOjB,GAEjBI,EAAaQ,UACfb,EAAwBkB,OAAOb,EAAaQ,YAIlDpB,EAAO0B,YAAYhB,GAEZG,EAGTc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F,KAAM,CAACjB,KAAKqG,IAAKwC,EAAWC,EAAS9I,KAAK+I,YAAY/B,KAAKhH,SAIvDyH,iBAAiBF,GACvB,GAAIvH,KAAKkH,YAAe,EACtB,OAGF,MAAM8B,EAAiBzJ,YAAcS,KAAKkH,YAAcK,EAAa,GACrEvH,KAAKsE,OAAO0E,QAAkBtG,EAGxBgF,iBAAiBH,GACvB,GAAyB,IAArBvH,KAAKkH,YACP,OAGF,MAAM+B,EAAiB1J,YAAcS,KAAKkH,YAAcK,EAAa,GAEhEvH,KAAKsE,OAAO2E,IACfjJ,KAAKwH,aAAayB,GAIdF,YAAYrE,EAAoBwE,GACtC,MAAM3B,EAAavH,KAAKqE,cAAcK,GAChCH,EAAQvE,KAAKsE,OAAOiD,GAErBhD,IAILA,EAAMvE,KAAK4I,qBAAqBlE,IAAewE,EAE3ClJ,KAAK6D,WACP7D,KAAKiE,a,oBCtaXkF,EAAOC,QAAU,WACf,OAAO,IAAIxG,OAAO,IAA0B","file":"7.4b051a320886f1eac385.js","sourcesContent":["export default function cycleRestrict(length: number, index: number) {\n return index - Math.floor(index / length) * length;\n}\n","import generateIdFor from './generateIdFor';\n\nexport interface CancellableCallback {\n (\n ...args: any[]\n ): void;\n\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n}\n\ntype CallMethodData = {\n type: 'callMethod';\n messageId?: string;\n name: string;\n args: any;\n};\n\ntype OriginMessageData = CallMethodData | {\n type: 'cancelProgress';\n messageId: string;\n};\n\nexport interface OriginMessageEvent {\n data: OriginMessageData;\n}\n\nexport type WorkerMessageData = {\n type: 'methodResponse';\n messageId: string;\n response?: any;\n error?: { message: string };\n} | {\n type: 'methodCallback';\n messageId: string;\n callbackArgs: any[];\n} | {\n type: 'unhandledError';\n error?: { message: string };\n};\n\nexport interface WorkerMessageEvent {\n data: WorkerMessageData;\n}\n\ninterface RequestStates {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback: AnyToVoidFunction;\n}\n\n// TODO Replace `any` with proper generics\nexport default class WorkerConnector {\n private requestStates = new Map();\n\n private requestStatesByCallback = new Map();\n\n constructor(private worker: Worker) {\n this.subscribe();\n }\n\n request(messageData: { name: string; args: any }) {\n const { worker, requestStates, requestStatesByCallback } = this;\n\n const messageId = generateIdFor(requestStates);\n const payload: CallMethodData = {\n type: 'callMethod',\n messageId,\n ...messageData,\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 (typeof payload.args[payload.args.length - 1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n }\n\n cancelCallback(progressCallback: CancellableCallback) {\n progressCallback.isCanceled = true;\n\n const { messageId } = this.requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n this.worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n }\n\n private subscribe() {\n const { worker, requestStates } = this;\n\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n 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 const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n }\n}\n","import Worker from 'worker-loader!./rlottie.worker';\n\nimport {\n DPR,\n IS_MOBILE_SCREEN,\n IS_SAFARI,\n} from '../../util/environment';\nimport WorkerConnector from '../../util/WorkerConnector';\nimport { animate } from '../../util/animation';\nimport cycleRestrict from '../../util/cycleRestrict';\n\ninterface Params {\n noLoop?: boolean;\n size?: number;\n quality?: number;\n isLowPriority?: boolean;\n}\n\ntype Frames = ArrayBuffer[];\ntype Chunks = (Frames | undefined)[];\n\n// TODO Consider removing chunks\nconst CHUNK_SIZE = 1;\nconst MAX_WORKERS = 4;\nconst HIGH_PRIORITY_QUALITY = IS_MOBILE_SCREEN ? 0.75 : 1;\nconst LOW_PRIORITY_QUALITY = 0.75;\nconst HIGH_PRIORITY_MAX_FPS = 60;\nconst LOW_PRIORITY_MAX_FPS = 30;\nconst HIGH_PRIORITY_CACHE_MODULO = IS_SAFARI ? 2 : 4;\nconst LOW_PRIORITY_CACHE_MODULO = 0;\n\nconst workers = new Array(MAX_WORKERS).fill(undefined).map(() => new WorkerConnector(new Worker()));\nlet lastWorkerIndex = -1;\n\nclass RLottie {\n // Config\n\n private imgSize!: number;\n\n private key!: string;\n\n private msPerFrame!: number;\n\n private reduceFactor!: number;\n\n private cacheModulo!: number;\n\n private chunkSize!: number;\n\n private workerIndex!: number;\n\n private chunks: Chunks = [];\n\n private framesCount?: number;\n\n private chunksCount?: number;\n\n // Container\n\n private canvas = document.createElement('canvas');\n\n private ctx = this.canvas.getContext('2d')!;\n\n // State\n\n private isAnimating = false;\n\n private isWaiting = true;\n\n private isOnLoadFired = false;\n\n private isDestroyed = false;\n\n private approxFrameIndex = 0;\n\n private prevFrameIndex = -1;\n\n private stopFrameIndex? = 0;\n\n private speed = 1;\n\n private direction: 1 | -1 = 1;\n\n private lastRenderAt?: number;\n\n constructor(\n private id: string,\n private container: HTMLDivElement,\n private animationData: AnyLiteral,\n private params: Params = {},\n private onLoad?: () => void,\n ) {\n this.initContainer();\n this.initConfig();\n this.initRenderer();\n }\n\n isPlaying() {\n return this.isAnimating || this.isWaiting;\n }\n\n play() {\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n pause() {\n if (this.isWaiting) {\n this.stopFrameIndex = this.approxFrameIndex;\n } else {\n this.isAnimating = false;\n }\n\n const currentChunkIndex = this.getChunkIndex(this.approxFrameIndex);\n this.chunks = this.chunks.map((chunk, i) => (i === currentChunkIndex ? chunk : undefined));\n }\n\n goToAndPlay(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = undefined;\n this.direction = 1;\n this.doPlay();\n }\n\n goToAndStop(frameIndex: number) {\n this.approxFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(frameIndex / this.reduceFactor);\n this.direction = 1;\n this.doPlay();\n }\n\n playSegment([startFrameIndex, stopFrameIndex]: [number, number]) {\n this.approxFrameIndex = Math.floor(startFrameIndex / this.reduceFactor);\n this.stopFrameIndex = Math.floor(stopFrameIndex / this.reduceFactor);\n this.direction = startFrameIndex < stopFrameIndex ? 1 : -1;\n this.doPlay();\n }\n\n setSpeed(speed: number) {\n this.speed = speed;\n }\n\n destroy() {\n this.isDestroyed = true;\n this.pause();\n this.destroyRenderer();\n this.destroyContainer();\n }\n\n private initContainer() {\n if (!(this.container.parentNode instanceof HTMLElement)) {\n throw new Error('[RLottie] Container is not mounted');\n }\n\n let { size } = this.params;\n\n if (!size) {\n size = (\n this.container.offsetWidth\n || parseInt(this.container.style.width, 10)\n || this.container.parentNode.offsetWidth\n );\n\n if (!size) {\n throw new Error('[RLottie] Failed to detect width from container');\n }\n }\n\n this.canvas.style.width = `${size}px`;\n this.canvas.style.height = `${size}px`;\n\n const { isLowPriority, quality = isLowPriority ? LOW_PRIORITY_QUALITY : HIGH_PRIORITY_QUALITY } = this.params;\n // Reduced quality only looks acceptable on high DPR screens\n const imgSize = Math.round(size * Math.max(DPR * quality, 1));\n\n this.canvas.width = imgSize;\n this.canvas.height = imgSize;\n\n this.container.appendChild(this.canvas);\n\n this.imgSize = imgSize;\n }\n\n private initConfig() {\n this.key = `${this.id}_${this.imgSize}`;\n\n const { isLowPriority } = this.params;\n\n const maxFps = isLowPriority ? LOW_PRIORITY_MAX_FPS : HIGH_PRIORITY_MAX_FPS;\n const sourceFps = this.animationData.fr || maxFps;\n this.reduceFactor = sourceFps % maxFps === 0 ? sourceFps / maxFps : 1;\n this.msPerFrame = 1000 / (sourceFps / this.reduceFactor);\n this.cacheModulo = isLowPriority ? LOW_PRIORITY_CACHE_MODULO : HIGH_PRIORITY_CACHE_MODULO;\n this.chunkSize = CHUNK_SIZE;\n }\n\n private destroyContainer() {\n this.canvas.remove();\n }\n\n private initRenderer() {\n this.workerIndex = cycleRestrict(MAX_WORKERS, ++lastWorkerIndex);\n\n workers[this.workerIndex].request({\n name: 'init',\n args: [\n this.key,\n this.animationData,\n this.imgSize,\n this.params.isLowPriority,\n this.reduceFactor,\n this.onRendererInit.bind(this),\n ],\n });\n }\n\n private destroyRenderer() {\n workers[this.workerIndex].request({\n name: 'destroy',\n args: [this.key],\n });\n }\n\n private onRendererInit(framesCount: number) {\n this.framesCount = framesCount;\n this.chunksCount = Math.ceil(framesCount / this.chunkSize);\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n\n private doPlay() {\n if (!this.framesCount) {\n return;\n }\n\n if (this.isDestroyed) {\n return;\n }\n\n if (this.isAnimating) {\n return;\n }\n\n if (!this.isWaiting) {\n this.lastRenderAt = undefined;\n }\n\n this.isAnimating = true;\n this.isWaiting = false;\n\n animate(() => {\n if (this.isDestroyed) {\n return false;\n }\n\n // Paused from outside\n if (!this.isAnimating && this.isOnLoadFired) {\n return false;\n }\n\n const frameIndex = Math.round(this.approxFrameIndex);\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n this.requestChunk(chunkIndex);\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n if (this.cacheModulo && chunkIndex % this.cacheModulo === 0) {\n this.cleanupPrevChunk(chunkIndex);\n }\n\n this.requestNextChunk(chunkIndex);\n\n if (frameIndex !== this.prevFrameIndex) {\n const frame = this.getFrame(frameIndex);\n if (!frame) {\n this.isAnimating = false;\n this.isWaiting = true;\n return false;\n }\n\n const imageData = new ImageData(new Uint8ClampedArray(frame), this.imgSize, this.imgSize);\n this.ctx.putImageData(imageData, 0, 0);\n\n if (this.onLoad && !this.isOnLoadFired) {\n this.isOnLoadFired = true;\n this.onLoad();\n }\n\n this.prevFrameIndex = frameIndex;\n }\n\n const now = Date.now();\n const currentSpeed = this.lastRenderAt ? this.msPerFrame / (now - this.lastRenderAt) : 1;\n const delta = Math.min(1, (this.direction * this.speed) / currentSpeed);\n const expectedNextFrameIndex = Math.round(this.approxFrameIndex + delta);\n\n this.lastRenderAt = now;\n\n // Forward animation finished\n if (delta > 0 && (frameIndex === this.framesCount! - 1 || expectedNextFrameIndex > this.framesCount! - 1)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = 0;\n\n // Backward animation finished\n } else if (delta < 0 && (frameIndex === 0 || expectedNextFrameIndex < 0)) {\n if (this.params.noLoop) {\n this.isAnimating = false;\n return false;\n }\n\n this.approxFrameIndex = this.framesCount! - 1;\n\n // Stop frame reached\n } else if (\n this.stopFrameIndex !== undefined\n && (frameIndex === this.stopFrameIndex\n || (\n (delta > 0 && expectedNextFrameIndex > this.stopFrameIndex)\n || (delta < 0 && expectedNextFrameIndex < this.stopFrameIndex)\n ))\n ) {\n this.stopFrameIndex = undefined;\n this.isAnimating = false;\n return false;\n\n // Preparing next frame\n } else {\n this.approxFrameIndex += delta;\n }\n\n const nextFrameIndex = Math.round(this.approxFrameIndex);\n\n if (!this.getFrame(nextFrameIndex)) {\n this.requestChunk(this.getChunkIndex(nextFrameIndex));\n this.isWaiting = true;\n this.isAnimating = false;\n return false;\n }\n\n return true;\n });\n }\n\n private getFrame(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const indexInChunk = this.getFrameIndexInChunk(frameIndex);\n const chunk = this.chunks[chunkIndex];\n if (!chunk) {\n return undefined;\n }\n\n return chunk[indexInChunk];\n }\n\n private getFrameIndexInChunk(frameIndex: number) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n return frameIndex - chunkIndex * this.chunkSize;\n }\n\n private getChunkIndex(frameIndex: number) {\n return Math.floor(frameIndex / this.chunkSize);\n }\n\n private requestChunk(chunkIndex: number) {\n if (this.chunks[chunkIndex]) {\n return;\n }\n\n this.chunks[chunkIndex] = [];\n\n const fromIndex = chunkIndex * this.chunkSize;\n const toIndex = Math.min(fromIndex + this.chunkSize - 1, this.framesCount! - 1);\n\n workers[this.workerIndex].request({\n name: 'renderFrames',\n args: [this.key, fromIndex, toIndex, this.onFrameLoad.bind(this)],\n });\n }\n\n private cleanupPrevChunk(chunkIndex: number) {\n if (this.chunksCount! < 3) {\n return;\n }\n\n const prevChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex - 1);\n this.chunks[prevChunkIndex] = undefined;\n }\n\n private requestNextChunk(chunkIndex: number) {\n if (this.chunksCount === 1) {\n return;\n }\n\n const nextChunkIndex = cycleRestrict(this.chunksCount!, chunkIndex + 1);\n\n if (!this.chunks[nextChunkIndex]) {\n this.requestChunk(nextChunkIndex);\n }\n }\n\n private onFrameLoad(frameIndex: number, arrayBuffer: ArrayBuffer) {\n const chunkIndex = this.getChunkIndex(frameIndex);\n const chunk = this.chunks[chunkIndex];\n // Frame can be skipped and chunk can be already cleaned up\n if (!chunk) {\n return;\n }\n\n chunk[this.getFrameIndexInChunk(frameIndex)] = arrayBuffer;\n\n if (this.isWaiting) {\n this.doPlay();\n }\n }\n}\n\nexport default RLottie;\n","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0c4a4b990ada4f850f27.worker.js\");\n};"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/7c2292f972e10d28cc51.worker.js b/dist/8ede9bdfe3390ee397af.worker.js similarity index 99% rename from dist/7c2292f972e10d28cc51.worker.js rename to dist/8ede9bdfe3390ee397af.worker.js index 4619c7f0..0f935c97 100644 --- a/dist/7c2292f972e10d28cc51.worker.js +++ b/dist/8ede9bdfe3390ee397af.worker.js @@ -1,3 +1,3 @@ -/*! For license information please see 7c2292f972e10d28cc51.worker.js.LICENSE.txt */ -!function(e){var t={};function n(s){if(t[s])return t[s].exports;var i=t[s]={i:s,l:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(s,i,function(t){return e[t]}.bind(null,i));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=111)}([function(e,t,n){const s=n(6),i=n(81),a=n(59),r=n(21),o=n(99),c=n(100),u=n(20),d=n(29),l=n(104),f=n(42),p=n(8);e.exports={Api:s,TelegramClient:i,sessions:l,connection:a,extensions:f,tl:r,version:o,events:c,utils:u,errors:d,helpers:p}},function(e,t,n){"use strict";n.d(t,"f",(function(){return M})),n.d(t,"a",(function(){return k})),n.d(t,"b",(function(){return E})),n.d(t,"e",(function(){return R})),n.d(t,"g",(function(){return T})),n.d(t,"c",(function(){return D})),n.d(t,"i",(function(){return B})),n.d(t,"h",(function(){return x})),n.d(t,"d",(function(){return j}));var s={};n.r(s),n.d(s,"Type",(function(){return m})),n.d(s,"fetch",(function(){return y})),n.d(s,"save",(function(){return b})),n.d(s,"clear",(function(){return _}));var i=n(0),a=n(42),r=n(4),o=n(17),c=n(26),u=n(9),d=n(41),l=n(11),f=n(5),p=n(2),g=n(34);const h=self.caches;let m;async function y(e,t,n){if(h)try{const s=new Request(t),i=await h.open(e),a=await i.match(s);if(!a)return;switch(n){case m.Text:return await a.text();case m.Blob:{const e=await a.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=a.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case m.Json:return await a.json();default:return}}catch(e){return void console.warn(e)}}async function b(e,t,n){if(h)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),i=new Request(t),a=new Response(s),r=await h.open(e);return await r.put(i,a)}catch(e){return void console.warn(e)}}async function _(e){try{if(!h)return;return await h.delete(e)}catch(e){return void console.warn(e)}}async function w({url:e,mediaFormat:t,start:n,end:a},o,c,u){const{data:h,mimeType:m,fullSize:y}=await async function(e,t,n,s,a,o,c){const u=e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!u)return;if("file"===u[1]){const e=await fetch(u[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d,g=u[2];const h=u[3]?u[3].replace("?size=",""):void 0;let m;"avatar"===u[1]||"profile"===u[1]?(d=Object(p.s)(Number(g)),g=Math.abs(Number(g))):d=u[1];switch(d){case"channel":case"chat":m=f.a.chats[g];break;case"user":m=f.a.users[g];break;case"msg":m=f.a.messages[g];break;case"sticker":case"gif":case"wallpaper":m=f.a.documents[g];break;case"photo":m=f.a.photos[g];break;case"stickerSet":m=f.a.stickerSets[g]}if(!m)return;if(["msg","sticker","gif","wallpaper","photo"].includes(d)){c===l.ApiMediaFormat.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(m,{sizeType:h,start:a,end:o,progressCallback:s,workers:r.k});let n,u;return m instanceof i.Api.Message?(n=function(e,t){if(!e||!e.media)return;if(e.media instanceof i.Api.MessageMediaPhoto)return"image/jpeg";if(e.media instanceof i.Api.MessageMediaDocument&&e.media.document instanceof i.Api.Document)return t?e.media.document.attributes.some(e=>e instanceof i.Api.DocumentAttributeSticker)?"image/webp":"image/jpeg":e.media.document.mimeType;return}(m,h),m.media instanceof i.Api.MessageMediaDocument&&m.media.document instanceof i.Api.Document&&(u=m.media.document.size)):m instanceof i.Api.Photo?n="image/jpeg":"sticker"===d&&h?n="image/webp":(n=m.mimeType,u=m.size),{mimeType:n,data:e,fullSize:u}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(m);return{mimeType:c===l.ApiMediaFormat.Lottie?"application/json":v(e),data:e}}{const e=await t.downloadProfilePhoto(m,"profile"===u[1]);return{mimeType:v(e),data:e}}}(e,o,c,u,n,a,t)||{};if(!h)return;const _=await async function(e,t,n){switch(t){case l.ApiMediaFormat.DataUri:return Object(g.a)(new Blob([e],{type:n}));case l.ApiMediaFormat.BlobUrl:return new Blob([e],{type:n});case l.ApiMediaFormat.Lottie:{const t=Object(d.inflate)(e,{to:"string"});return JSON.parse(t)}case l.ApiMediaFormat.Progressive:return e.buffer}return}(h,t,m);if(!_)return;const w=t!==l.ApiMediaFormat.Progressive&&(t!==l.ApiMediaFormat.BlobUrl||_.size<=r.o);if(!r.n&&s&&w){b(e.startsWith("avatar")?r.q:r.p,e,_)}return{prepared:t===l.ApiMediaFormat.Progressive?"":function(e){if(e instanceof Blob)return URL.createObjectURL(e);return e}(_),arrayBuffer:t===l.ApiMediaFormat.Progressive?_:void 0,mimeType:m,fullSize:y}}function v(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce((e,t)=>e+t.toString(16),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(m||(m={}));var A=n(13);a.Logger.setLevel(r.h?"debug":"warn");const I={build:e=>e};let P,C,S=!1;async function M(e,t){P=e,r.g&&console.log(">>> START INIT API"),C=new i.TelegramClient(new i.sessions.CallbackSession(t,U),"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||"Unknown UserAgent",appVersion:r.d+" Z",useWSS:!0,additionalDcsDisabled:r.l}),C.addEventHandler(O,I),C.addEventHandler(c.b,I);try{r.g&&console.log("[GramJs/client] CONNECTING"),await C.start({phoneNumber:o.g,phoneCode:o.e,password:o.f,firstAndLastNames:o.i,qrCode:o.h,onError:o.b}),r.g&&(console.log(">>> FINISH INIT API"),console.log("[GramJs/client] CONNECTED")),Object(o.c)(),P({"@type":"updateApiReady"}),j()}catch(e){throw r.g&&console.log("[GramJs/client] CONNECTING ERROR",e),e}}async function k(){await T(new i.Api.auth.LogOut),await C.destroy()}async function E(){await C.disconnect()}function R(){return C}function U(e){P({"@type":"updateSession",sessionData:e})}function O(e){e instanceof i.connection.UpdateConnectionState?S=e.state===i.connection.UpdateConnectionState.connected:e instanceof i.Api.UpdatesTooLong&&async function(){try{await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&P({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}()}async function T(e,t=!1,n=!1){if(S)try{r.g&&console.log("[GramJs/client] INVOKE "+e.className);const n=await C.invoke(e);if(r.g&&console.log("[GramJs/client] INVOKE RESPONSE "+e.className,n),t){let t;n instanceof i.Api.Updates||n instanceof i.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof i.Api.Updates||n.updates instanceof i.Api.UpdatesCombined)&&(t=n.updates),t?(!function(e){const t=[...e.users,...e.chats];e.updates.forEach(e=>{t&&(e._entities=t)})}(t),t.updates.forEach(t=>{Object(c.b)(t,e)})):n instanceof i.Api.UpdatesTooLong||Object(c.b)(n,e)}return n}catch(t){if(r.g&&(console.log("[GramJs/client] INVOKE ERROR "+e.className),console.error(t)),function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof i.Api.messages.SendMessage||t instanceof i.Api.messages.SendMedia||t instanceof i.Api.messages.SendMultiMedia),{message:s}=e;P({"@type":"error",error:{message:s,isSlowMode:n}})}(t,e),n)throw t;return}else r.g&&console.warn(`[GramJs/client] INVOKE ERROR ${e.className}: Client is not connected`)}function D(e,t){return w(e,C,S,t)}function B(e,t){return C.uploadFile({file:e,onProgress:t,workers:r.w})}function x(e){return C.updateTwoFaSettings(e)}async function j(){const e=await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}));if(!(e&&e.user instanceof i.Api.User))return;f.a.users[e.user.id]=e.user;const t=Object(A.b)(e);Object(u.o)(t.id),Object(o.d)(t)}},function(e,t,n){"use strict";(function(e){n.d(t,"s",(function(){return d})),n.d(t,"o",(function(){return l})),n.d(t,"i",(function(){return f})),n.d(t,"g",(function(){return g})),n.d(t,"l",(function(){return h})),n.d(t,"f",(function(){return m})),n.d(t,"h",(function(){return y})),n.d(t,"j",(function(){return b})),n.d(t,"d",(function(){return _})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return v})),n.d(t,"n",(function(){return A})),n.d(t,"q",(function(){return I})),n.d(t,"t",(function(){return P})),n.d(t,"u",(function(){return C})),n.d(t,"c",(function(){return S})),n.d(t,"e",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"a",(function(){return E})),n.d(t,"p",(function(){return R})),n.d(t,"k",(function(){return U}));var s=n(15),i=n.n(s),a=n(0),r=n(8),o=n(11),c=n(5),u=n(14);function d(e){return e>0?"user":e<=-1e9?"channel":"chat"}function l(e){return e>0?new a.Api.PeerUser({userId:e}):e<=-1e9?new a.Api.PeerChannel({channelId:-e}):new a.Api.PeerChat({chatId:-e})}function f(e,t){return e>0||e<=-1e9?e>0?new a.Api.InputPeerUser({userId:e,accessHash:i()(t)}):new a.Api.InputPeerChannel({channelId:-e,accessHash:i()(t)}):new a.Api.InputPeerChat({chatId:-e})}function p(e){if(e>0){const{accessHash:t}=c.a.users[e]||{};return t?new a.Api.InputPeerUser({userId:e,accessHash:t}):void 0}if(e<=-1e9){const{accessHash:t}=c.a.chats[-e]||{};return t?new a.Api.InputPeerChannel({channelId:-e,accessHash:t}):void 0}return new a.Api.InputPeerChat({chatId:-e})}function g(e,t){return e>0?new a.Api.InputUser({userId:e,accessHash:i()(t)}):e<=-1e9?new a.Api.InputChannel({channelId:-e,accessHash:i()(t)}):-e}function h(e,t){return new a.Api.InputStickerSetID({id:i()(e),accessHash:i()(t)})}function m(e){const t=c.a.documents[e.id];if(t)return new a.Api.InputDocument(Object(u.b)(t,["id","accessHash","fileReference"]))}function y(e){const t=m(e);if(t)return new a.Api.InputMediaDocument({id:t})}function b(t,n){const{summary:s,quiz:i}=t,r=new a.Api.Poll({id:n,publicVoters:s.isPublic,question:s.question,answers:s.answers.map(({text:t,option:n})=>new a.Api.PollAnswer({text:t,option:e.from(n)})),quiz:s.quiz,multipleChoice:s.multipleChoice});if(!i)return new a.Api.InputMediaPoll({poll:r});const o=i.correctAnswers.map(t=>e.from(t)),{solution:c}=i,u=i.solutionEntities?i.solutionEntities.map(A):[];return new a.Api.InputMediaPoll({poll:r,correctAnswers:o,...c&&{solution:c,solutionEntities:u}})}function _(e){const{emoticon:t,contacts:n,nonContacts:s,groups:i,channels:r,bots:o,excludeArchived:c,excludeMuted:u,excludeRead:d,pinnedChatIds:l,includedChatIds:f,excludedChatIds:g}=e,h=l?l.map(p).filter(Boolean):[],m=f?f.map(p).filter(Boolean):[],y=g?g.map(p).filter(Boolean):[];return new a.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:i||void 0,bots:o||void 0,excludeArchived:c||void 0,excludeMuted:u||void 0,excludeRead:d||void 0,broadcasts:r||void 0,pinnedPeers:h,includePeers:m,excludePeers:y})}function w(){return Object(r.readBigIntFromBuffer)(Object(r.generateRandomBytes)(8),!0,!0)}function v(e,t,n){return new a.Api.Message({id:e,peerId:l(t),fromId:l(t),media:n.media})}function A(e){const{type:t,offset:n,length:s,url:i,userId:r}=e,u=r?c.a.users[r]:void 0;switch(t){case o.ApiMessageEntityTypes.Bold:return new a.Api.MessageEntityBold({offset:n,length:s});case o.ApiMessageEntityTypes.Italic:return new a.Api.MessageEntityItalic({offset:n,length:s});case o.ApiMessageEntityTypes.Underline:return new a.Api.MessageEntityUnderline({offset:n,length:s});case o.ApiMessageEntityTypes.Strike:return new a.Api.MessageEntityStrike({offset:n,length:s});case o.ApiMessageEntityTypes.Code:return new a.Api.MessageEntityCode({offset:n,length:s});case o.ApiMessageEntityTypes.Pre:return new a.Api.MessageEntityPre({offset:n,length:s,language:""});case o.ApiMessageEntityTypes.Blockquote:return new a.Api.MessageEntityBlockquote({offset:n,length:s});case o.ApiMessageEntityTypes.TextUrl:return new a.Api.MessageEntityTextUrl({offset:n,length:s,url:i});case o.ApiMessageEntityTypes.Url:return new a.Api.MessageEntityUrl({offset:n,length:s});case o.ApiMessageEntityTypes.Hashtag:return new a.Api.MessageEntityHashtag({offset:n,length:s});case o.ApiMessageEntityTypes.MentionName:return new a.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new a.Api.InputUser({userId:r,accessHash:u.accessHash})});default:return new a.Api.MessageEntityUnknown({offset:n,length:s})}}function I(e){let t=0;return e.forEach(e=>{t=(20261*t&2147483647)+e&2147483647}),t}function P(e){const{media:t}=e;return!!t&&(t instanceof a.Api.MessageMediaPhoto||t instanceof a.Api.MessageMediaDocument||t instanceof a.Api.MessageMediaWebPage&&t.webpage instanceof a.Api.WebPage&&t.webpage.photo instanceof a.Api.Photo)}function C(e){return"photo"in e.action&&e.action.photo instanceof a.Api.Photo}function S(e){if(e instanceof a.Api.PhotoEmpty)return new a.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new a.Api.ChatPhoto({dcId:t,photoId:n})}function M({phone:e,firstName:t,lastName:n}){return new a.Api.InputPhoneContact({clientId:i()(1),phone:e,firstName:t,lastName:n})}function k(e,t=0){return new a.Api.ChatBannedRights({...e,untilDate:t})}function E(e){return new a.Api.ChatAdminRights(e)}function R(e){const{shippingAddress:t}=e;return new a.Api.PaymentRequestedInfo({...e,shippingAddress:t?new a.Api.PostAddress(t):void 0})}function U(e){switch(e){case"phoneNumber":return new a.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new a.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new a.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new a.Api.InputPrivacyKeyForwards;case"chatInvite":return new a.Api.InputPrivacyKeyChatInvite}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"k",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"f",(function(){return A})),n.d(t,"g",(function(){return I})),n.d(t,"h",(function(){return P})),n.d(t,"a",(function(){return C})),n.d(t,"b",(function(){return S}));var s=n(0),i=n(14);function a(e){return e.hasOwnProperty("userId")}function r(e){return e.hasOwnProperty("chatId")}var o=n(18);function c(e,t=!1){const n=Boolean("min"in e&&e.min),i="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&v(e.photo),r=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:r,...i&&{accessHash:i},...a&&{avatarHash:a},...(e instanceof s.Api.Channel||e instanceof s.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 s.Api.Chat||e instanceof s.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...d(e),..."creator"in e&&{isCreator:e.creator},...l(e),...f(e)}}function u(e,t){const{peer:n,folderId:s,unreadMark:i,unreadCount:a,unreadMentionsCount:r,notifySettings:{silent:o,muteUntil:u},readOutboxMaxId:d,readInboxMaxId:l}=e,f=o||"number"==typeof u&&Date.now()<1e3*u;return{id:h(n),...s&&{folderId:s},type:y(t),title:_(n,t),lastReadOutboxMessageId:d,lastReadInboxMessageId:l,unreadCount:a,unreadMentionsCount:r,isMuted:f,...i&&{hasUnreadMark:!0},...c(t)}}function d(e){return e instanceof s.Api.Chat||e instanceof s.Api.Channel?{adminRights:Object(o.b)(e.adminRights),currentUserBannedRights:e instanceof s.Api.Channel?Object(o.b)(e.bannedRights):void 0,defaultBannedRights:Object(o.b)(e.defaultBannedRights)}:{}}function l(e){if(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden)return{isRestricted:!0};if(e instanceof s.Api.User){const t=e.restricted?p(e.restrictionReason):void 0;return void 0===t?{isRestricted:!1}:{isRestricted:e.restricted,restrictionReason:t}}if(e instanceof s.Api.Chat)return{isNotJoined:e.left,isRestricted:e.kicked};if(e instanceof s.Api.Channel){const t=e.restricted&&e.restrictionReason&&e.restrictionReason.some(e=>"all"===e.platform);return{isNotJoined:e.left,isRestricted:t,restrictionReason:p(e.restrictionReason)}}return{}}function f(e){return e instanceof s.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof s.Api.InputChannelEmpty)?{migratedTo:{chatId:h(e.migratedTo),...e.migratedTo instanceof s.Api.InputChannel&&{accessHash:e.migratedTo.accessHash.toString()}}}:{}}function p(e){if(!e)return;const t=e.find(({platform:e})=>"all"===e);return t?Object(i.b)(t,["reason","text"]):void 0}function g(e,t=!1,n=!1){if(e instanceof s.Api.Chat||e instanceof s.Api.Channel||e instanceof s.Api.User||n&&(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden))return{id:e instanceof s.Api.User?e.id:-e.id,type:y(e),title:e instanceof s.Api.User?w(e):e.title,...c(e,t)}}function h(e){return a(e)?e.userId:r(e)?-e.chatId:-e.channelId}function m(e){return function(e){return e.hasOwnProperty("userId")}(e)?e.userId:function(e){return e.hasOwnProperty("chatId")}(e)?-e.chatId:function(e){return e.hasOwnProperty("channelId")}(e)?-e.channelId:void 0}function y(e){return e instanceof s.Api.User||e instanceof s.Api.UserEmpty?"chatTypePrivate":e instanceof s.Api.Chat||e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function b(e){return a(e)?"user"+e.userId:r(e)?"chat"+e.chatId:"chat"+e.channelId}function _(e,t){return a(e)?w(t):t.title}function w(e){return e.firstName?`${e.firstName}${e.lastName?" "+e.lastName:""}`:e.lastName||void 0}function v(e){if("photoId"in e)return e.photoId.toString()}function A(e){return{userId:e instanceof s.Api.ChannelParticipantBanned||e instanceof s.Api.ChannelParticipantLeft?h(e.peer):e.userId,inviterId:"inviterId"in e?e.inviterId:void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?e.kickedBy:void 0,promotedByUserId:"promotedBy"in e?e.promotedBy:void 0,bannedRights:"bannedRights"in e?Object(o.b)(e.bannedRights):void 0,adminRights:"adminRights"in e?Object(o.b)(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof s.Api.ChannelParticipantAdmin||e instanceof s.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof s.Api.ChannelParticipantCreator||e instanceof s.Api.ChatParticipantCreator)&&{isOwner:!0}}}function I(e){return e instanceof s.Api.ChatParticipants||e instanceof s.Api.channels.ChannelParticipants?e.participants.map(A).filter(Boolean):void 0}function P(e){let t="";if(!(e.action instanceof s.Api.SendMessageCancelAction))return e.action instanceof s.Api.SendMessageTypingAction?t="lng_user_typing":e.action instanceof s.Api.SendMessageRecordVideoAction?t="lng_send_action_record_video":e.action instanceof s.Api.SendMessageUploadVideoAction?t="lng_send_action_upload_video":e.action instanceof s.Api.SendMessageRecordAudioAction?t="lng_send_action_record_audio":e.action instanceof s.Api.SendMessageUploadAudioAction?t="lng_send_action_upload_audio":e.action instanceof s.Api.SendMessageUploadPhotoAction?t="lng_send_action_upload_photo":e.action instanceof s.Api.SendMessageUploadDocumentAction?t="lng_send_action_upload_file":e.action instanceof s.Api.SendMessageGeoLocationAction?t="selecting a location to share":e.action instanceof s.Api.SendMessageChooseContactAction?t="selecting a contact to share":e.action instanceof s.Api.SendMessageGamePlayAction?t="lng_playing_game":e.action instanceof s.Api.SendMessageRecordRoundAction?t="lng_send_action_record_round":e.action instanceof s.Api.SendMessageUploadRoundAction&&(t="lng_send_action_upload_round"),{action:t,...!(e instanceof s.Api.UpdateUserTyping)&&{userId:h(e.fromId)},timestamp:Date.now()}}function C(e){return{...Object(i.c)(e,["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"]),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(m).filter(Boolean),includedChatIds:e.includePeers.map(m).filter(Boolean),excludedChatIds:e.excludePeers.map(m).filter(Boolean)}}function S({filter:e,description:t}){return{...C(e),description:t}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return s})),n.d(t,"g",(function(){return i})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return r})),n.d(t,"n",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"q",(function(){return u})),n.d(t,"o",(function(){return d})),n.d(t,"c",(function(){return l})),n.d(t,"b",(function(){return f})),n.d(t,"k",(function(){return p})),n.d(t,"w",(function(){return g})),n.d(t,"r",(function(){return h})),n.d(t,"t",(function(){return m})),n.d(t,"f",(function(){return y})),n.d(t,"u",(function(){return b})),n.d(t,"m",(function(){return _})),n.d(t,"s",(function(){return w})),n.d(t,"v",(function(){return v})),n.d(t,"a",(function(){return A})),n.d(t,"e",(function(){return I})),n.d(t,"j",(function(){return P})),n.d(t,"i",(function(){return C}));const s="1.0.6",i=!1,a=!1,r=!1,o=!1,c="tt-media",u="tt-media-avatars",d=524288,l=300,f=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),p=16,g=16,h=("undefined"!=typeof window&&window.innerHeight,200),m=50,y=100,b=40,_=1e9,w="MEMOJI_STICKER",v=777e3,A=0,I=1,P=777,C="android"},function(e,t,n){"use strict";t.a={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{}}},function(e,t,n){(function(t){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{parseTl:i,serializeBytes:a,serializeDate:r}=n(44),{toSignedLittleBuffer:o}=n(8),c=n(79),u=n(80),d="undefined"!=typeof self&&void 0!==self.localStorage;function l(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,n){switch(n){case"int":{const n=t.alloc(4);return n.writeInt32LE(e,0),n}case"long":return o(e,8);case"int128":return o(e,16);case"int256":return o(e,32);case"double":{const n=t.alloc(8);return n.writeDoubleLE(e,0),n}case"string":return a(e);case"Bool":return e?t.from("b5757299","hex"):t.from("379779bc","hex");case"true":return t.alloc(0);case"bytes":return a(e);case"date":return r(e);default:return e.getBytes()}}function p(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let i=0;i{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}(g("constructor",e.constructors),g("request",e.requests))}()}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"p",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"k",(function(){return m})),n.d(t,"w",(function(){return y})),n.d(t,"h",(function(){return b})),n.d(t,"u",(function(){return _})),n.d(t,"v",(function(){return w})),n.d(t,"a",(function(){return v})),n.d(t,"H",(function(){return A})),n.d(t,"b",(function(){return I})),n.d(t,"q",(function(){return P})),n.d(t,"r",(function(){return C})),n.d(t,"d",(function(){return S})),n.d(t,"c",(function(){return M})),n.d(t,"g",(function(){return k})),n.d(t,"z",(function(){return E})),n.d(t,"y",(function(){return R})),n.d(t,"i",(function(){return U})),n.d(t,"n",(function(){return O})),n.d(t,"f",(function(){return T})),n.d(t,"e",(function(){return D})),n.d(t,"A",(function(){return B})),n.d(t,"o",(function(){return x})),n.d(t,"B",(function(){return j})),n.d(t,"F",(function(){return N})),n.d(t,"G",(function(){return V})),n.d(t,"E",(function(){return F})),n.d(t,"I",(function(){return L})),n.d(t,"D",(function(){return q})),n.d(t,"C",(function(){return H})),n.d(t,"m",(function(){return K})),n.d(t,"l",(function(){return z})),n.d(t,"x",(function(){return G})),n.d(t,"s",(function(){return W})),n.d(t,"t",(function(){return $}));var s=n(0),i=n(4),a=n(1),r=n(3),o=n(9),c=n(13),u=n(14),d=n(5),l=n(2),f=n(16);let p;function g(e){p=e}async function h({limit:e,offsetDate:t,archived:n,withPinned:d}){const l=await Object(a.g)(new s.Api.messages.GetDialogs({offsetPeer:new s.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?i.e:void 0,...d&&{excludePinned:!0}})),f=d?await Object(a.g)(new s.Api.messages.GetPinnedDialogs({folderId:n?i.e:void 0})):void 0;if(!l||l instanceof s.Api.messages.DialogsNotModified)return;Z(l),f&&Z(f);const p=Object(u.a)([...l.messages,...f?f.messages:[]].map(o.b).filter(Boolean),"chatId"),g={...J(l),...f&&J(f)},h=[],m={},y={},b=[...f?f.dialogs:[],...l.dialogs],_=[];b.forEach(e=>{if(!(e instanceof s.Api.Dialog)||!n&&e.folderId===i.e||n&&e.folderId!==i.e)return;const t=g[Object(r.k)(e.peer)],a=Object(r.c)(e,t);if(a.lastMessage=p[a.id],h.push(a),d&&e.pinned&&_.push(a.id),e.draft){const{formattedText:t,replyingToId:n}=Object(o.h)(e.draft)||{};t&&(m[a.id]=t),n&&(y[a.id]=n)}});const w=[...l.users,...f?f.users:[]].map(c.a).filter(Boolean),v=h.map(e=>e.id);let A;return A=l instanceof s.Api.messages.DialogsSlice?l.count:v.length,{chatIds:v,chats:h,users:w,draftsById:m,replyingToById:y,orderedPinnedIds:d?_:void 0,totalChatCount:A}}function m(e){const{id:t,accessHash:n,adminRights:i}=e;return Object(l.g)(t,n)instanceof s.Api.InputChannel?async function(e,t,n){const i=await Object(a.g)(new s.Api.channels.GetFullChannel({channel:Object(l.g)(e,t)}));if(!(i&&i.fullChat instanceof s.Api.ChannelFull))return;const{about:o,onlineCount:c,exportedInvite:u,slowmodeSeconds:d,slowmodeNextSendDate:f,migratedFromChatId:p,migratedFromMaxId:g,canViewParticipants:h,linkedChatId:m,hiddenPrehistory:y,call:b}=i.fullChat,_=u instanceof s.Api.ChatInviteExported?u.link:void 0,{members:w,users:v}=h&&await K(e,t)||{},{members:A,users:I}=h&&n&&await K(e,t,"kicked")||{},{members:P,users:C}=h&&n&&await K(e,t,"admin")||{};return{fullInfo:{about:o,onlineCount:c,inviteLink:_,slowMode:d?{seconds:d,nextSendDate:f}:void 0,migratedFrom:p?{chatId:Object(r.j)({chatId:p}),maxMessageId:g}:void 0,canViewMembers:h,isPreHistoryHidden:y,members:w,kickedMembers:A,adminMembers:P,groupCallId:b?b.id.toString():void 0,linkedChatId:m?Object(r.j)({chatId:m}):void 0},users:[...v||[],...I||[],...C||[]]}}(t,n,i):async function(e){const t=await Object(a.g)(new s.Api.messages.GetFullChat({chatId:Object(l.g)(e)}));if(!(t&&t.fullChat instanceof s.Api.ChatFull))return;Z(t);const{about:n,participants:i,exportedInvite:o}=t.fullChat,u=Object(r.g)(i),d=u?u.filter(({isAdmin:e,isOwner:t})=>e||t):void 0;return{fullInfo:{about:n,members:u,adminMembers:d,canViewMembers:!0,...o&&{inviteLink:o.link}},users:t.users.map(c.a).filter(Boolean)}}(t)}async function y({query:e}){const t=await Object(a.g)(new s.Api.contacts.Search({q:e}));if(!t)return;Z(t);const n=t.myResults.map(r.j),i=[...t.chats,...t.users].map(e=>Object(r.d)(e)).filter(Boolean),o=t.users.map(c.a).filter(e=>!!e&&!e.isSelf);return{localChats:i.filter(e=>n.includes(e.id)),localUsers:o.filter(e=>n.includes(e.id)),globalChats:i.filter(e=>!n.includes(e.id)),globalUsers:o.filter(e=>!n.includes(e.id))}}async function b({type:e,user:t}){let n;if("self"===e||"user"===e){const i=await Object(a.g)(new s.Api.users.GetUsers({id:["user"===e&&t?Object(l.g)(t.id,t.accessHash):new s.Api.InputUserSelf]}));if(!i||!i.length)return;[n]=i}else if("support"===e){const e=await Object(a.g)(new s.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const i=Object(r.d)(n,"support"===e);if(i)return p({"@type":"updateChat",id:i.id,chat:i}),{chatId:i.id}}async function _(e){const{id:t,accessHash:n}=e,i=await Object(a.g)(new s.Api.messages.GetPeerDialogs({peers:[new s.Api.InputDialogPeer({peer:Object(l.i)(t,n)})]}));if(!i)return;const c=i.dialogs[0];if(!(c&&c instanceof s.Api.Dialog))return;const u=J(i)[Object(r.k)(c.peer)];if(!u)return;Z(i);const d=Object(o.b)(i.messages[0]);p({"@type":"updateChat",id:t,chat:{...Object(r.c)(c,u),lastMessage:d}})}function w({chat:e,text:t,entities:n,replyToMsgId:i}){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:t,...n&&{entities:n.map(l.n)},replyToMsgId:i}))}function v(e){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:""}))}async function A({chat:e,isMuted:t}){await Object(a.g)(new s.Api.account.UpdateNotifySettings({peer:new s.Api.InputNotifyPeer({peer:Object(l.i)(e.id,e.accessHash)}),settings:new s.Api.InputPeerNotifySettings({muteUntil:t?2**31-1:void 0})})),_(e)}async function I({title:e,about:t,users:n}){const o=await Object(a.g)(new s.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(o instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected channel creation update",o));const c=o.chats[0];if(!(c&&c instanceof s.Api.Channel))return void(i.g&&console.error("Created channel not found",o));const u=Object(r.d)(c);return await Object(a.g)(new s.Api.channels.InviteToChannel({channel:Object(l.g)(u.id,u.accessHash),users:n.map(({id:e,accessHash:t})=>Object(l.g)(e,t))})),u}function P({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.JoinChannel({channel:Object(l.g)(e,t)}),!0)}function C({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.LeaveChannel({channel:Object(l.g)(e,t)}),!0)}function S({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.DeleteChannel({channel:Object(l.g)(e,t)}),!0)}async function M({title:e,users:t}){const n=await Object(a.g)(new s.Api.messages.CreateChat({title:e,users:t.map(({id:e,accessHash:t})=>Object(l.g)(e,t))}),!0);if(!(n instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected chat creation update",n));const o=n.chats[0];if(o&&o instanceof s.Api.Chat)return Object(r.d)(o);i.g&&console.error("Created chat not found",n)}async function k({chatId:e,accessHash:t,photo:n}){const i=await Object(a.i)(n),r=Object(l.g)(e,t);return Object(a.g)(r instanceof s.Api.InputChannel?new s.Api.channels.EditPhoto({channel:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}):new s.Api.messages.EditChatPhoto({chatId:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}),!0)}async function E({chat:e,shouldBePinned:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.ToggleDialogPin({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),pinned:t||void 0}))&&p({"@type":"updateChatPinned",id:e.id,isPinned:t})}function R({chat:e,folderId:t}){const{id:n,accessHash:i}=e;return Object(a.g)(new s.Api.folders.EditPeerFolders({folderPeers:[new s.Api.InputFolderPeer({peer:Object(l.i)(n,i),folderId:t})]}),!0)}async function U(){const e=await Object(a.g)(new s.Api.messages.GetDialogFilters);if(e)return{byId:Object(u.a)(e.map(r.a),"id"),orderedIds:e.map(({id:e})=>e)}}async function O(){const e=await Object(a.g)(new s.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(r.b)}async function T({id:e,folderUpdate:t}){const n=Object(l.d)(t);await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&p({"@type":"updateChatFolder",id:e,folder:t})}async function D(e){const t=await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await O();t&&p({"@type":"updateChatFolder",id:e,folder:void 0}),n&&p({"@type":"updateRecommendedChatFolders",folders:n})}async function B({chat:e,hasUnreadMark:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.MarkDialogUnread({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),unread:t||void 0}))&&p({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function x(e){const t=await Object(a.g)(new s.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:i}=t,o=i.length?Object(r.d)(i[0]):Object(r.d)(n[0]);return o?(Z(t),o):void 0}function j({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.TogglePreHistoryHidden({channel:r,enabled:t}),!0)}function N({chat:e,bannedRights:t}){const{id:n,accessHash:i}=e,r=Object(l.i)(n,i);return Object(a.g)(new s.Api.messages.EditChatDefaultBannedRights({peer:r,bannedRights:Object(l.b)(t)}),!0)}function V({chat:e,user:t,bannedRights:n}){const i=Object(l.g)(e.id,e.accessHash),r=Object(l.i)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditBanned({channel:i,participant:r,bannedRights:Object(l.b)(n)}),!0)}function F({chat:e,user:t,adminRights:n,customTitle:i=""}){const r=Object(l.g)(e.id,e.accessHash),o=Object(l.g)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditAdmin({channel:r,userId:o,adminRights:Object(l.a)(n),rank:i}),!0)}async function L(e,t){const n=Object(l.g)(e.id,e.accessHash);await Object(a.g)(n instanceof s.Api.InputChannel?new s.Api.channels.EditTitle({channel:n,title:t}):new s.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function q(e,t){await Object(a.g)(new s.Api.messages.EditChatAbout({peer:Object(l.i)(e.id,e.accessHash),about:t}))&&p({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function H({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.ToggleSignatures({channel:r,enabled:t}),!0)}async function K(e,t,n="recent",o){let u;switch(n){case"kicked":u=new s.Api.ChannelParticipantsKicked({q:""});break;case"admin":u=new s.Api.ChannelParticipantsAdmins;break;default:u=new s.Api.ChannelParticipantsRecent}const d=await Object(a.g)(new s.Api.channels.GetParticipants({channel:Object(l.g)(e,t),filter:u,offset:o,limit:i.r}));if(d&&!(d instanceof s.Api.channels.ChannelParticipantsNotModified))return Z(d),{members:Object(r.g)(d),users:d.users.map(c.a).filter(Boolean)}}async function z(){const e=await Object(a.g)(new s.Api.channels.GetGroupsForDiscussion);if(e)return Z(e),e.chats.map(e=>Object(r.d)(e))}function G({channel:e,chat:t}){return Object(a.g)(new s.Api.channels.SetDiscussionGroup({broadcast:Object(l.i)(e.id,e.accessHash),group:t?Object(l.i)(t.id,t.accessHash):new s.Api.InputChannelEmpty}))}async function W(e){const t=await Object(a.g)(new s.Api.messages.MigrateChat({chatId:Object(l.g)(e.id)}),!0);if(t&&t instanceof s.Api.Updates)return Z(t),Object(r.d)(t.chats[1]);i.g&&console.error("Unexpected channel creation update",t)}async function $(e){const t=await Object(a.g)(new s.Api.messages.CheckChatInvite({hash:e}));if(t)return t instanceof s.Api.ChatInvite?void await Object(a.g)(new s.Api.messages.ImportChatInvite({hash:e}),!0):Object(r.d)(t.chat)}function J(e){const t={};return e.chats.forEach(e=>{t["chat"+e.id]=e}),e.users.forEach(e=>{t["user"+e.id]=e}),t}function Z(e){"users"in e&&e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),"chats"in e&&e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),"messages"in e&&e.messages.forEach(e=>{e instanceof s.Api.Message&&Object(l.t)(e)&&Object(f.a)(e)})}},function(e,t,n){(function(t){const s=n(15),i=n(35);function a(e,n=!0,i=!1){let a=t.from(e);const r=a.length;n&&(a=a.reverse());let o=s(a.toString("hex"),16);return i&&Math.floor(o.toString("2").length/8)>=r&&(o=o.subtract(s(2).pow(s(8*r)))),o}function r(e,n=8){const i=s(e),a=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0},generateRandomBytes:c,generateKeyDataFromNonce:async function(e,n){e=r(e,16),n=r(n,32);const[s,i,a]=await Promise.all([u(t.concat([n,e])),u(t.concat([e,n])),u(t.concat([n,n]))]);return{key:t.concat([s,i.slice(0,12)]),iv:t.concat([i.slice(12,20),a,n.slice(0,4)])}},sha1:u,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 i=s.one,a=e;for(;t.greater(s.zero);){const e=t.remainder(s(2));t=t.divide(s(2)),e.eq(s.one)&&(i=i.multiply(a),i=i.remainder(n)),a=a.multiply(a),a=a.remainder(n)}return i},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise(t=>setTimeout(t,e)),getByteArray:function(e,t=!1){const n=e.toString(2).length,i=Math.floor((n+8-1)/8);return o(s(e),i,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const n=t.alloc(4*e.length);for(let t=0;t1?"s":""})`}}else if(e instanceof s.Api.MessageActionContactSignUp)o="%action_origin% joined Telegram";else if(e instanceof s.Api.MessageActionPaymentSent){const t=l(e.currency),n=(Number(e.totalAmount)/100).toFixed(2);o=`You successfully transferred ${t}${n} to shop for %product%`}else if(e instanceof s.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);o=`Voice chat ended (${t} min${t>1?"s":""})`}else o="Voice chat started";else o="%ACTION_NOT_IMPLEMENTED%";"photo"in e&&e.photo instanceof s.Api.Photo&&(Object(p.b)(e.photo),a=Object(c.a)(e.photo));return{text:o,type:u,targetUserId:d,targetChatId:f,photo:a}}(t.action,n,Boolean(t.post),a);u&&(o.action=u);const{replyToMsgId:d,replyToTopId:f}=t.replyTo||{},h=t.editDate&&!t.editHide,{inlineButtons:m,keyboardButtons:y}=function(e){const{id:t,replyMarkup:n,media:i}=e;if(!n)return i instanceof s.Api.MessageMediaWebPage&&i.webpage instanceof s.Api.WebPage&&"telegram_message"===i.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:i.webpage.url}]]}:void 0;if(!(n instanceof s.Api.ReplyKeyboardMarkup||n instanceof s.Api.ReplyInlineMarkup))return;const a=n.rows.map(({buttons:e})=>e.map(e=>{let n,a,{text:r}=e;return e instanceof s.Api.KeyboardButton?(n="command",a=r):e instanceof s.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof s.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof s.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof s.Api.KeyboardButtonBuy?(i instanceof s.Api.MessageMediaInvoice&&i.receiptMsgId&&(r="Receipt",a=i.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:r,messageId:t,value:a}}));return{[n instanceof s.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a}}(t)||{},b=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&Object(r.j)(e.savedFromPeer),s=e.fromId&&Object(r.j)(e.fromId);return{isChannelPost:Boolean(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,i),{replies:_,mediaUnread:w,postAuthor:v}=t,I=t.groupedId&&t.groupedId.toString(),C=Boolean(I)&&!(o.document||o.audio),S=t.replyMarkup instanceof s.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:a,content:o,date:t.date,senderId:n||t.out&&t.post&&g||e,views:t.views,isFromScheduled:t.fromScheduled,...d&&{replyToMessageId:d},...f&&{replyToTopMessageId:f},...b&&{forwardInfo:b},...h&&{isEdited:h},...w&&{isMediaUnread:w},...t.mentioned&&w&&{hasUnreadMention:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:m,...y&&{keyboardButtons:y},...S&&{shouldHideKeyboardButtons:S},...t.viaBotId&&{viaBotId:t.viaBotId},..._&&_.comments&&{threadInfo:B(_,t.id,e)},...v&&{adminTitle:v}}}function A(e,t){return{text:e,...t&&{entities:t.map(D)}}}function I(e){if(!(e instanceof s.Api.DraftMessageEmpty)&&e.message)return{formattedText:A(e.message,e.entities),replyingToId:e.replyToMsgId}}function P(e){const t=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;return Object(o.a)(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(!(e instanceof s.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof s.Api.Photo))return;if(e.ttlSeconds)return;return Object(c.a)(e.photo)}(e);if(n)return{photo:n};const i=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document instanceof s.Api.Document&&e.document.mimeType.startsWith("video")))return;return C(e.document)}(e);if(i)return{video:i};const r=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||t.voice)return;return{fileName:R(e.document,"audio"),...Object(a.b)(e.document,["size","mimeType"]),...Object(a.b)(t,["duration","performer","title"])}}(e);if(r)return{audio:r};const u=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||!t.voice)return;const{duration:n,waveform:i}=t;return{duration:n,waveform:i?Array.from(i):void 0}}(e);if(u)return{voice:u};const d=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document))return;if(e.ttlSeconds)return;return S(e.document)}(e);if(d)return{document:d};const f=function(e){if(!(e instanceof s.Api.MessageMediaContact))return;return Object(a.b)(e,["firstName","lastName","phoneNumber","userId"])}(e);if(f)return{contact:f};const p=function(e){if(!(e instanceof s.Api.MessageMediaPoll))return;return M(e.poll,e.results)}(e);if(p)return{poll:p};const g=E(e);if(g)return{webPage:g};const h=function(e){if(!(e instanceof s.Api.MessageMediaInvoice))return;return function(e){const{description:t,title:n,photo:s,test:i,totalAmount:a,currency:r,receiptMsgId:o}=e,c=l(r);return{text:t,title:n,photoUrl:s&&s.url,receiptMsgId:o,description:`${c}${(Number(a)/100).toFixed(2)} ${i?"TEST INVOICE":""}`}}(e)}(e);return h?{invoice:h}:void 0}function C(e){if(e instanceof s.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:i,size:a,attributes:r}=e,o=r.find(e=>e instanceof s.Api.DocumentAttributeVideo);if(!o)return;const u=r.find(e=>e instanceof s.Api.DocumentAttributeAnimated),{duration:d,w:l,h:f,supportsStreaming:p=!1,roundMessage:g=!1}=o;return{id:String(t),mimeType:n,duration:d,fileName:R(e,"video"),width:l,height:f,supportsStreaming:p,isRound:g,isGif:Boolean(u),thumbnail:Object(c.e)(i),size:a}}function S(e){if(!(e instanceof s.Api.Document))return;const{id:t,size:n,mimeType:i,date:a,thumbs:r}=e,o=r&&Object(c.e)(r);return{id:String(t),size:n,mimeType:i,timestamp:a,fileName:R(e),thumbnail:o}}function M(e,t){const{id:n,answers:s}=e,i=s.map(e=>({text:e.text,option:String.fromCharCode(...e.option)}));return{id:n.toString(),summary:{isPublic:e.publicVoters,...Object(a.b)(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:i},results:k(t)}}function k(e){const{results:t,totalVoters:n,recentVoters:s,solution:i,solutionEntities:a}=e;return{totalVoters:n,recentVoterIds:s,results:t&&t.map(({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})),solution:i,...a&&{solutionEntities:a.map(D)}}}function E(e){if(!(e instanceof s.Api.MessageMediaWebPage&&e.webpage instanceof s.Api.WebPage))return;const{id:t,photo:n,document:i}=e.webpage;return{id:Number(t),...Object(a.b)(e.webpage,["url","displayUrl","siteName","title","description"]),photo:n&&n instanceof s.Api.Photo?{id:String(n.id),thumbnail:Object(c.e)(n.sizes),sizes:n.sizes.filter(e=>e instanceof s.Api.PhotoSize).map(c.b)}:void 0,...i&&{hasDocument:!0}}}function R(e,t="file"){const{mimeType:n,attributes:i}=e,a=i.find(e=>e instanceof s.Api.DocumentAttributeFilename);if(a)return a.fileName;const r=n.split("/")[1];return`${t}${String(e.id)}.${r}`}function U(e,t,n,s,i,a,r,o,c,d){const l=h++,f=i&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:i,size:a}=e;if(e.quick){const{width:r,height:o,duration:c}=e.quick;return i.startsWith("image/")?{photo:{id:"temp",sizes:[],thumbnail:{width:r,height:o,dataUri:""},blobUrl:n}}:{video:{id:"temp",mimeType:i,duration:c||0,fileName:t,width:r,height:o,blobUrl:n,...s&&{thumbnail:{width:r,height:o,dataUri:s}},size:a}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=Object(u.a)(n,63);return{voice:{duration:t,waveform:s}}}return i.startsWith("audio/")?{audio:{mimeType:i,fileName:t,size:a,duration:200}}:{document:{mimeType:i,fileName:t,size:a,...s&&{previewBlobUrl:s}}}}(i),p="chatTypeChannel"===e.type;return{id:l,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...a&&{sticker:a},...r&&{video:r},...o&&T(o,l)},date:d||Math.round(Date.now()/1e3),isOutgoing:!p,senderId:g,...s&&{replyToMessageId:s},...c&&{groupedId:c,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}function O(e,t){const n=h++,{content:s,chatId:i,id:a,senderId:r,groupedId:o,isInAlbum:c}=t,u=s.audio,d=e.id===g&&(i!==e.id||t.forwardInfo)&&!u;return{id:n,chatId:e.id,content:s,date:Math.round(Date.now()/1e3),isOutgoing:!d&&"chatTypeChannel"!==e.type,senderId:g,sendingState:"messageSendingStatePending",...r!==g&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:i,fromMessageId:a,senderUserId:r}},groupedId:o,isInAlbum:c}}function T(e,t){return{poll:{id:t.toString(),summary:Object(a.b)(e.summary,["question","answers"]),results:{}}}}function D(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function B(e,t,n){const{channelId:s,replies:a,maxId:o,readMaxId:c,recentRepliers:u}=e;if(s===i.j)return;return{threadId:t,...n!==s?{chatId:Object(r.j)({channelId:s}),originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:o,lastReadInboxMessageId:c,...u&&{recentReplierIds:u.map(r.j)}}}},function(e,t,n){"use strict";(function(e){n.d(t,"m",(function(){return y})),n.d(t,"g",(function(){return b})),n.d(t,"e",(function(){return _})),n.d(t,"v",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"s",(function(){return P})),n.d(t,"q",(function(){return S})),n.d(t,"y",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"c",(function(){return E})),n.d(t,"a",(function(){return R})),n.d(t,"o",(function(){return U})),n.d(t,"p",(function(){return O})),n.d(t,"r",(function(){return T})),n.d(t,"u",(function(){return D})),n.d(t,"t",(function(){return B})),n.d(t,"j",(function(){return x})),n.d(t,"w",(function(){return j})),n.d(t,"n",(function(){return N})),n.d(t,"l",(function(){return V})),n.d(t,"k",(function(){return F})),n.d(t,"i",(function(){return L})),n.d(t,"x",(function(){return q})),n.d(t,"f",(function(){return H})),n.d(t,"h",(function(){return z}));var s=n(0),i=n(11),a=n(4),r=n(1),o=n(9),c=n(13),u=n(2),d=n(5),l=n(3),f=n(34),p=n(16),g=n(33),h=n(7);let m;function y(e){m=e}async function b({chat:e,threadId:t,...n}){const a=t===i.MAIN_THREAD_ID?s.Api.messages.GetHistory:s.Api.messages.GetReplies;let d;try{d=await Object(r.g)(new a({peer:Object(u.i)(e.id,e.accessHash),...t!==i.MAIN_THREAD_ID&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&m({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!d||d instanceof s.Api.messages.MessagesNotModified||!d.messages)return;K(d);const f=d.messages.map(o.b).filter(Boolean),p=d.users.map(c.a).filter(Boolean),g=d.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=f.map(({threadInfo:e})=>e).filter(Boolean);return{messages:f,users:p,chats:g,threadInfos:h}}async function _({chat:e,messageId:t}){const n="channel"===Object(u.s)(e.id),a=await Object(r.g)(n?new s.Api.channels.GetMessages({channel:Object(u.g)(e.id,e.accessHash),id:[new s.Api.InputMessageID({id:t})]}):new s.Api.messages.GetMessages({id:[new s.Api.InputMessageID({id:t})]}));if(!a||a instanceof s.Api.messages.MessagesNotModified)return;const d=a.messages[0];if(!d)return;if(d instanceof s.Api.MessageEmpty)return i.MESSAGE_DELETED;const l=d&&Object(o.b)(d);if(!l)return;d instanceof s.Api.Message&&Object(p.a)(d);return{message:l,users:a.users.map(c.a).filter(Boolean)}}let w=Promise.resolve();function v({chat:e,text:t,entities:n,replyingTo:i,attachment:c,sticker:l,gif:f,poll:p,isSilent:g,scheduledAt:h,groupedId:y,noWebPage:b},_){const v=Object(o.g)(e,t,n,i,c,l,f,p,y,h);m({"@type":v.isScheduled?"newScheduledMessage":"newMessage",id:v.id,chatId:e.id,message:v}),setTimeout(()=>{m({"@type":v.isScheduled?"updateScheduledMessage":"updateMessage",id:v.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})},1e3);const I=Object(u.r)();if(d.a.localMessages[I.toString()]=v,y)return function({chat:e,text:t,entities:n,replyingTo:i,attachment:o,groupedId:c,isSilent:d,scheduledAt:l},f,p,g){let h=-1;A[c]||(A[c]={counter:0,singleMediaByIndex:{}});h=A[c].counter++;const m=w;return w=(async()=>{let y;try{y=await C(p,o,g)}catch(e){return a.g&&console.warn(e),A[c].counter--,void await m}const b=await async function(e,t){const n=await Object(r.g)(new s.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof s.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof s.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaPhoto({id:new s.Api.InputPhoto({id:e,accessHash:t,fileReference:i})})}if(n instanceof s.Api.MessageMediaDocument&&n.document&&n.document instanceof s.Api.Document){const{document:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaDocument({id:new s.Api.InputDocument({id:e,accessHash:t,fileReference:i})})}return}(Object(u.i)(e.id,e.accessHash),y);if(await m,!b)return A[c].counter--,void(a.g&&console.warn("Failed to upload grouped media"));if(A[c].singleMediaByIndex[h]=new s.Api.InputSingleMedia({media:b,randomId:f,message:t||"",entities:n?n.map(u.n):void 0}),Object.keys(A[c].singleMediaByIndex).length{let o;if(c)try{o=await C(v,c,_)}catch(e){return a.g&&console.warn(e),void await P}else l?o=Object(u.h)(l):f?o=Object(u.h)(f):p&&(o=Object(u.j)(p,I));await P;const d=o?s.Api.messages.SendMedia:s.Api.messages.SendMessage;await Object(r.g)(new d({clearDraft:!0,message:t||"",entities:n?n.map(u.n):void 0,peer:Object(u.i)(e.id,e.accessHash),randomId:I,...g&&{silent:g},...h&&{scheduleDate:h},...i&&{replyToMsgId:i},...o&&{media:o},...b&&{noWebpage:b}}),!0)})(),w}const A={};async function I({chat:e,message:t,text:n,entities:i,noWebPage:a}){const o=1e3*t.date>Date.now(),c={content:{...t.content,...n&&{text:{text:n,entities:i}}}};m({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:c}),d.a.localMessages[t.id]={...t,...c};const l=i&&i.map(u.n);await Object(r.g)(new s.Api.messages.EditMessage({message:n||"",entities:l,peer:Object(u.i)(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function P({chat:e,message:t,scheduledAt:n}){await Object(r.g)(new s.Api.messages.EditMessage({peer:Object(u.i)(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function C(t,n,i){const{filename:a,blobUrl:o,mimeType:c,quick:u,voice:d}=n,l=await Object(f.b)(o,a),p=e=>{i.isCanceled?p.isCanceled=!0:i(e,t.id)},h=await Object(r.i)(l,p),m=[new s.Api.DocumentAttributeFilename({fileName:a})];if(u){if(c.startsWith("image/"))return new s.Api.InputMediaUploadedPhoto({file:h});{const{width:e,height:t,duration:n}=u;void 0!==n&&m.push(new s.Api.DocumentAttributeVideo({duration:n,w:e,h:t}))}}if(d){const{duration:t,waveform:n}=d,{data:i}=Object(g.a)(n,63);m.push(new s.Api.DocumentAttributeAudio({voice:!0,duration:t,waveform:e.from(i)}))}return new s.Api.InputMediaUploadedDocument({file:h,mimeType:c,attributes:m})}async function S({chat:e,messageId:t,isUnpin:n,isOneSide:i,isSilent:a}){await Object(r.g)(new s.Api.messages.UpdatePinnedMessage({peer:Object(u.i)(e.id,e.accessHash),id:t,...n&&{unpin:!0},...i&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function M({chat:e}){await Object(r.g)(new s.Api.messages.UnpinAllMessages({peer:Object(u.i)(e.id,e.accessHash)}),!0)}async function k({chat:e,messageIds:t,shouldDeleteForAll:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteMessages({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&m({"@type":"deleteMessages",ids:t,...i&&{chatId:e.id}})}async function E({chat:e,messageIds:t}){await Object(r.g)(new s.Api.messages.DeleteScheduledMessages({peer:Object(u.i)(e.id,e.accessHash),id:t}))&&m({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function R({chat:e,shouldDeleteForAll:t,maxId:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n}):new s.Api.messages.DeleteHistory({peer:Object(u.i)(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&m({"@type":"deleteHistory",chatId:e.id})}async function U({chat:e,threadId:t,maxId:n}){const a="channel"===Object(u.s)(e.id);a&&t===i.MAIN_THREAD_ID?await Object(r.g)(new s.Api.channels.ReadHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n})):a?await Object(r.g)(new s.Api.messages.ReadDiscussion({peer:Object(u.i)(e.id,e.accessHash),msgId:t,readMaxId:n})):await Object(r.g)(new s.Api.messages.ReadHistory({peer:Object(u.i)(e.id,e.accessHash),maxId:n})),t===i.MAIN_THREAD_ID?Object(h.u)(e):T({chat:e,threadId:t})}async function O({chat:e,messageIds:t}){const n="channel"===Object(u.s)(e.id);await Object(r.g)(n?new s.Api.channels.ReadMessageContents({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.ReadMessageContents({id:t})),m({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function T({chat:e,threadId:t}){const[n,i]=await Promise.all([Object(r.g)(new s.Api.messages.GetDiscussionMessage({peer:Object(u.i)(e.id,e.accessHash),msgId:t})),Object(r.g)(new s.Api.messages.GetReplies({peer:Object(u.i)(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=Object(p.c)(n.messages[0]);if(!a)return;m({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:i instanceof s.Api.messages.ChannelMessages?i.count:void 0},firstMessageId:i&&"messages"in i&&i.messages.length?i.messages[0].id:void 0});n.chats.map(e=>Object(l.d)(e)).filter(Boolean).forEach(e=>{m({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})}async function D({chatOrUser:e,type:t,query:n,topMessageId:i,minDate:a,maxDate:d,...l}){let f;switch(t){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"profilePhoto":f=new s.Api.InputMessagesFilterChatPhotos;break;case"text":default:f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:f,q:n||"",topMsgId:i,minDate:a,maxDate:d,...l}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K(p);const g=p.messages.map(o.b).filter(Boolean),h=p.users.map(c.a).filter(Boolean);let m,y=g.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(y=p.count,g.length&&(m=g[g.length-1].id)),{messages:g,users:h,totalCount:y,nextOffsetId:m}}async function B({query:e,offsetRate:t=0,limit:n,type:i="text",minDate:u,maxDate:d}){let f;switch(i){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"text":default:if(!(e||d&&u))return;f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new s.Api.InputPeerEmpty,limit:n,filter:f,folderId:a.a,minDate:u,maxDate:d}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K({chats:p.chats,users:p.users,messages:p.messages});const g=p.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=p.users.map(c.a).filter(Boolean),m=p.messages.map(o.b).filter(Boolean);let y,b=m.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(b=p.count,m.length&&(y=m[m.length-1].id)),{messages:m,users:h,chats:g,totalCount:b,nextRate:"nextRate"in p&&p.nextRate?p.nextRate:y}}async function x({message:e}){const t=await Object(r.g)(new s.Api.messages.GetWebPagePreview({message:e}));return t&&Object(o.n)(t)}async function j({chat:t,messageId:n,options:i}){const{id:a,accessHash:o}=t;await Object(r.g)(new s.Api.messages.SendVote({peer:Object(u.i)(a,o),msgId:n,options:i.map(t=>e.from(t))}),!0)}async function N({chat:t,messageId:n,option:i,offset:a,limit:o,shouldResetVoters:d}){const{id:l,accessHash:f}=t,p=await Object(r.g)(new s.Api.messages.GetPollVotes({peer:Object(u.i)(l,f),id:n,...i&&{option:e.from(i)},...a&&{offset:a},...o&&{limit:o}}));if(!p)return;K({chats:[],users:p.users,messages:[]});const g=p.users.map(c.a).filter(Boolean),h=p.votes.map(e=>({userId:e.userId,date:e.date}));return{count:p.count,votes:h,users:g,nextOffset:p.nextOffset,shouldResetVoters:d}}async function V({fromChat:e,toChat:t,messages:n}){const i=n.map(({id:e})=>e),a=n.map(u.r);n.forEach((e,n)=>{const s=Object(o.f)(t,e);d.a.localMessages[String(a[n])]=s,m({"@type":"newMessage",id:s.id,chatId:t.id,message:s})}),await Object(r.g)(new s.Api.messages.ForwardMessages({fromPeer:Object(u.i)(e.id,e.accessHash),toPeer:Object(u.i)(t.id,t.accessHash),randomId:a,id:i}),!0)}async function F({chat:e,timestamp:t}){const n=await Object(r.g)(new s.Api.messages.GetHistory({peer:Object(u.i)(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof s.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function L({chat:e,hash:t=0}){const{id:n,accessHash:i}=e,a=await Object(r.g)(new s.Api.messages.GetScheduledHistory({peer:Object(u.i)(n,i),hash:t}));if(!a||a instanceof s.Api.messages.MessagesNotModified||!a.messages)return;K(a);const c=a.messages.map(o.b).filter(Boolean);return{messages:c,hash:Object(u.q)(c.map(e=>e.id))}}async function q({chat:e,ids:t}){const{id:n,accessHash:i}=e;await Object(r.g)(new s.Api.messages.SendScheduledMessages({peer:Object(u.i)(n,i),id:t}),!0)}function H({chat:e,message:t}){return Object(r.g)(new s.Api.channels.ExportMessageLink({id:t.id,channel:Object(u.g)(e.id,e.accessHash),...t.isInAlbum&&{grouped:!0},...t.threadInfo&&t.threadInfo.topMessageId!==t.id&&{thread:!0}}))}function K(e){e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),e.messages.forEach(e=>{(e instanceof s.Api.Message&&Object(u.t)(e)||e instanceof s.Api.MessageService&&Object(u.u)(e))&&Object(p.a)(e)})}async function z({chat:e}){const t=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:new s.Api.InputMessagesFilterPinned,q:"",limit:a.t}));if(!t||t instanceof s.Api.messages.MessagesNotModified||!t.messages)return;K(t);return{messages:t.messages.map(o.b).filter(Boolean),users:t.users.map(c.a).filter(Boolean),chats:t.chats.map(e=>Object(l.d)(e)).filter(Boolean)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";var s=n(64);n.o(s,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return s.ApiMediaFormat})),n.o(s,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return s.ApiMessageEntityTypes})),n.o(s,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return s.MAIN_THREAD_ID})),n.o(s,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return s.MESSAGE_DELETED}));var i=n(65);n.o(i,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return i.ApiMediaFormat})),n.o(i,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return i.ApiMessageEntityTypes})),n.o(i,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return i.MAIN_THREAD_ID})),n.o(i,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return i.MESSAGE_DELETED}));var a=n(66);n.d(t,"ApiMessageEntityTypes",(function(){return a.a})),n.d(t,"MAIN_THREAD_ID",(function(){return a.b})),n.d(t,"MESSAGE_DELETED",(function(){return a.c}));var r=n(67);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat}));var o=n(68);n.d(t,"ApiMediaFormat",(function(){return o.a}));n(69),n(70),n(71)},function(e,t,n){"use strict";(function(e){var s=n(73),i=n(74),a=n(75);function r(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(r()=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(s)return F(e).length;t=(""+t).toLowerCase(),s=!0}}function h(e,t,n){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function m(e,t,n){var s=e[t];e[t]=e[n],e[n]=s}function y(e,t,n,s,i){if(0===e.length)return-1;if("string"==typeof n?(s=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,s)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,s,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,s,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,s,i){var a,r=1,o=e.length,c=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;r=2,o/=2,c/=2,n/=2}function u(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(i){var d=-1;for(a=n;ao&&(n=o-c),a=n;a>=0;a--){for(var l=!0,f=0;fi&&(s=i):s=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");s>a/2&&(s=a/2);for(var r=0;r>8,i=n%256,a.push(i),a.push(s);return a}(t,e.length-n),e,n,s)}function C(e,t,n){return 0===t&&n===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,n))}function S(e,t,n){n=Math.min(e.length,n);for(var s=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+l<=n)switch(l){case 1:u<128&&(d=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(d=c);break;case 3:a=e[i+1],r=e[i+2],128==(192&a)&&128==(192&r)&&(c=(15&u)<<12|(63&a)<<6|63&r)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:a=e[i+1],r=e[i+2],o=e[i+3],128==(192&a)&&128==(192&r)&&128==(192&o)&&(c=(15&u)<<18|(63&a)<<12|(63&r)<<6|63&o)>65535&&c<1114112&&(d=c)}null===d?(d=65533,l=1):d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|1023&d),s.push(d),i+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",s=0;for(;s0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,s,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||n>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=n)return 0;if(s>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(i>>>=0)-(s>>>=0),r=(n>>>=0)-(t>>>=0),o=Math.min(a,r),u=this.slice(s,i),d=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var a=!1;;)switch(s){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return v(this,e,t,n);case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(e,t,n){var s="";n=Math.min(e.length,n);for(var i=t;is)&&(n=s);for(var i="",a=t;an)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,s,i,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function T(e,t,n,s){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-n,2);i>>8*(s?i:1-i)}function D(e,t,n,s){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-n,4);i>>8*(s?i:3-i)&255}function B(e,t,n,s,i,a){if(n+s>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function x(e,t,n,s,a){return a||B(e,0,n,4),i.write(e,t,n,s,23,4),n+4}function j(e,t,n,s,a){return a||B(e,0,n,8),i.write(e,t,n,s,52,8),n+8}c.prototype.slice=function(e,t){var n,s=this.length;if((e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(t=void 0===t?s:~~t)<0?(t+=s)<0&&(t=0):t>s&&(t=s),t0&&(i*=256);)s+=this[e+--t]*i;return s},c.prototype.readUInt8=function(e,t){return t||U(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||U(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||U(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=this[e],i=1,a=0;++a=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=t,i=1,a=this[e+--s];s>0&&(i*=256);)a+=this[e+--s]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||U(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||U(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,s){(e=+e,t|=0,n|=0,s)||O(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=0,r=1,o=0;for(this[t]=255&e;++a>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=n-1,r=1,o=0;for(this[t+a]=255&e;--a>=0&&(r*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/r>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,s){if(n||(n=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(a<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(r+1===s){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function L(e){return s.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,s){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(43))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return o}));var s=n(0);function i(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:i}=e;return{...a(e.user),fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,...i&&{botDescription:i.description}}}}function a(e){if(!(e instanceof s.Api.User))return;const{id:t,firstName:n,lastName:i}=e,a=e.photo instanceof s.Api.UserProfilePhoto?String(e.photo.photoId):void 0;return{id:t,isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:r(e),...n&&{firstName:n},...i&&{lastName:i},username:e.username||"",phoneNumber:e.phone||"",status:o(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a}}}function r(e){return e.bot?"userTypeBot":e.deleted?"userTypeDeleted":"userTypeRegular"}function o(e){return!e||e instanceof s.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof s.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof s.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof s.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof s.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}},function(e,t,n){"use strict";function s(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function i(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),{})}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a}))},function(e,t,n){(function(e){var s,i=function(e){"use strict";var t=1e7,n=9007199254740992,s=l(n),a="function"==typeof BigInt;function r(e,t,n,s){return void 0===e?r[0]:void 0!==t&&(10!=+t||n)?F(e,t,n,s):z(e)}function o(e,t){this.value=e,this.sign=t,this.isSmall=!1}function c(e){this.value=e,this.sign=e<0,this.isSmall=!0}function u(e){this.value=e}function d(e){return-n0?Math.floor(e):Math.ceil(e)}function m(e,n){var s,i,a=e.length,r=n.length,o=new Array(a),c=0,u=t;for(i=0;i=u?1:0,o[i]=s-c*u;for(;i0&&o.push(c),o}function y(e,t){return e.length>=t.length?m(e,t):m(t,e)}function b(e,n){var s,i,a=e.length,r=new Array(a),o=t;for(i=0;i0;)r[i++]=n%o,n=Math.floor(n/o);return r}function _(e,t){var n,s,i=e.length,a=t.length,r=new Array(i),o=0;for(n=0;n0;)r[i++]=c%o,c=Math.floor(c/o);return r}function I(e,t){for(var n=[];t-- >0;)n.push(0);return n.concat(e)}function P(e,n,s){return new o(e=0;--n)i=(a=1e7*i+e[n])-(s=h(a/t))*t,o[n]=0|s;return[o,0|i]}function M(e,n){var s,i=z(n);if(a)return[new u(e.value/i.value),new u(e.value%i.value)];var d,m=e.value,y=i.value;if(0===y)throw new Error("Cannot divide by zero");if(e.isSmall)return i.isSmall?[new c(h(m/y)),new c(m%y)]:[r[0],e];if(i.isSmall){if(1===y)return[e,r[0]];if(-1==y)return[e.negate(),r[0]];var b=Math.abs(y);if(b=0;i--){for(s=p-1,b[i+l]!==m&&(s=Math.floor((b[i+l]*p+b[i+l-1])/m)),a=0,r=0,c=_.length,o=0;oc&&(i=1e7*(i+1)),n=Math.ceil(i/a);do{if(k(r=A(t,n),d)<=0)break;n--}while(n);u.push(n),d=_(d,r)}return u.reverse(),[f(u),f(d)]}(m,y))[0];var I=e.sign!==i.sign,P=s[1],C=e.sign;return"number"==typeof d?(I&&(d=-d),d=new c(d)):d=new o(d,I),"number"==typeof P?(C&&(P=-P),P=new c(P)):P=new o(P,C),[d,P]}function k(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}function E(e){var t=e.abs();return!t.isUnit()&&(!!(t.equals(2)||t.equals(3)||t.equals(5))||!(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))&&(!!t.lesser(49)||void 0))}function R(e,t){for(var n,s,a,r=e.prev(),o=r,c=0;o.isEven();)o=o.divide(2),c++;e:for(s=0;s=0?s=_(e,t):(s=_(t,e),n=!n),"number"==typeof(s=f(s))?(n&&(s=-s),new c(s)):new o(s,n)}(n,s,this.sign)},o.prototype.minus=o.prototype.subtract,c.prototype.subtract=function(e){var t=z(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var s=t.value;return t.isSmall?new c(n-s):w(s,Math.abs(n),n>=0)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(e){return new u(this.value-z(e).value)},u.prototype.minus=u.prototype.subtract,o.prototype.negate=function(){return new o(this.value,!this.sign)},c.prototype.negate=function(){var e=this.sign,t=new c(-this.value);return t.sign=!e,t},u.prototype.negate=function(){return new u(-this.value)},o.prototype.abs=function(){return new o(this.value,!1)},c.prototype.abs=function(){return new c(Math.abs(this.value))},u.prototype.abs=function(){return new u(this.value>=0?this.value:-this.value)},o.prototype.multiply=function(e){var n,s,i,a=z(e),c=this.value,u=a.value,d=this.sign!==a.sign;if(a.isSmall){if(0===u)return r[0];if(1===u)return this;if(-1===u)return this.negate();if((n=Math.abs(u))0?function e(t,n){var s=Math.max(t.length,n.length);if(s<=30)return v(t,n);s=Math.ceil(s/2);var i=t.slice(s),a=t.slice(0,s),r=n.slice(s),o=n.slice(0,s),c=e(a,o),u=e(i,r),d=e(y(a,i),y(o,r)),l=y(y(c,I(_(_(d,c),u),s)),I(u,2*s));return p(l),l}(c,u):v(c,u),d)},o.prototype.times=o.prototype.multiply,c.prototype._multiplyBySmall=function(e){return d(e.value*this.value)?new c(e.value*this.value):P(Math.abs(e.value),l(Math.abs(this.value)),this.sign!==e.sign)},o.prototype._multiplyBySmall=function(e){return 0===e.value?r[0]:1===e.value?this:-1===e.value?this.negate():P(Math.abs(e.value),this.value,this.sign!==e.sign)},c.prototype.multiply=function(e){return z(e)._multiplyBySmall(this)},c.prototype.times=c.prototype.multiply,u.prototype.multiply=function(e){return new u(this.value*z(e).value)},u.prototype.times=u.prototype.multiply,o.prototype.square=function(){return new o(C(this.value),!1)},c.prototype.square=function(){var e=this.value*this.value;return d(e)?new c(e):new o(C(l(Math.abs(this.value))),!1)},u.prototype.square=function(e){return new u(this.value*this.value)},o.prototype.divmod=function(e){var t=M(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=c.prototype.divmod=o.prototype.divmod,o.prototype.divide=function(e){return M(this,e)[0]},u.prototype.over=u.prototype.divide=function(e){return new u(this.value/z(e).value)},c.prototype.over=c.prototype.divide=o.prototype.over=o.prototype.divide,o.prototype.mod=function(e){return M(this,e)[1]},u.prototype.mod=u.prototype.remainder=function(e){return new u(this.value%z(e).value)},c.prototype.remainder=c.prototype.mod=o.prototype.remainder=o.prototype.mod,o.prototype.pow=function(e){var t,n,s,i=z(e),a=this.value,o=i.value;if(0===o)return r[1];if(0===a)return r[0];if(1===a)return r[1];if(-1===a)return i.isEven()?r[1]:r[-1];if(i.sign)return r[0];if(!i.isSmall)throw new Error("The exponent "+i.toString()+" is too large.");if(this.isSmall&&d(t=Math.pow(a,o)))return new c(h(t));for(n=this,s=r[1];!0&o&&(s=s.times(n),--o),0!==o;)o/=2,n=n.square();return s},c.prototype.pow=o.prototype.pow,u.prototype.pow=function(e){var t=z(e),n=this.value,s=t.value,i=BigInt(0),a=BigInt(1),o=BigInt(2);if(s===i)return r[1];if(n===i)return r[0];if(n===a)return r[1];if(n===BigInt(-1))return t.isEven()?r[1]:r[-1];if(t.isNegative())return new u(i);for(var c=this,d=r[1];(s&a)===a&&(d=d.times(c),--s),s!==i;)s/=o,c=c.square();return d},o.prototype.modPow=function(e,t){if(e=z(e),(t=z(t)).isZero())throw new Error("Cannot take modPow with modulus 0");var n=r[1],s=this.mod(t);for(e.isNegative()&&(e=e.multiply(r[-1]),s=s.modInv(t));e.isPositive();){if(s.isZero())return r[0];e.isOdd()&&(n=n.multiply(s).mod(t)),e=e.divide(2),s=s.square().mod(t)}return n},u.prototype.modPow=c.prototype.modPow=o.prototype.modPow,o.prototype.compareAbs=function(e){var t=z(e),n=this.value,s=t.value;return t.isSmall?1:k(n,s)},c.prototype.compareAbs=function(e){var t=z(e),n=Math.abs(this.value),s=t.value;return t.isSmall?n===(s=Math.abs(s))?0:n>s?1:-1:-1},u.prototype.compareAbs=function(e){var t=this.value,n=z(e).value;return(t=t>=0?t:-t)===(n=n>=0?n:-n)?0:t>n?1:-1},o.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:k(n,s)*(this.sign?-1:1)},o.prototype.compareTo=o.prototype.compare,c.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return t.isSmall?n==s?0:n>s?1:-1:n<0!==t.sign?n<0?-1:1:n<0?1:-1},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,n=z(e).value;return t===n?0:t>n?1:-1},u.prototype.compareTo=u.prototype.compare,o.prototype.equals=function(e){return 0===this.compare(e)},u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals=o.prototype.eq=o.prototype.equals,o.prototype.notEquals=function(e){return 0!==this.compare(e)},u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals=o.prototype.neq=o.prototype.notEquals,o.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater=o.prototype.gt=o.prototype.greater,o.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser=o.prototype.lt=o.prototype.lesser,o.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals=o.prototype.geq=o.prototype.greaterOrEquals,o.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals=o.prototype.leq=o.prototype.lesserOrEquals,o.prototype.isEven=function(){return 0==(1&this.value[0])},c.prototype.isEven=function(){return 0==(1&this.value)},u.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},o.prototype.isOdd=function(){return 1==(1&this.value[0])},c.prototype.isOdd=function(){return 1==(1&this.value)},u.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},o.prototype.isPositive=function(){return!this.sign},c.prototype.isPositive=function(){return this.value>0},u.prototype.isPositive=c.prototype.isPositive,o.prototype.isNegative=function(){return this.sign},c.prototype.isNegative=function(){return this.value<0},u.prototype.isNegative=c.prototype.isNegative,o.prototype.isUnit=function(){return!1},c.prototype.isUnit=function(){return 1===Math.abs(this.value)},u.prototype.isUnit=function(){return this.abs().value===BigInt(1)},o.prototype.isZero=function(){return!1},c.prototype.isZero=function(){return 0===this.value},u.prototype.isZero=function(){return this.value===BigInt(0)},o.prototype.isDivisibleBy=function(e){var t=z(e);return!t.isZero()&&(!!t.isUnit()||(0===t.compareAbs(2)?this.isEven():this.mod(t).isZero()))},u.prototype.isDivisibleBy=c.prototype.isDivisibleBy=o.prototype.isDivisibleBy,o.prototype.isPrime=function(e){var t=E(this);if(void 0!==t)return t;var n=this.abs(),s=n.bitLength();if(s<=64)return R(n,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var a=Math.log(2)*s.toJSNumber(),r=Math.ceil(!0===e?2*Math.pow(a,2):a),o=[],c=0;c-n?new c(e-1):new o(s,!0)},u.prototype.prev=function(){return new u(this.value-BigInt(1))};for(var U=[1];2*U[U.length-1]<=t;)U.push(2*U[U.length-1]);var O=U.length,T=U[O-1];function D(e){return Math.abs(e)<=t}function B(e,t,n){t=z(t);for(var s=e.isNegative(),a=t.isNegative(),r=s?e.not():e,o=a?t.not():t,c=0,u=0,d=null,l=null,f=[];!r.isZero()||!o.isZero();)c=(d=M(r,T))[1].toJSNumber(),s&&(c=T-1-c),u=(l=M(o,T))[1].toJSNumber(),a&&(u=T-1-u),r=d[0],o=l[0],f.push(n(c,u));for(var p=0!==n(s?1:0,a?1:0)?i(-1):i(0),g=f.length-1;g>=0;g-=1)p=p.multiply(T).add(i(f[g]));return p}o.prototype.shiftLeft=function(e){var t=z(e).toJSNumber();if(!D(t))throw new Error(String(t)+" is too large for shifting.");if(t<0)return this.shiftRight(-t);var n=this;if(n.isZero())return n;for(;t>=O;)n=n.multiply(T),t-=O-1;return n.multiply(U[t])},u.prototype.shiftLeft=function(e){return e=z(e),new u(this.value<=O;){if(s.isZero()||s.isNegative()&&s.isUnit())return s;s=(t=M(s,T))[1].isNegative()?t[0].prev():t[0],n-=O-1}return(t=M(s,U[n]))[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=function(e){return e=z(e),new u(this.value>>e.value)},c.prototype.shiftRight=o.prototype.shiftRight,o.prototype.not=function(){return this.negate().prev()},u.prototype.not=c.prototype.not=o.prototype.not,o.prototype.and=function(e){return B(this,e,(function(e,t){return e&t}))},u.prototype.and=c.prototype.and=o.prototype.and,o.prototype.or=function(e){return B(this,e,(function(e,t){return e|t}))},u.prototype.or=c.prototype.or=o.prototype.or,o.prototype.xor=function(e){return B(this,e,(function(e,t){return e^t}))},u.prototype.xor=c.prototype.xor=o.prototype.xor;function x(e){var n=e.value,s="number"==typeof n?n|1<<30:"bigint"==typeof n?n|BigInt(1<<30):n[0]+n[1]*t|1073758208;return s&-s}function j(e,t){return e=z(e),t=z(t),e.greater(t)?e:t}function N(e,t){return e=z(e),t=z(t),e.lesser(t)?e:t}function V(e,t){if(e=z(e).abs(),t=z(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var n,s,i=r[1];e.isEven()&&t.isEven();)n=N(x(e),x(t)),e=e.divide(n),t=t.divide(n),i=i.multiply(n);for(;e.isEven();)e=e.divide(x(e));do{for(;t.isEven();)t=t.divide(x(t));e.greater(t)&&(s=t,t=e,e=s),t=t.subtract(e)}while(!t.isZero());return i.isUnit()?e:e.multiply(i)}o.prototype.bitLength=function(){var e=this;return e.compareTo(i(0))<0&&(e=e.negate().subtract(i(1))),0===e.compareTo(i(0))?i(0):i(function e(t,n){if(n.compareTo(t)<=0){var s=e(t,n.square(n)),a=s.p,r=s.e,o=a.multiply(n);return o.compareTo(t)<=0?{p:o,e:2*r+1}:{p:a,e:2*r}}return{p:i(1),e:0}}(e,i(2)).e).add(i(1))},u.prototype.bitLength=c.prototype.bitLength=o.prototype.bitLength;var F=function(e,t,n,s){n=n||"0123456789abcdefghijklmnopqrstuvwxyz",e=String(e),s||(e=e.toLowerCase(),n=n.toLowerCase());var i,a=e.length,r=Math.abs(t),o={};for(i=0;i=r)){if("1"===d&&1===r)continue;throw new Error(d+" is not a valid digit in base "+t+".")}}t=z(t);var c=[],u="-"===e[0];for(i=u?1:0;i"!==e[i]&&i=0;s--)i=i.add(e[s].times(a)),a=a.times(t);return n?i.negate():i}function q(e,t){if((t=i(t)).isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var n=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return n.unshift([1]),{value:[].concat.apply([],n),isNegative:!1}}var s=!1;if(e.isNegative()&&t.isPositive()&&(s=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:s};for(var a,r=[],o=e;o.isNegative()||o.compareAbs(t)>=0;){a=o.divmod(t),o=a.quotient;var c=a.remainder;c.isNegative()&&(c=t.minus(c).abs(),o=o.next()),r.push(c.toJSNumber())}return r.push(o.toJSNumber()),{value:r.reverse(),isNegative:s}}function H(e,t,n){var s=q(e,t);return(s.isNegative?"-":"")+s.value.map((function(e){return function(e,t){return e<(t=t||"0123456789abcdefghijklmnopqrstuvwxyz").length?t[e]:"<"+e+">"}(e,n)})).join("")}function K(e){if(d(+e)){var t=+e;if(t===h(t))return a?new u(BigInt(t)):new c(t);throw new Error("Invalid integer: "+e)}var n="-"===e[0];n&&(e=e.slice(1));var s=e.split(/e/i);if(s.length>2)throw new Error("Invalid integer: "+s.join("e"));if(2===s.length){var i=s[1];if("+"===i[0]&&(i=i.slice(1)),(i=+i)!==h(i)||!d(i))throw new Error("Invalid integer: "+i+" is not a valid exponent.");var r=s[0],l=r.indexOf(".");if(l>=0&&(i-=r.length-l-1,r=r.slice(0,l)+r.slice(l+1)),i<0)throw new Error("Cannot include negative exponent part for integers");e=r+=new Array(i+1).join("0")}if(!/^([0-9][0-9]*)$/.test(e))throw new Error("Invalid integer: "+e);if(a)return new u(BigInt(n?"-"+e:e));for(var f=[],g=e.length,m=g-7;g>0;)f.push(+e.slice(m,g)),(m-=7)<0&&(m=0),g-=7;return p(f),new o(f,n)}function z(e){return"number"==typeof e?function(e){if(a)return new u(BigInt(e));if(d(e)){if(e!==h(e))throw new Error(e+" is not an integer.");return new c(e)}return K(e.toString())}(e):"string"==typeof e?K(e):"bigint"==typeof e?new u(e):e}o.prototype.toArray=function(e){return q(this,e)},c.prototype.toArray=function(e){return q(this,e)},u.prototype.toArray=function(e){return q(this,e)},o.prototype.toString=function(e,t){if(void 0===e&&(e=10),10!==e)return H(this,e,t);for(var n,s=this.value,i=s.length,a=String(s[--i]);--i>=0;)n=String(s[i]),a+="0000000".slice(n.length)+n;return(this.sign?"-":"")+a},c.prototype.toString=function(e,t){return void 0===e&&(e=10),10!=e?H(this,e,t):String(this.value)},u.prototype.toString=c.prototype.toString,u.prototype.toJSON=o.prototype.toJSON=c.prototype.toJSON=function(){return this.toString()},o.prototype.valueOf=function(){return parseInt(this.toString(),10)},o.prototype.toJSNumber=o.prototype.valueOf,c.prototype.valueOf=function(){return this.value},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=u.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var G=0;G<1e3;G++)r[G]=z(G),G>0&&(r[-G]=z(-G));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=j,r.min=N,r.gcd=V,r.lcm=function(e,t){return e=z(e).abs(),t=z(t).abs(),e.divide(V(e,t)).multiply(t)},r.isInstance=function(e){return e instanceof o||e instanceof c||e instanceof u},r.randBetween=function(e,n,s){e=z(e),n=z(n);var i=s||Math.random,a=N(e,n),o=j(e,n).subtract(a).add(1);if(o.isSmall)return a.add(Math.floor(i()*o));for(var c=q(o,t).value,u=[],d=!0,l=0;l{r.resolve=e,r.reject=t})}function d(e=!1){return o({...y("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise((e,t)=>{r.resolve=e,r.reject=t})}function l(e){return o({...y("authorizationStateWaitPassword"),hint:e}),new Promise(e=>{r.resolve=e})}function f(){return o(y("authorizationStateWaitRegistration")),new Promise(e=>{r.resolve=e})}function p(e){return o({...y("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise((e,t)=>{r.reject=t})}function g(e){let t;if(e instanceof s.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=a[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),o({"@type":"updateAuthorizationError",message:t})}function h(){o(y("authorizationStateReady"))}function m(e){o({"@type":"updateCurrentUser",currentUser:e})}function y(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function b(e){r.resolve&&r.resolve(e)}function _(e){r.resolve&&r.resolve(e)}function w(e){r.resolve&&r.resolve(e)}function v(e){const{firstName:t,lastName:n}=e;r.resolve&&r.resolve([t,n])}function A(){r.reject&&r.reject(new Error("RESTART_AUTH"))}function I(){r.reject&&r.reject(new Error("RESTART_AUTH_WITH_QR"))}},function(e,t,n){"use strict";function s(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function i(e){if(!e)return;const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:i,classType:a,...r}=e;return r}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i}))},function(e,t,n){"use strict";n.d(t,"e",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return f}));var s=n(0),i=n(20),a=n(18);function r(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 o={w:100,h:100};function c(e,t){if(!e||!e.length)return;const n=e.find(e=>e instanceof s.Api.PhotoStrippedSize);if(!n)return;const r=e.filter(e=>e instanceof s.Api.PhotoSize),{w:c,h:u}=r&&r.length?r[r.length-1]:o,{bytes:d}=n;return{dataUri:Object(a.a)(t&&"image/jpeg"!==t?d:Object(i.strippedPhotoToJpg)(d),void 0,t),width:c,height:u}}function u(e){const{w:t,h:n,bytes:s}=e;return{dataUri:Object(a.a)(s,void 0,"image/webp"),width:t,height:n}}function d(e,t){const{w:n,h:s}=t;return{dataUri:"data:image/svg+xml;utf8,"+r(e.bytes,n,s),width:n,height:s}}function l(e){const t=e.sizes.filter(e=>e instanceof s.Api.PhotoSize||e instanceof s.Api.PhotoSizeProgressive).map(f);return{id:String(e.id),thumbnail:c(e.sizes),sizes:t}}function f(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}},function(e,t,n){(function(t){const{constructors:s}=n(21),i=t.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),a=t.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error("Invalid message type: "+e.constructor.name)}},getInputPeer:function e(t,n=!0,i=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof s.User){if(t.isSelf&&n)return new s.InputPeerSelf;if(void 0===t.accessHash&&i)throw new Error("User without accessHash or min info cannot be input");return new s.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof s.Chat||t instanceof s.ChatEmpty||t instanceof s.ChatForbidden)return new s.InputPeerChat({chatId:t.id});if(t instanceof s.Channel){if(void 0===t.accessHash&&i)throw new TypeError("Channel without accessHash or min info cannot be input");return new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof s.ChannelForbidden?new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof s.InputUser?new s.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof s.InputChannel?new s.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof s.UserEmpty?new s.InputPeerEmpty:t instanceof s.UserFull?e(t.user):t instanceof s.ChatFull?new s.InputPeerChat({chatId:t.id}):t instanceof s.PeerChat?new s.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof s.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof s.Chat||e instanceof s.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=1572864e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const n=t.from(i);return n[164]=e[1],n[166]=e[2],t.concat([n,e.slice(3),a])},getDC:function(e){switch(e){case 1:return{id:1,ipAddress:"pluto.web.telegram.org",port:443};case 2:return{id:2,ipAddress:"venus.web.telegram.org",port:443};case 3:return{id:3,ipAddress:"aurora.web.telegram.org",port:443};case 4:return{id:4,ipAddress:"vesta.web.telegram.org",port:443};case 5:return{id:5,ipAddress:"flora.web.telegram.org",port:443};default:throw new Error("Cannot find the DC with the ID of "+e)}}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(6),{serializeBytes:i,serializeDate:a}=n(44);e.exports={constructors:s,requests:s,serializeBytes:i,serializeDate:a}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return u}));var s=n(0),i=n(4),a=n(19),r=n(5);function o(e){if(e instanceof s.Api.DocumentEmpty)return;const t=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeSticker);if(!t)return;const n=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeImageSize),r=t.stickerset,o=t.alt,c="application/x-tgsticker"===e.mimeType,u=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoCachedSize),d=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoPathSize),l=u?Object(a.c)(u):d&&n?Object(a.d)(d,n):void 0,{w:f,h:p}=u||n||{};return{id:String(e.id),stickerSetId:r.id?String(r.id):i.s,stickerSetAccessHash:String(r.accessHash),emoji:o,isAnimated:c,width:f,height:p,thumbnail:l}}function c(e){const{archived:t,animated:n,installedDate:s,id:i,accessHash:a,title:r,thumbs:o,count:c,hash:u}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(i),accessHash:String(a),title:r,hasThumbnail:Boolean(o&&o.length),count:c,hash:u}}function u(e){const t=c(e.set),n=e instanceof s.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach(e=>{if(e instanceof s.Api.Document){const n=o(e);n&&(t.covers.push(n),r.a.documents[String(e.id)]=e)}}),t}},function(e,t){class n extends Error{constructor(){super("The read operation was cancelled.")}}class s 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 i 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 r extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=" Caused by "+e.className,super(n),this.message=n,this.code=t}}var c,u,d;d={16:"msg_id too low (most likely, client time is wrong it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted).",17:"msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",32:"msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno).",33:"msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",48:"Incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it).",64:"Invalid container."},(u="ErrorMessages")in(c=o)?Object.defineProperty(c,u,{value:d,enumerable:!0,configurable:!0,writable:!0}):c[u]=d,e.exports={ReadCancelledError:n,TypeNotFoundError:s,InvalidChecksumError:i,InvalidBufferError:a,SecurityError:r,CdnFileTamperedError:class extends r{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return u}));var s=n(0),i=n(9),a=n(14);function r(e){if(e instanceof s.Api.WallPaperNoFile)return;const{slug:t}=e,n=Object(i.a)(e.document);return n?{slug:t,document:n}:void 0}function o(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...Object(a.b)(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function c(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}function u(e){let t,n,i,a,r;return e.forEach(e=>{e instanceof s.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof s.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof s.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof s.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof s.Api.PrivacyValueAllowUsers?n=e.users:e instanceof s.Api.PrivacyValueDisallowUsers?a=e.users:e instanceof s.Api.PrivacyValueAllowChatParticipants?i=e.chats.map(e=>-e):e instanceof s.Api.PrivacyValueDisallowChatParticipants&&(r=e.chats.map(e=>-e))}),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:i||[],blockUserIds:a||[],blockChatIds:r||[]}}},function(e,t,n){const{TypeNotFoundError:s}=n(23),{coreObjects:i}=n(54),{tlobjects:a}=n(49),{readBigIntFromBuffer:r}=n(8);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return r(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error("Invalid boolean code "+e.toString("16"))}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=a[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;ne instanceof s.Api.User).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}),n.filter(e=>e instanceof s.Api.Chat||e instanceof s.Api.Channel).map(e=>Object(r.d)(e)).forEach(e=>{e&&h({"@type":"updateChat",id:e.id,chat:e})})),e instanceof s.Api.UpdateNewScheduledMessage?h({"@type":y.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):h({"@type":y.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t}),e.message instanceof s.Api.MessageService){const{action:n}=e.message;if(n instanceof s.Api.MessageActionChatEditTitle)h({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof s.Api.MessageActionChatEditPhoto){const i=Object(c.c)(n.photo),a=Object(r.e)(i),o=Math.abs(Object(f.c)(e.message));u.a.chats[o]&&(u.a.chats[o].photo=i),Object(f.b)(n.photo),a&&h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof s.Api.Photo&&{newProfilePhoto:Object(g.a)(n.photo)}})}else if(n instanceof s.Api.MessageActionChatDeletePhoto){const n=Math.abs(Object(f.c)(e.message));u.a.chats[n]&&(u.a.chats[n].photo=new s.Api.ChatPhotoEmpty),h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof s.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&e.id===n.userId)&&h({"@type":"updateChatLeave",id:t.chatId}):n instanceof s.Api.MessageActionChatAddUser&&e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&n.users.includes(e.id))&&h({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof s.Api.UpdateEditMessage||e instanceof s.Api.UpdateEditChannelMessage){if(e.message instanceof s.Api.MessageEmpty)return void(l.g&&console.error("Unexpected update:",e.className,e));e.message instanceof s.Api.Message&&Object(c.t)(e.message)&&Object(f.a)(e.message);const t=Object(a.b)(e.message);h({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof s.Api.UpdateDeleteMessages)h({"@type":"deleteMessages",ids:e.messages});else if(e instanceof s.Api.UpdateDeleteScheduledMessages)h({"@type":"deleteScheduledMessages",ids:e.messages,chatId:Object(r.i)(e.peer)});else if(e instanceof s.Api.UpdateDeleteChannelMessages){const t=Object(r.j)({channelId:e.channelId}),n=e.messages,i=n.filter(e=>u.a.messages[`${t}-${e}`]),a=n.filter(e=>!u.a.messages[`${t}-${e}`]),o=n.map(e=>{const n=u.a.messages[`${t}-${e}`];return n&&n instanceof s.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0}).filter(Boolean);i.length&&h({"@type":"deleteMessages",ids:i,chatId:t}),o.length&&h({"@type":"deleteProfilePhotos",ids:o,chatId:t}),a.length&&setTimeout(()=>{h({"@type":"deleteMessages",ids:a,chatId:t})},1e3)}else if((t instanceof s.Api.messages.SendMessage||t instanceof s.Api.messages.SendMedia||t instanceof s.Api.messages.SendMultiMedia||t instanceof s.Api.messages.ForwardMessages)&&(e instanceof s.Api.UpdateMessageID||e instanceof s.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const i=n&&u.a.localMessages[n.toString()];if(!i)throw new Error("Local message not found");let r;if(e instanceof s.Api.UpdateShortSentMessage){i.content.text&&e.entities&&(r={text:Object(a.j)(i.content.text.text,e.entities)}),e.media&&(r={...r,...Object(a.i)(e.media)});const t=Object(c.m)(e.id,i.chatId,e);Object(c.t)(t)&&Object(f.a)(t)}y.add(e.id);const o="date"in e&&1e3*e.dateString.fromCharCode(...e))});else if(e instanceof s.Api.UpdateChannelMessageViews)h({"@type":"updateMessage",chatId:Object(r.j)({channelId:e.channelId}),id:e.id,message:{views:e.views}});else if(e instanceof s.Api.UpdateReadHistoryInbox)h({"@type":"updateChatInbox",id:Object(r.j)(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadHistoryOutbox)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateReadChannelInbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadChannelOutbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateDialogPinned&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChatPinned",id:Object(r.j)(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof s.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter(e=>e instanceof s.Api.DialogPeer).map(e=>Object(r.j)(e.peer)):[];h({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof s.Api.UpdateFolderPeers)e.folderPeers.forEach(e=>{const{folderId:t,peer:n}=e;h({"@type":"updateChatListType",id:Object(r.j)(n),folderId:t})});else if(e instanceof s.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Object(r.a)(n):void 0;h({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof s.Api.UpdateDialogFilterOrder)h({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof s.Api.UpdateChatParticipants){const t=Object(r.g)(e.participants);h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.participants.chatId}),replacedMembers:t})}else if(e instanceof s.Api.UpdateChatParticipantAdd){const t=Object(r.f)(Object(i.b)(e,["userId","inviterId","date"]));h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),addedMember:t})}else if(e instanceof s.Api.UpdateChatParticipantDelete){const{userId:t}=e;h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),deletedMemberId:t})}else if(e instanceof s.Api.UpdatePinnedMessages||e instanceof s.Api.UpdatePinnedChannelMessages){const t=e instanceof s.Api.UpdatePinnedMessages?e.peer:{channelId:e.channelId},n=Object(r.j)(t);h({"@type":"updatePinnedIds",chatId:n,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof s.Api.UpdateNotifySettings&&e.peer instanceof s.Api.NotifyPeer){const{silent:t,muteUntil:n,showPreviews:s,sound:i}=e.notifySettings,a=t||"number"==typeof n&&Date.now()<1e3*n;h({"@type":"updateNotifyExceptions",id:Object(r.j)(e.peer.peer),isMuted:a,...""===i&&{isSilent:!0},...void 0!==s&&{shouldShowPreviews:Boolean(s)}})}else if(e instanceof s.Api.UpdateUserTyping||e instanceof s.Api.UpdateChatUserTyping){const t=e instanceof s.Api.UpdateUserTyping?e.userId:Object(r.j)({chatId:e.chatId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannelUserTyping){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find(e=>e instanceof s.Api.Channel||e instanceof s.Api.ChannelForbidden);if(n instanceof s.Api.Channel){const t=Object(r.d)(n);t&&(h({"@type":"updateChat",id:t.id,chat:t}),h({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:Object(r.j)({channelId:e.channelId})}))}else if(n instanceof s.Api.ChannelForbidden){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),h({"@type":"updateChatLeave",id:t})}else 0===t.length&&h({"@type":"resetMessages",id:Object(r.j)({chatId:e.channelId})})}else if(e instanceof s.Api.UpdateDialogUnreadMark&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChat",id:Object(r.j)(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof s.Api.UpdateChatDefaultBannedRights)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{defaultBannedRights:Object(d.b)(e.defaultBannedRights)}});else if(e instanceof s.Api.UpdateUserStatus){const{userId:t,status:n}=e;h({"@type":"updateUserStatus",userId:t,status:Object(o.c)(n)})}else if(e instanceof s.Api.UpdateUserName){const t=u.a.users[e.userId],n=t&&t.mutualContact&&!t.self?Object(i.b)(e,["username"]):Object(i.b)(e,["firstName","lastName","username"]);h({"@type":"updateUser",id:e.userId,user:n})}else if(e instanceof s.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=Object(r.e)(n);u.a.users[t]&&(u.a.users[t].photo=n),h({"@type":"updateUser",id:t,user:{avatarHash:s}})}else if(e instanceof s.Api.UpdateUserPhone){const{userId:t,phone:n}=e;h({"@type":"updateUser",id:t,user:{phoneNumber:n}})}else if(e instanceof s.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;t&&t.length&&(t.filter(e=>e instanceof s.Api.User&&!e.contact).forEach(e=>{h({"@type":"deleteUser",id:e.id})}),t.filter(e=>e instanceof s.Api.User&&e.contact).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}))}else if(e instanceof s.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:i}}=e,a="NotifyUsers"===i?"contact":"NotifyChats"===i?"group":"NotifyBroadcasts"===i?"broadcast":void 0;if(!a)return;h({"@type":"updateNotifySettings",peerType:a,isSilent:Boolean(n||"number"==typeof s&&Date.now()<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof s.Api.UpdatePeerBlocked)h({"@type":"updatePeerBlocked",id:Object(r.j)(e.peerId),isBlocked:e.blocked});else if(e instanceof s.Api.UpdatePrivacy){const t=Object(p.c)(e.key);t&&h({"@type":"updatePrivacy",key:t,rules:Object(p.d)(e.rules)})}else if(e instanceof s.Api.UpdateContactsReset)h({"@type":"updateResetContactList"});else if(e instanceof s.Api.UpdateFavedStickers)h({"@type":"updateFavoriteStickers"});else if(l.g){const t="object"==typeof e&&"className"in e?e.className:e;console.warn("[GramJs/updater] Unexpected update:",t)}}},function(e,t,n){const s=n(48);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}}},function(e,t,n){(function(t){const{sha1:s,toSignedLittleBuffer:i,readBufferFromBigInt:a,readBigIntFromBuffer:r}=n(8),o=n(25),{sleep:c}=n(8);class u{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new o(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 u)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await s(this._key);const t=new o(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await c(20)}getKey(){return this._key}async calcNewNonceHash(e,n){e=i(e,32);const o=t.alloc(1);o.writeUInt8(n,0);const c=t.concat([e,t.concat([o,a(this.auxHash,8,!0)])]),u=(await s(c)).slice(4,20);return r(u,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=u}).call(this,n(12).Buffer)},function(e,t,n){const{RPCError:s}=n(36),{rpcErrorRe:i}=n(47);const a=n(23),r=n(36),o=n(47);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of i){const i=e.errorMessage.match(n);if(i){return new s({request:t,capture:2===i.length?parseInt(i[1],10):void 0})}}return new s(e.errorMessage,t)},...a,...r,...o}},function(e,t,n){"use strict";function s(e,t,n=!0){let s,i,a;return(...r)=>{i=!0,a=r,s||(n&&(i=!1,e(...a)),s=self.setInterval(()=>{if(!i)return self.clearInterval(s),void(s=void 0);i=!1,e(...a)},t))}}function i(e){return a(r,e)}function a(e,t){let n,s=!1;return(...i)=>{n=i,s||(s=!0,e(()=>{s=!1,t(...n)}))}}function r(e){Promise.resolve().then(e)}n.d(t,"b",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const o=e=>new Promise(t=>{setTimeout(()=>t(),e)})},function(e,t,n){(function(t){const s=n(15),{constructors:i}=n(21),{readBigIntFromBuffer:a,readBufferFromBigInt:r,sha256:o,bigIntMod:c,modExp:u,generateRandomBytes:d}=n(8),l=n(35);function f(e,n){if(!t.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(n))throw new Error("Changing passwords unsupported")}function p(e){return t.concat([t.alloc(256-e.length),e])}function g(e){return r(e,256,!1)}function h(e,t){const n=t.subtract(e);return!(n.lesser(s(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function m(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=d(256),n=a(e,!1),i=u(s(_),n,b);if(h(i,b)){const e=g(i),r=a(await o(t.concat([e,P])),!1);if(r.greater(s(0)))return[n,e,r]}}})(),U=c(w.subtract(M),b);if(!h(U,b))throw new Error("bad gB");const O=R.multiply(v),T=k.add(O),D=u(U,T,b),[B,x,j,N,V]=await Promise.all([o(g(D)),o(A),o(I),o(r.salt1),o(r.salt2)]),F=await o(t.concat([m(x,j),N,V,E,P,B]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:t.from(E),M1:F})},computeDigest:async function(e,t){try{f(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return g(u(s(e.g),a(await y(e,t),!1),a(e.p,!1)))}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){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{inflate:i}=n(41),{serializeBytes:a}=n(21);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{const s=new FileReader;s.onload=e=>{const{result:s}=e.target||{};"string"==typeof s&&t(s),n(new Error("Failed to read blob"))},s.onerror=n,s.readAsDataURL(e)})}async function a(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}},function(e,t,n){(function(t){const s=n(45).default,{i2ab:i,ab2i:a}=n(77),{getWords:r}=n(78);class o{constructor(e){this.setBytes(e)}setBytes(e){e=t.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 c{constructor(e,t){t instanceof o||(t=new o(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new s(r(e))}update(e){return this.encrypt(e)}encrypt(e){const n=t.from(e);for(let e=0;e{s[e]&&r[e]&&(this._authKeys[e]=new i(t.from(s[e].data),t.from(r[e].data)))})}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey="GramJs-session-"+Date.now()),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(n=>{const s=this._authKeys[n];s._key&&(t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash)}),t}async _loadFromSessionString(){const[,e,n]=this._sessionString.split(":"),s=Number(e),{ipAddress:r,port:o}=a.getDC(s);this.setDC(s,r,o);const c=new i;await c.setKey(t.from(n,"hex"),!0),this.setAuthKey(c,s)}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")}}}).call(this,n(12).Buffer)},function(e,t,n){e.exports=function e(t,n,s){function i(r,o){if(!n[r]){if(!t[r]){if(a)return a(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[r]={exports:{}};t[r][0].call(u.exports,(function(e){return i(t[r][1][e]||e)}),u,u.exports,e,t,n,s)}return n[r].exports}for(var a=!1,r=0;r=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&a||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r>>6,t[r++]=128|63&n):n<65536?(t[r++]=224|n>>>12,t[r++]=128|n>>>6&63,t[r++]=128|63&n):(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63,t[r++]=128|n>>>6&63,t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n4)u[s++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?u[s++]=65533:i<65536?u[s++]=i:(i-=65536,u[s++]=55296|i>>10&1023,u[s++]=56320|1023&i)}return c(u,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,s){for(var i=65535&e|0,a=e>>>16&65535|0,r=0;0!==n;){n-=r=n>2e3?2e3:n;do{a=a+(i=i+t[s++]|0)|0}while(--r);i%=65521,a%=65521}return i|a<<16|0}},{}],4:[function(e,t,n){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){"use strict";var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=s,r=i+n;e^=-1;for(var o=i;o>>8^a[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,n){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){"use strict";t.exports=function(e,t){var n,s,i,a,r,o,c,u,d,l,f,p,g,h,m,y,b,_,w,v,A,I,P,C,S;n=e.state,s=e.next_in,C=e.input,i=s+(e.avail_in-5),a=e.next_out,S=e.output,r=a-(t-e.avail_out),o=a+(e.avail_out-257),c=n.dmax,u=n.wsize,d=n.whave,l=n.wnext,f=n.window,p=n.hold,g=n.bits,h=n.lencode,m=n.distcode,y=(1<>>=w=_>>>24,g-=w,0==(w=_>>>16&255))S[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=h[(65535&_)+(p&(1<>>=w,g-=w),g<15&&(p+=C[s++]<>>=w=_>>>24,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<c){e.msg="invalid distance too far back",n.mode=30;break e}if(p>>>=w,g-=w,A>(w=a-r)){if((w=A-w)>d&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(I=0,P=f,0===l){if(I+=u-w,w2;)S[a++]=P[I++],S[a++]=P[I++],S[a++]=P[I++],v-=3;v&&(S[a++]=P[I++],v>1&&(S[a++]=P[I++]))}else{I=a-A;do{S[a++]=S[I++],S[a++]=S[I++],S[a++]=S[I++],v-=3}while(v>2);v&&(S[a++]=S[I++],v>1&&(S[a++]=S[I++]))}break}}break}}while(s>3,p&=(1<<(g-=v<<3))-1,e.next_in=s,e.next_out=a,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(852),t.distcode=t.distdyn=new s.Buf32(592),t.sane=1,t.back=-1,0):-2}function l(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,d(e)):-2}function f(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?-2:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,l(e))):-2}function p(e,t){var n,s;return e?(s=new u,e.state=s,s.window=null,0!==(n=f(e,t))&&(e.state=null),n):-2}var g,h,m=!0;function y(e){if(m){var t;for(g=new s.Buf32(512),h=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(1,e.lens,0,288,g,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(2,e.lens,0,32,h,0,e.work,{bits:5}),m=!1}e.lencode=g,e.lenbits=9,e.distcode=h,e.distbits=5}function b(e,t,n,i){var a,r=e.state;return null===r.window&&(r.wsize=1<=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):((a=r.wsize-r.wnext)>i&&(a=i),s.arraySet(r.window,t,n-i,a,r.wnext),(i-=a)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,n.check=a(n.check,B,2,0),h=0,m=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&h)){e.msg="unknown compression method",n.mode=30;break}if(m-=4,R=8+(15&(h>>>=4)),0===n.wbits)n.wbits=R;else if(R>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=3;case 3:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>8&255,B[2]=h>>>16&255,B[3]=h>>>24&255,n.check=a(n.check,B,4,0)),h=0,m=0,n.mode=4;case 4:for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>8),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=5;case 5:if(1024&n.flags){for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((v=n.length)>p&&(v=p),v&&(n.head&&(R=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,u,l,v,R)),512&n.flags&&(n.check=a(n.check,u,v,l)),p-=v,l+=v,n.length-=v),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===p)break e;v=0;do{R=u[l+v++],n.head&&R&&n.length<65536&&(n.head.name+=String.fromCharCode(R))}while(R&&v>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>=7&m,m-=7&m,n.mode=27;break}for(;m<3;){if(0===p)break e;p--,h+=u[l++]<>>=1)){case 0:n.mode=14;break;case 1:if(y(n),n.mode=20,6===t){h>>>=2,m-=2;break e}break;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}h>>>=2,m-=2;break;case 14:for(h>>>=7&m,m-=7&m;m<32;){if(0===p)break e;p--,h+=u[l++]<>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&h,h=0,m=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(v=n.length){if(v>p&&(v=p),v>g&&(v=g),0===v)break e;s.arraySet(d,u,l,v,f),p-=v,l+=v,g-=v,f+=v,n.length-=v;break}n.mode=12;break;case 17:for(;m<14;){if(0===p)break e;p--,h+=u[l++]<>>=5,m-=5,n.ndist=1+(31&h),h>>>=5,m-=5,n.ncode=4+(15&h),h>>>=4,m-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,m-=3}for(;n.have<19;)n.lens[x[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,O={bits:n.lenbits},U=o(0,n.lens,0,19,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=P,m-=P,n.lens[n.have++]=S;else{if(16===S){for(T=P+2;m>>=P,m-=P,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}R=n.lens[n.have-1],v=3+(3&h),h>>>=2,m-=2}else if(17===S){for(T=P+3;m>>=P)),h>>>=3,m-=3}else{for(T=P+7;m>>=P)),h>>>=7,m-=7}if(n.have+v>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;v--;)n.lens[n.have++]=R}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,O={bits:n.lenbits},U=o(1,n.lens,0,n.nlen,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,O={bits:n.distbits},U=o(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,O),n.distbits=O.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(p>=6&&g>=258){e.next_out=f,e.avail_out=g,e.next_in=l,e.avail_in=p,n.hold=h,n.bits=m,r(e,w),f=e.next_out,d=e.output,g=e.avail_out,l=e.next_in,u=e.input,p=e.avail_in,h=n.hold,m=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;C=(D=n.lencode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,n.length=S,0===C){n.mode=26;break}if(32&C){n.back=-1,n.mode=12;break}if(64&C){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&C,n.mode=22;case 22:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;C=(D=n.distcode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,64&C){e.msg="invalid distance code",n.mode=30;break}n.offset=S,n.extra=15&C,n.mode=24;case 24:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===g)break e;if(v=w-g,n.offset>v){if((v=n.offset-v)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}v>n.wnext?(v-=n.wnext,A=n.wsize-v):A=n.wnext-v,v>n.length&&(v=n.length),I=n.window}else I=d,A=f-n.offset,v=n.length;v>g&&(v=g),g-=v,n.length-=v;do{d[f++]=I[A++]}while(--v);0===n.length&&(n.mode=21);break;case 26:if(0===g)break e;d[f++]=n.length,g--,n.mode=21;break;case 27:if(n.wrap){for(;m<32;){if(0===p)break e;p--,h|=u[l++]<=1&&0===B[S];S--);if(M>S&&(M=S),0===S)return u[d++]=20971520,u[d++]=20971520,f.bits=1,0;for(C=1;C0&&(0===e||1!==S))return-1;for(x[1]=0,I=1;I<15;I++)x[I+1]=x[I]+B[I];for(P=0;P852||2===e&&U>592)return 1;for(;;){_=I-E,l[P]b?(w=j[N+l[P]],v=T[D+l[P]]):(w=96,v=0),p=1<>E)+(g-=p)]=_<<24|w<<16|v|0}while(0!==g);for(p=1<>=1;if(0!==p?(O&=p-1,O+=p):O=0,P++,0==--B[I]){if(I===S)break;I=t[n+l[P]]}if(I>M&&(O&m)!==h){for(0===E&&(E=M),y+=C,R=1<<(k=I-E);k+E852||2===e&&U>592)return 1;u[h=O&m]=M<<24|k<<16|y-d|0}}return 0!==O&&(u[y+O]=I-E<<24|64<<16|0),f.bits=M,0}},{"../utils/common":1}],10:[function(e,t,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){"use strict";var s=e("./zlib/inflate"),i=e("./utils/common"),a=e("./utils/strings"),r=e("./zlib/constants"),o=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),d=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(o[n]);if(this.header=new u,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=a.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(o[n])}function f(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}l.prototype.push=function(e,t){var n,o,c,u,l,f=this.strm,p=this.options.chunkSize,g=this.options.dictionary,h=!1;if(this.ended)return!1;o=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?f.input=a.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?f.input=new Uint8Array(e):f.input=e,f.next_in=0,f.avail_in=f.input.length;do{if(0===f.avail_out&&(f.output=new i.Buf8(p),f.next_out=0,f.avail_out=p),(n=s.inflate(f,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===h&&(n=r.Z_OK,h=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),this.ended=!0,!1;f.next_out&&(0!==f.avail_out&&n!==r.Z_STREAM_END&&(0!==f.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=a.utf8border(f.output,f.next_out),u=f.next_out-c,l=a.buf2string(f.output,c),f.next_out=u,f.avail_out=p-u,u&&i.arraySet(f.output,f.output,c,u,0),this.onData(l)):this.onData(i.shrinkBuf(f.output,f.next_out)))),0===f.avail_in&&0===f.avail_out&&(h=!0)}while((f.avail_in>0||0===f.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),f.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=l,n.inflate=f,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},n.ungzip=f},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")},function(e,t,n){const s=n(46),i=n(58),a=n(25),r=n(60),o=n(57),c=n(61);e.exports={BinaryWriter:i,BinaryReader:a,MessagePacker:o,AsyncQueue:c,Logger:s,PromisedWebSockets:r}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){(function(t){const n=e=>e.replace(/(?:^|_)([a-z])/g,(e,t)=>t.toUpperCase()).replace(/_/g,""),s=e=>e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_","")),i=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),a=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let r;function o(e){r||(r=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}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0}const c=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),c(e,t,n)),n},u=(e,i)=>{const a=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!a)throw new Error("Cannot parse TLObject "+e);const r=c(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),u={name:a[1],constructorId:parseInt(a[2],16),argsConfig:{},subclassOfId:o(a[3]),result:a[3],isFunction:i,namespace:void 0};if(!u.constructorId){const e="";let n;n=Object.values(u.argsConfig).length?" "+Object.keys(u.argsConfig).map(e=>e.toString()).join(" "):"";const s=`${u.name}${e}${n} = ${u.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===u.name&&u.name,u.constructorId=o(t.from(s,"utf8"))}for(const[e,t,n]of r)void 0===e&&(u.argsConfig[s(t)]=d(t,n));return u.name.includes(".")&&([u.namespace,u.name]=u.name.split(/\.(.+)/)),u.name=n(u.name),u};function d(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:c,parseTl:function*(e,t,n=[],s=i){(n||[]).reduce((e,t)=>({...e,[t.name]:t}),{});const r=[],o={},c={},d=e;let l=!1;for(let e of d.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;l="functions"===e}else try{const t=u(e,l);if(s.has(t.constructorId))continue;r.push(t),t.isFunction||(c[t.result]||(c[t.result]=[]),o[t.name]=t,c[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of r)if(a.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of r)yield e},buildArgConfig:d,fromLine:u,CORE_TYPES:i,serializeDate:function(e){if(!e)return t.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const n=t.alloc(4);return n.writeInt32LE(e,0),n}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof t)){if("string"!=typeof e)throw Error("Bytes or str expected, not "+e.constructor.name);e=t.from(e)}const n=[];let s;return e.length<254?(s=(e.length+1)%4,0!==s&&(s=4-s),n.push(t.from([e.length])),n.push(e)):(s=e.length%4,0!==s&&(s=4-s),n.push(t.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),n.push(e)),n.push(t.alloc(s).fill(0)),t.concat(n)},snakeToCamelCase:n,variableSnakeToCamelCase:s}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"CTR",(function(){return y})),n.d(t,"IGE",(function(){return m}));var s=new Uint8Array(256),i=new Uint8Array(256),a=new Uint32Array(256),r=new Uint32Array(256),o=new Uint32Array(256),c=new Uint32Array(256),u=new Uint32Array(256),d=new Uint32Array(256),l=new Uint32Array(256),f=new Uint32Array(256);function p(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(var t=e.length%4;t<=4;t++)e+="\0x00";var n=new Uint32Array(e.length/4);for(t=0;t>7),m[h[_]^_]=_;for(;!s[y];y^=e||1)n=(n=b^b<<1^b<<2^b<<3^b<<4)>>8^255&n^99,s[y]=n,i[n]=y,g=16843009*h[t=h[e=h[y]]]^65537*t^257*e^16843008*y,p=257*h[n]^16843008*n,a[y]=p=p<<24^p>>>8,r[y]=p=p<<24^p>>>8,o[y]=p=p<<24^p>>>8,c[y]=p=p<<24^p>>>8,u[n]=g=g<<24^g>>>8,d[n]=g=g<<24^g>>>8,l[n]=g=g<<24^g>>>8,f[n]=g=g<<24^g>>>8,b=m[b]||1}();var h=function(){function e(e){var t=p(e);if(4!==t.length&&6!==t.length&&8!==t.length)throw new Error("Invalid key size");this.encKey=new Uint32Array(4*t.length+28),this.decKey=new Uint32Array(4*t.length+28),this.encKey.set(t);for(var n,i=1,a=t.length;a<4*t.length+28;a++)n=this.encKey[a-1],(a%t.length==0||8===t.length&&a%t.length==4)&&(n=s[n>>>24]<<24^s[n>>16&255]<<16^s[n>>8&255]<<8^s[255&n],a%t.length==0&&(n=n<<8^n>>>24^i<<24,i=i<<1^283*(i>>7))),this.encKey[a]=this.encKey[a-t.length]^n;for(var r=0;a;r++,a--)n=this.encKey[3&r?a:a-4],this.decKey[r]=a<=4||r<4?n:u[s[n>>>24]]^d[s[n>>16&255]]^l[s[n>>8&255]]^f[s[255&n]]}return e.prototype.encrypt=function(e){for(var t,n,i,u=p(e),d=new Uint32Array(4),l=u[0]^this.encKey[0],f=u[1]^this.encKey[1],g=u[2]^this.encKey[2],h=u[3]^this.encKey[3],m=this.encKey.length/4-2,y=4,b=0;b>>24]^r[f>>16&255]^o[g>>8&255]^c[255&h]^this.encKey[y],n=a[f>>>24]^r[g>>16&255]^o[h>>8&255]^c[255&l]^this.encKey[y+1],i=a[g>>>24]^r[h>>16&255]^o[l>>8&255]^c[255&f]^this.encKey[y+2],h=a[h>>>24]^r[l>>16&255]^o[f>>8&255]^c[255&g]^this.encKey[y+3],l=t,f=n,g=i,y+=4;for(b=0;b<4;b++)d[b]=s[l>>>24]<<24^s[f>>16&255]<<16^s[g>>8&255]<<8^s[255&h]^this.encKey[y++],t=l,l=f,f=g,g=h,h=t;return d},e.prototype.decrypt=function(e){for(var t,n,s,a=p(e),r=new Uint32Array(4),o=a[0]^this.decKey[0],c=a[3]^this.decKey[1],g=a[2]^this.decKey[2],h=a[1]^this.decKey[3],m=this.decKey.length/4-2,y=4,b=0;b>>24]^d[c>>16&255]^l[g>>8&255]^f[255&h]^this.decKey[y],n=u[c>>>24]^d[g>>16&255]^l[h>>8&255]^f[255&o]^this.decKey[y+1],s=u[g>>>24]^d[h>>16&255]^l[o>>8&255]^f[255&c]^this.decKey[y+2],h=u[h>>>24]^d[o>>16&255]^l[c>>8&255]^f[255&g]^this.decKey[y+3],o=t,c=n,g=s,y+=4;for(b=0;b<4;b++)r[3&-b]=i[o>>>24]<<24^i[c>>16&255]<<16^i[g>>8&255]<<8^i[255&h]^this.decKey[y++],t=o,o=c,c=g,g=h,h=t;return r},e}(),m=function(){function e(e,t,n){void 0===n&&(n=16),this.key=p(e),this.iv=p(t),this.cipher=new h(e),this.blockSize=n/4}return e.prototype.encrypt=function(e,t){for(var n=p(e),s=t||new Uint32Array(n.length),i=this.iv.subarray(this.blockSize,this.iv.length),a=this.iv.subarray(0,this.blockSize),r=new Uint32Array(this.blockSize),o=0;o=this.blockSize&&this.incrementCounter(),i&&(a-=i,i=0)}return this.offset=(this.offset+n.length%4)%4,s},e.prototype.decrypt=function(e,t){return this.encrypt(e,t)},e.prototype.incrementCounter=function(){for(var e=this.counter.length-1;e>=0&&!(++this.counter[e]<4294967295);e--);},e}();t.default=h},function(e,t,n){(function(t){let n;class s{constructor(e){n||(n=e||"debug"),this.isBrowser=void 0===t||"renderer"===t.type||!0===t.browser||t.__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){n=e}canSend(e){return s.levels.indexOf(n)>=s.levels.indexOf(e)}warn(e){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){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,t,s){n&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(t,e),s):console.log(s+this.format(t,e)+this.colors.end))}}var i,a,r;r=["error","warn","info","debug"],(a="levels")in(i=s)?Object.defineProperty(i,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[a]=r,e.exports=s}).call(this,n(83))},function(e,t,n){const{RPCError:s,InvalidDCError:i,FloodError:a,BadRequestError:r}=n(36);class o extends i{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 i{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 u extends a{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 a{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 l extends a{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 f extends i{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 p extends i{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 g extends r{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 h=[[/FILE_MIGRATE_(\d+)/,f],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,l],[/FLOOD_WAIT_(\d+)/,d],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,u],[/USER_MIGRATE_(\d+)/,o],[/NETWORK_MIGRATE_(\d+)/,p],[/EMAIL_UNCONFIRMED_(\d+)/,g]];e.exports={rpcErrorRe:h,FileMigrateError:f,FloodTestPhoneWaitError:l,FloodWaitError:d,PhoneMigrateError:c,SlowModeWaitError:u,UserMigrateError:o,NetworkMigrateError:p,EmailUnconfirmedError:g}},function(e,t){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")}}},function(e,t,n){const s=n(6),i={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)i[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))i[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:128,tlobjects:i}},function(e,t,n){const s=n(51),i=n(52),a=n(8),r=n(28),o=n(56),c=n(55),u=n(38),d=n(32),l=n(86),{MsgsAck:f,upload:p,MsgsStateInfo:g,Pong:h}=n(21).constructors,m=n(57),y=n(25),{UpdateConnectionState:b}=n(59),{BadMessageError:_}=n(23),{BadServerSalt:w,BadMsgNotification:v,MsgDetailedInfo:A,MsgNewDetailedInfo:I,NewSessionCreated:P,FutureSalts:C,MsgsStateReq:S,MsgResendReq:M,MsgsAllInfo:k}=n(21).constructors,{SecurityError:E}=n(23),{InvalidBufferError:R}=n(23),{LogOut:U}=n(21).requests.auth,{RPCMessageToError:O}=n(29),{TypeNotFoundError:T}=n(23);class D{constructor(e,t){const n={...D.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._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new r,this._state=new i(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[u.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[d.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[w.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[I.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[f.CONSTRUCTOR_ID]:this._handleAck.bind(this),[C.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[S.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this._connection=e;for(let e=0;e1024)throw new u("Server replied with the wrong message padding");const y=f.tgReadObject();return new c(p,g,y)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=s(Math.floor(e)).shiftLeft(s(32)).or(s(t).shiftLeft(s(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(s(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,i=Math.floor((new Date).getTime()/1e3),a=e.shiftRight(s(32));return this.timeOffset=a-i,this.timeOffset!==n&&(this._lastMsgId=s(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}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const{IGE:s}=n(45),i=n(8);e.exports=class{constructor(e,t){this.ige=new s(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const n=e.length%16;return n&&(e=t.concat([e,i.generateRandomBytes(16-n)])),i.convertToLittle(this.ige.encrypt(e))}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(37),i=n(55),a=n(38),r=n(32),o={[i.CONSTRUCTOR_ID]:i,[r.CONSTRUCTOR_ID]:r,[a.CONSTRUCTOR_ID]:a};e.exports={TLMessage:s,RPCResult:i,MessageContainer:a,GZIPPacked:r,coreObjects:o}},function(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{RpcError:i}=n(21).constructors,a=n(32);class r{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===i.CONSTRUCTOR_ID?new r(t,void 0,i.fromReader(e)):n===a.CONSTRUCTOR_ID?new r(t,(await a.fromReader(e)).data):(e.seek(-4),new r(t,e.read(),void 0))}}s(r,"CONSTRUCTOR_ID",4082920705),s(r,"classType","constructor"),e.exports=r},function(e,t,n){(function(t){const s=n(15),i=n(53),a=n(28),r=n(84),o=n(85),c=n(8),{constructors:u,requests:d}=n(21),l=n(25),{SecurityError:f}=n(23);e.exports=async function(e,n){let p=c.generateRandomBytes(16);const g=c.readBigIntFromBuffer(p,!1,!0),h=await e.send(new d.ReqPqMulti({nonce:g}));if(n.debug("Starting authKey generation step 1"),!(h instanceof u.ResPQ))throw new Error("Step 1 answer was "+h);if(h.nonce.neq(g))throw new f("Step 1 invalid nonce from server");const m=c.readBigIntFromBuffer(h.pq,!1,!0);n.debug("Finished authKey generation step 1"),n.debug("Starting authKey generation step 2");let{p:y,q:b}=r.factorize(m);y=c.getByteArray(y),b=c.getByteArray(b),p=c.generateRandomBytes(32);const _=c.readBigIntFromBuffer(p,!0,!0),w=new u.PQInnerData({pq:c.getByteArray(m),p:y,q:b,nonce:h.nonce,serverNonce:h.serverNonce,newNonce:_});let v,A;for(const e of h.serverPublicKeyFingerprints)if(v=await o.encrypt(e.toString(),w.getBytes()),void 0!==v){A=e;break}if(void 0===v)throw new f("Step 2 could not find a valid key for fingerprints");const I=await e.send(new d.ReqDHParams({nonce:h.nonce,serverNonce:h.serverNonce,p:y,q:b,publicKeyFingerprint:A,encryptedData:v}));if(!(I instanceof u.ServerDHParamsOk||I instanceof u.ServerDHParamsFail))throw new Error("Step 2.1 answer was "+I);if(I.nonce.neq(h.nonce))throw new f("Step 2 invalid nonce from server");if(I.serverNonce.neq(h.serverNonce))throw new f("Step 2 invalid server nonce from server");if(I instanceof u.ServerDHParamsFail){const e=await c.sha1(c.toSignedLittleBuffer(_,32).slice(4,20)),t=c.readBigIntFromBuffer(e,!0,!0);if(I.newNonceHash.neq(t))throw new f("Step 2 invalid DH fail nonce from server")}if(!(I instanceof u.ServerDHParamsOk))throw new Error("Step 2.2 answer was "+I);n.debug("Finished authKey generation step 2"),n.debug("Starting authKey generation step 3");const{key:P,iv:C}=await c.generateKeyDataFromNonce(h.serverNonce,_);if(I.encryptedAnswer.length%16!=0)throw new f("Step 3 AES block size mismatch");const S=new i(P,C),M=S.decryptIge(I.encryptedAnswer),k=new l(M);k.read(20);const E=k.tgReadObject();if(!(E instanceof u.ServerDHInnerData))throw new Error("Step 3 answer was "+E);if(E.nonce.neq(h.nonce))throw new f("Step 3 Invalid nonce in encrypted answer");if(E.serverNonce.neq(h.serverNonce))throw new f("Step 3 Invalid server nonce in encrypted answer");const R=c.readBigIntFromBuffer(E.dhPrime,!1,!1),U=c.readBigIntFromBuffer(E.gA,!1,!1),O=E.serverTime-Math.floor((new Date).getTime()/1e3),T=c.readBigIntFromBuffer(c.generateRandomBytes(256),!1,!1),D=c.modExp(s(E.g),T,R),B=c.modExp(U,T,R),x=new u.ClientDHInnerData({nonce:h.nonce,serverNonce:h.serverNonce,retryId:0,gB:c.getByteArray(D,!1)}).getBytes(),j=t.concat([await c.sha1(x),x]),N=S.encryptIge(j),V=await e.send(new d.SetClientDHParams({nonce:h.nonce,serverNonce:h.serverNonce,encryptedData:N})),F=[u.DhGenOk,u.DhGenRetry,u.DhGenFail];if(!(V instanceof F[0]||V instanceof F[1]||V instanceof F[2]))throw new Error("Step 3.1 answer was "+V);const{name:L}=V.constructor;if(V.nonce.neq(h.nonce))throw new f(`Step 3 invalid ${L} nonce from server`);if(V.serverNonce.neq(h.serverNonce))throw new f(`Step 3 invalid ${L} server nonce from server`);const q=new a;await q.setKey(c.getByteArray(B));const H=1+F.indexOf(V.constructor),K=await q.calcNewNonceHash(_,H);if(V["newNonceHash"+H].neq(K))throw new f("Step 3 invalid new nonce hash");if(!(V instanceof u.DhGenOk))throw new Error("Step 3.2 answer was "+V);return n.debug("Finished authKey generation step 3"),{authKey:q,timeOffset:O}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const s=n(38),i=n(37),a=n(58);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){this._queue.push(e),this.setReady(!0),e&&(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,n=new a(t.alloc(0));const r=[];let o=0;for(;this._queue.length&&r.length<=s.MAXIMUM_LENGTH;){const e=this._queue.shift();if(o+=e.data.length+i.SIZE_OVERHEAD,o<=s.MAXIMUM_SIZE){let t;e.after&&(t=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(n,e.data,"request"===e.request.classType,t),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),r.push(e)}else{if(r.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"),o=0}}if(r.length){if(r.length>1){const i=t.alloc(8);i.writeUInt32LE(s.CONSTRUCTOR_ID,0),i.writeInt32LE(r.length,4),e=t.concat([i,n.getValue()]),n=new a(t.alloc(0));const o=await this._state.writeDataAsMessage(n,e,!1);for(const e of r)e.containerId=o}return e=n.getValue(),{batch:r,data:e}}}rejectAll(){this._pendingStates.forEach(e=>{e.reject(new Error("Disconnect"))})}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){e.exports=class{constructor(e){this._stream=e}write(e){this._stream=t.concat([this._stream,e])}getValue(){return this._stream}}}).call(this,n(12).Buffer)},function(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 i=n(51),a=n(56),r=n(50);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(87);e.exports={Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:i,doAuthentication:a,MTProtoSender:r,UpdateConnectionState:o}},function(e,t,n){(function(t){const{Mutex:s}=n(88),i=new s,a=n(90).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(){this.client=void 0,this.closed=!0}async readExactly(e){let n=t.alloc(0);for(;;){const s=await this.read(e);if(n=t.concat([n,s]),!(e-=s.length))return n}}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=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),e}getWebSocketLink(e,t){return 443===t?`wss://${e}:${t}/apiws`:`ws://${e}:${t}/apiws`}connect(e,n){return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),this.closed=!1,this.website=this.getWebSocketLink(n,e),this.client=new a(this.website,"binary"),new Promise((e,t)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{t(e)},this.client.onclose=()=>{this.resolveRead(!1),this.closed=!0},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=>{const n=await i.acquire();try{const s=e.data instanceof ArrayBuffer?t.from(e.data):t.from(await new Response(e.data).arrayBuffer());this.stream=t.concat([this.stream,s]),this.resolveRead(!0)}finally{n()}}}}}).call(this,n(12).Buffer)},function(e,t){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}}},function(e,t,n){(function(t){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 i=n(15),{readBufferFromBigInt:a}=n(8),{Connection:r,PacketCodec:o}=n(39);class c extends o{constructor(e){super(e),this.tag=c.tag,this.obfuscateTag=c.obfuscateTag}encodePacket(e){let n=e.length>>2;if(n<127){const e=t.alloc(1);e.writeUInt8(n,0),n=e}else n=t.concat([t.from("7f","hex"),a(i(n),3)]);return t.concat([n,e])}async readPacket(e){let n=(await e.read(1))[0];return n>=127&&(n=t.concat([await e.read(3),t.alloc(1)]).readInt32LE(0)),e.read(n<<2)}}s(c,"tag",t.from("ef","hex")),s(c,"obfuscateTag",t.from("efefefef","hex"));e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),s(this,"PacketCodecClass",c)}},AbridgedPacketCodec:c}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){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{generateRandomBytes:i}=n(8),{ObfuscatedConnection:a}=n(39),{AbridgedPacketCodec:r}=n(62),o=n(94);class c{constructor(e){s(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 n=[t.from("50567247","hex"),t.from("474554","hex"),t.from("504f5354","hex"),t.from("eeeeeeee","hex")];let s;for(;;)if(s=i(64),239!==s[0]&&!s.slice(4,8).equals(t.alloc(4))){let e=!0;for(const t of n)if(t.equals(s.slice(0,4))){e=!1;break}if(e)break}s=s.toJSON().data;const a=t.from(s.slice(8,56)).reverse(),r=t.from(s.slice(8,40)),c=t.from(s.slice(40,56)),u=t.from(a.slice(0,32)),d=t.from(a.slice(32,48)),l=new o(r,c),f=new o(u,d);return s=t.concat([t.from(s.slice(0,56)),e.obfuscateTag,t.from(s.slice(60))]),s=t.concat([t.from(s.slice(0,56)),t.from(l.encrypt(s).slice(56,64)),t.from(s.slice(64))]),{random:s,encryptor:l,decryptor:f}}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 a{constructor(...e){super(...e),s(this,"ObfuscatedIO",c),s(this,"PacketCodecClass",r)}}}}).call(this,n(12).Buffer)},function(e,t){},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(s||(s={}));const i=-1,a="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(s||(s={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return r}));var s=n(1),i=n(0),a=n(2);async function r({chatId:t,accessHash:n,messageId:r,data:o}){const c=await Object(s.g)(new i.Api.messages.GetBotCallbackAnswer({peer:Object(a.i)(t,n),msgId:r,data:e.from(o)}));if(c)return c}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";t.byteLength=function(e){var t=u(e),n=t[0],s=t[1];return 3*(n+s)/4-s},t.toByteArray=function(e){var t,n,s=u(e),r=s[0],o=s[1],c=new a(function(e,t,n){return 3*(t+n)/4-n}(0,r,o)),d=0,l=o>0?r-4:r;for(n=0;n>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===o&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[d++]=255&t);1===o&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,a=[],r=0,o=n-i;ro?o:r+16383));1===i?(t=e[n-1],a.push(s[t>>2]+s[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],a.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return a.join("")};for(var s=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=r.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e,t,n){for(var i,a,r=[],o=t;o>18&63]+s[a>>12&63]+s[a>>6&63]+s[63&a]);return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,s,i){var a,r,o=8*i-s-1,c=(1<>1,d=-7,l=n?i-1:0,f=n?-1:1,p=e[t+l];for(l+=f,a=p&(1<<-d)-1,p>>=-d,d+=o;d>0;a=256*a+e[t+l],l+=f,d-=8);for(r=a&(1<<-d)-1,a>>=-d,d+=s;d>0;r=256*r+e[t+l],l+=f,d-=8);if(0===a)a=1-u;else{if(a===c)return r?NaN:1/0*(p?-1:1);r+=Math.pow(2,s),a-=u}return(p?-1:1)*r*Math.pow(2,a-s)},t.write=function(e,t,n,s,i,a){var r,o,c,u=8*a-i-1,d=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:a-1,g=s?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,r=d):(r=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-r))<1&&(r--,c*=2),(t+=r+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(r++,c/=2),r+l>=d?(o=0,r=d):r+l>=1?(o=(t*c-1)*Math.pow(2,i),r+=l):(o=t*Math.pow(2,l-1)*Math.pow(2,i),r=0));i>=8;e[n+p]=255&o,p+=g,o/=256,i-=8);for(r=r<0;e[n+p]=255&r,p+=g,r/=256,u-=8);e[n+p-g]|=128*h}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(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++]=i>>16&255,t[n++]=i>>8&255,t[n++]=255&i}return t.buffer}function i(e){return e.buffer}function a(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;enew p.InvokeWithLayer({layer:l,query:new p.InitConnection({apiId:this.apiId,deviceModel:r.deviceModel||s.type().toString()||"Unknown",systemVersion:r.systemVersion||s.release().toString()||"1.0",appVersion:r.appVersion||"1.0",langCode:r.langCode,langPack:"",systemLangCode:r.systemLangCode,query:e,proxy:void 0})}),this._args=r,this._config=void 0,this.phoneCodeHashes=[],this._borrowedSenderPromises={},this._additionalDcsDisabled=r.additionalDcsDisabled}async connect(){await this._initSession(),this._sender=new g(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});const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log);await this._sender.connect(e),this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new p.help.GetConfig({}))),this._updateLoop()}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]":"venus.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;this.isConnected();){await c.sleep(3e3);try{await S(()=>{return e=this._sender.send(new p.Ping({pingId:c.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)})),t=1500,Promise.race([e,c.sleep(t).then(()=>Promise.reject(new Error("TIMEOUT")))]);var e,t},3,100)}catch(e){return await this.disconnect(),void this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new p.updates.GetState)}catch(e){}}}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._borrowedSenderPromises).map(e=>e.then(e=>{if(e)return e.disconnect()}))),this._borrowedSenderPromises={}}async destroy(){await this.disconnect(),this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info("Reconnecting to new data center "+e);const t=u.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}_cleanupBorrowedSender(e){delete this._borrowedSenderPromises[e]}_borrowExportedSender(e){if(this._additionalDcsDisabled)return;let t=this._borrowedSenderPromises[e];return t||(t=this._createExportedSender(e),this._borrowedSenderPromises[e]=t,t.then(t=>{t||delete this._borrowedSenderPromises[e]})),t}async _createExportedSender(e){const t=u.getDC(e),n=new g(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._cleanupBorrowedSender.bind(this)});for(let s=0;s<5;s++)try{if(await n.connect(new this._connection(t.ipAddress,t.port,e,this._log)),this.session.dcId!==e){this._log.info("Exporting authorization for data center "+t.ipAddress);const s=await this.invoke(new p.auth.ExportAuthorization({dcId:e})),i=this._initWith(new p.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await n.send(i)}return n.dcId=e,n}catch(e){await n.disconnect()}}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof f.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof f.MessageMediaWebPage&&n.webpage instanceof f.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof f.MessageMediaPhoto||n instanceof f.Photo?this._downloadPhoto(n,t):n instanceof f.MessageMediaDocument||n instanceof f.Document?this._downloadDocument(n,t):n instanceof f.MessageMediaContact?this._downloadContact(n,t):n instanceof f.WebDocument||n instanceof f.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,i,a;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 f.UserProfilePhoto||s instanceof f.ChatPhoto)return i=s.dcId,a=new f.InputPeerPhotoFileLocation({peer:u.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(a,{dcId:i})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new f.InputStickerSetThumb({stickerset:new f.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=v.indexOf(t);se.type===v[s]),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof f.PhotoStrippedSize?u.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof f.MessageMediaPhoto&&(e=e.photo),!(e instanceof f.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof f.PhotoSizeEmpty?void 0:n instanceof f.PhotoCachedSize||n instanceof f.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new f.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 f.MessageMediaDocument&&(e=e.document),!(e instanceof f.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 f.PhotoCachedSize||n instanceof f.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new f.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")}_downloadWebDocument(e,t){throw new Error("not implemented")}async invoke(e){if("request"!==e.classType)throw new Error("You can only invoke MTProtoRequests");this._lastRequest=(new Date).getTime();let t=0;for(t=0;t1)for(var n=1;n{d[i(e.slice(-8),!0,!0)]=t}),e.exports={encrypt:async function(e,n){const u=d[e];if(!u)return;const l=o(235-n.length),f=t.concat([await r(n),n,l]),p=i(f,!1),g=c(p,s(u.e),u.n);return a(g,256,!1)}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(e,t){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}},function(e,t,n){const{Connection:s}=n(39),{ConnectionTCPFull:i}=n(93),{ConnectionTCPAbridged:a}=n(62),{ConnectionTCPObfuscated:r}=n(63);e.exports={Connection:s,ConnectionTCPFull:i,ConnectionTCPAbridged:a,ConnectionTCPObfuscated:r}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n(89);t.Mutex=s.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(){this._queue=[],this._pending=!1}return e.prototype.isLocked=function(){return this._pending},e.prototype.acquire=function(){var e=this,t=new Promise((function(t){return e._queue.push(t)}));return this._pending||this._dispatchNext(),t},e.prototype.runExclusive=function(e){return this.acquire().then((function(t){var n;try{n=e()}catch(e){throw t(),e}return Promise.resolve(n).then((function(e){return t(),e}),(function(e){throw t(),e}))}))},e.prototype._dispatchNext=function(){this._queue.length>0?(this._pending=!0,this._queue.shift()(this._dispatchNext.bind(this))):this._pending=!1},e}();t.default=s},function(e,t,n){(function(t){var s=function(){return this||void 0===t?this:t}(),i=s.WebSocket||s.MozWebSocket,a=n(91);function r(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(r,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?r:null,version:a}}).call(this,n(43))},function(e,t,n){e.exports=n(92).version},function(e){e.exports=JSON.parse('{"_args":[["websocket@1.0.30","/Users/alexander/dev/telegram-tt"]],"_from":"websocket@1.0.30","_id":"websocket@1.0.30","_inBundle":false,"_integrity":"sha512-aO6klgaTdSMkhfl5VVJzD5fm+Srhh5jLYbS15+OiI1sN6h/RU/XW6WN9J1uVIpUKNmsTvT3Hs35XAFjn9NMfOw==","_location":"/websocket","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"websocket@1.0.30","name":"websocket","escapedName":"websocket","rawSpec":"1.0.30","saveSpec":null,"fetchSpec":"1.0.30"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/websocket/-/websocket-1.0.30.tgz","_spec":"1.0.30","_where":"/Users/alexander/dev/telegram-tt","author":{"name":"Brian McKelvey","email":"theturtle32@gmail.com","url":"https://github.com/theturtle32"},"browser":"lib/browser.js","bugs":{"url":"https://github.com/theturtle32/WebSocket-Node/issues"},"config":{"verbose":false},"contributors":[{"name":"Iñaki Baz Castillo","email":"ibc@aliax.net","url":"http://dev.sipdoc.net"}],"dependencies":{"debug":"^2.2.0","nan":"^2.14.0","typedarray-to-buffer":"^3.1.5","yaeti":"^0.0.6"},"description":"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.","devDependencies":{"buffer-equal":"^1.0.0","faucet":"^0.0.1","gulp":"^4.0.2","gulp-jshint":"^2.0.4","jshint":"^2.0.0","jshint-stylish":"^2.2.1","tape":"^4.9.1"},"directories":{"lib":"./lib"},"engines":{"node":">=0.10.0"},"homepage":"https://github.com/theturtle32/WebSocket-Node","keywords":["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],"license":"Apache-2.0","main":"index","name":"websocket","repository":{"type":"git","url":"git+https://github.com/theturtle32/WebSocket-Node.git"},"scripts":{"gulp":"gulp","install":"(node-gyp rebuild 2> builderror.log) || (exit 0)","test":"faucet test/unit"},"version":"1.0.30"}')},function(e,t){},function(e,t,n){(function(t){const s=n(35);e.exports=class{constructor(e,n){if(!t.isBuffer(e)||!t.isBuffer(n)||16!==n.length)throw new Error("Key and iv need to be a buffer");this.cipher=s.createCipheriv("AES-256-CTR",e,n)}encrypt(e){return t.from(this.cipher.update(e))}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"authFlow",(function(){return u})),n.d(t,"checkAuthorization",(function(){return d}));var s=n(6),i=n.n(s),a=n(20),r=n.n(a),o=n(8),c=n(31);async function u(e,t,n){const s="phoneNumber"in n?await l(e,t,n):await async function(e,t,n){const{apiId:s,apiHash:a}=t,{botAuthToken:r}=n,{user:o}=await e.invoke(new i.a.auth.ImportBotAuthorization({apiId:s,apiHash:a,botAuthToken:r}));return o}(e,t,n);e._log.info("Signed in successfully as",r.a.getDisplayName(s))}async function d(e){try{return await e.invoke(new i.a.updates.GetState),!0}catch(e){return!1}}async function l(e,t,n){let s,a,r,o=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return f(e,t,n);throw s}else s=n.phoneNumber;const i=await p(e,t,s,n.forceSMS);if(a=i.phoneCodeHash,o=i.isCodeViaApp,"string"!=typeof a)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,u=!1;for(;;)try{try{r=await n.phoneCode(o)}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n)}if(!r)throw new Error("Code is empty");const d=await e.invoke(new i.a.auth.SignIn({phoneNumber:s,phoneCodeHash:a,phoneCode:r}));if(d instanceof i.a.auth.AuthorizationSignUpRequired){u=!0,c=d.termsOfService;break}return d.user}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);n.onError(s)}if(u)for(;;)try{const[t,r]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:o}=await e.invoke(new i.a.auth.SignUp({phoneNumber:s,phoneCodeHash:a,firstName:t,lastName:r}));return c&&await e.invoke(new i.a.help.AcceptTermsOfService({id:c.id})),o}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),l(e,t,n)}async function f(e,t,n){let s=!1;const a=(async()=>{for(;!s;){const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(!(t instanceof i.a.auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:a}=t;await Promise.race([n.qrCode({token:s,expires:a}),Object(o.sleep)(3e4)])}})(),r=new Promise(t=>{e.addEventHandler(e=>{e instanceof i.a.UpdateLoginToken&&t()},{build:e=>e})});try{await Promise.race([r,a])}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(t instanceof i.a.auth.LoginTokenSuccess&&t.authorization instanceof i.a.auth.Authorization)return t.authorization.user;if(t instanceof i.a.auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new i.a.auth.ImportLoginToken({token:t.token}));if(n instanceof i.a.auth.LoginTokenSuccess&&n.authorization instanceof i.a.auth.Authorization)return n.authorization.user}}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);throw s}throw void 0}async function p(e,t,n,s=!1){try{const{apiId:a,apiHash:r}=t,o=await e.invoke(new i.a.auth.SendCode({phoneNumber:n,apiId:a,apiHash:r,settings:new i.a.CodeSettings}));if(!s||o.type instanceof i.a.auth.SentCodeTypeSms)return{phoneCodeHash:o.phoneCodeHash,isCodeViaApp:o.type instanceof i.a.auth.SentCodeTypeApp};const c=await e.invoke(new i.a.auth.ResendCode({phoneNumber:n,phoneCodeHash:o.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof i.a.auth.SentCodeTypeApp}}catch(i){if("AUTH_RESTART"===i.message)return p(e,t,n,s);throw i}}async function g(e,t,n){for(;;)try{const t=await e.invoke(new i.a.account.GetPassword),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const a=await Object(c.computeCheck)(t,s),{user:r}=await e.invoke(new i.a.auth.CheckPassword({password:a}));return r}catch(e){n.onError(e)}}},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"downloadFile",(function(){return u}));var s=n(6),i=n.n(s),a=n(20),r=n(8);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}class c{constructor(e){this.maxWorkers=e,o(this,"deferred",void 0),o(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=function(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function u(t,n,s){let{partSizeKb:o,end:u}=s;const{fileSize:d,workers:l=1}=s,{dcId:f,progressCallback:p,start:g=0}=s;u=u&&u{try{const s=await Promise.race([await y.send(new i.a.upload.GetFile({location:n,offset:w,limit:e,precise:t||void 0})),Object(r.sleep)(15e3).then(()=>Promise.reject(new Error("REQUEST_TIMEOUT")))]);if(p){if(p.isCanceled)throw new Error("USER_CANCELED");A+=1/m,p(A)}return!u&&s.bytes.lengthu)break}const I=(await Promise.all(_)).filter(Boolean),P=u?u+1-g:void 0;return e.concat(I,P)}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"uploadFile",(function(){return o}));var s=n(6),i=n.n(s),a=n(8),r=n(20);async function o(t,n){const{file:s,onProgress:o}=n;let{workers:c}=n;const{name:u,size:d}=s,l=Object(a.readBigIntFromBuffer)(Object(a.generateRandomBytes)(8),!0,!0),f=d>10485760,p=1024*Object(r.getAppropriatedPartSize)(d),g=Math.floor((d+p-1)/p),h=e.from(await function(e){return new Response(e).arrayBuffer()}(s)),m=await t._borrowExportedSender(t.session.dcId);c&&d||(c=1),c>=g&&(c=g);let y=0;o&&o(y);for(let e=0;eg&&(n=g);for(let s=e;s{if(await m.send(f?new i.a.upload.SaveBigFilePart({fileId:l,filePart:s,fileTotalParts:g,bytes:e}):new i.a.upload.SaveFilePart({fileId:l,filePart:s,bytes:e})),o){if(o.isCanceled)throw new Error("USER_CANCELED");y+=1/g,o(y)}})())}try{await Promise.race([await Promise.all(t),Object(a.sleep)(15e3*c).then(()=>Promise.reject(new Error("TIMEOUT")))])}catch(t){if("TIMEOUT"===t.message){console.warn("Upload timeout. Retrying..."),e-=c;continue}throw t}}return f?new i.a.InputFileBig({id:l,parts:g,name:u}):new i.a.InputFile({id:l,parts:g,name:u,md5Checksum:""})}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"updateTwoFaSettings",(function(){return u}));var s=n(6),i=n.n(s),a=n(8),r=n(31),o=n(29),c=n.n(o);async function u(t,{isCheckPassword:n,currentPassword:s,newPassword:o,hint:u="",email:d,emailCodeCallback:l,onEmailCodeError:f}){if(!o&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(d&&(!l||!f))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await t.invoke(new i.a.account.GetPassword);p.newAlgo instanceof i.a.PasswordKdfAlgoUnknown||(p.newAlgo.salt1=e.concat([p.newAlgo.salt1,Object(a.generateRandomBytes)(32)])),!p.hasPassword&&s&&(s=void 0);const g=s?await Object(r.computeCheck)(p,s):new i.a.InputCheckPasswordEmpty;if(n)await t.invoke(new i.a.auth.CheckPassword({password:g}));else try{await t.invoke(new i.a.account.UpdatePasswordSettings({password:g,newSettings:new i.a.account.PasswordInputSettings({newAlgo:p.newAlgo,newPasswordHash:o?await Object(r.computeDigest)(p.newAlgo,o):e.alloc(0),hint:u,email:d,newSecureSettings:void 0})}))}catch(e){if(!(e instanceof c.a.EmailUnconfirmedError))throw e;for(;;)try{const n=await l(e.codeLength);if(!n)throw new Error("Code is empty");await t.invoke(new i.a.account.ConfirmPasswordEmail({code:n}));break}catch(e){f(e)}}}}.call(this,n(12).Buffer)},function(e,t){e.exports="0.0.2"},function(e,t,n){const s=n(101),i=n(102);class a extends Error{}e.exports={NewMessage:s,StopPropagation:a,Raw:i}},function(e,t){},function(e,t,n){const{EventBuilder:s}=n(103);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},function(e,t){e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},function(e,t,n){const s=n(27),i=n(105),a=n(106),r=n(107),o=n(108),c=n(110);e.exports={Memory:s,StringSession:i,CacheApiSession:a,LocalStorageSession:r,IdbSession:o,CallbackSession:c}},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(25);class r extends s{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new a(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 t.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=t.from([this.dcId]),n=t.from(this.serverAddress),s=t.alloc(2);s.writeInt16BE(n.length,0);const i=t.alloc(2);return i.writeInt16BE(this.port,0),"1"+r.encode(t.concat([e,s,n,i,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}).call(this,n(12).Buffer)},function(e,t,n){const s=n(40);e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open("GramJs")).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open("GramJs"),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("GramJs")).put(t,n)}}},function(e,t,n){const s=n(40);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)}}},function(e,t,n){const s=n(109),i=n(40);e.exports=class extends i{_delete(){return s.del("GramJs:"+this._storageKey)}_fetchFromCache(){return s.get("GramJs:"+this._storageKey)}_saveToCache(e){return s.set("GramJs:"+this._storageKey,e)}}},function(e,t,n){"use strict";function s(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function i(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const i=s(n);return(e,n)=>i.then(s=>n(s.transaction(t,e).objectStore(t)))}let a;function r(){return a||(a=i("keyval-store","keyval")),a}function o(e,t=r()){return t("readonly",t=>s(t.get(e)))}function c(e,t,n=r()){return n("readwrite",n=>(n.put(t,e),s(n.transaction)))}function u(e,t=r()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),s(t.transaction)))}function d(e,t=r()){return t("readonly",t=>Promise.all(e.map(e=>s(t.get(e)))))}function l(e,t,n=r()){return n("readwrite",n=>new Promise((i,a)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),i(s(n.transaction))}catch(e){a(e)}}}))}function f(e,t=r()){return t("readwrite",t=>(t.delete(e),s(t.transaction)))}function p(e=r()){return e("readwrite",e=>(e.clear(),s(e.transaction)))}function g(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},s(e.transaction)))}function h(e=r()){const t=[];return g(e,e=>t.push(e.key)).then(()=>t)}function m(e=r()){const t=[];return g(e,e=>t.push(e.value)).then(()=>t)}function y(e=r()){const t=[];return g(e,e=>t.push([e.key,e.value])).then(()=>t)}n.r(t),n.d(t,"clear",(function(){return p})),n.d(t,"createStore",(function(){return i})),n.d(t,"del",(function(){return f})),n.d(t,"entries",(function(){return y})),n.d(t,"get",(function(){return o})),n.d(t,"getMany",(function(){return d})),n.d(t,"keys",(function(){return h})),n.d(t,"promisifyRequest",(function(){return s})),n.d(t,"set",(function(){return c})),n.d(t,"setMany",(function(){return u})),n.d(t,"update",(function(){return l})),n.d(t,"values",(function(){return m}))},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(20);e.exports=class extends s{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:n,hashes:s}=this._sessionData,{ipAddress:r,port:o}=a.getDC(e);this.setDC(e,r,o,!0),await Promise.all(Object.keys(n).map(async e=>{const a="string"==typeof n[e]?t.from(n[e],"hex"):t.from(n[e]);if(s[e]){const n="string"==typeof s[e]?t.from(s[e],"hex"):t.from(s[e]);this._authKeys[e]=new i(a,n)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)}))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(t=>{const n=this._authKeys[t];n&&n._key&&(e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex"))}),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t);var s={};n.r(s),n.d(s,"destroy",(function(){return p.a})),n.d(s,"disconnect",(function(){return p.b})),n.d(s,"downloadMedia",(function(){return p.c})),n.d(s,"fetchCurrentUser",(function(){return p.d})),n.d(s,"provideAuthPhoneNumber",(function(){return o.l})),n.d(s,"provideAuthCode",(function(){return o.j})),n.d(s,"provideAuthPassword",(function(){return o.k})),n.d(s,"provideAuthRegistration",(function(){return o.m})),n.d(s,"restartAuth",(function(){return o.n})),n.d(s,"restartAuthWithQr",(function(){return o.o})),n.d(s,"fetchChats",(function(){return c.j})),n.d(s,"fetchFullChat",(function(){return c.k})),n.d(s,"searchChats",(function(){return c.w})),n.d(s,"requestChatUpdate",(function(){return c.u})),n.d(s,"saveDraft",(function(){return c.v})),n.d(s,"clearDraft",(function(){return c.a})),n.d(s,"fetchChat",(function(){return c.h})),n.d(s,"updateChatMutedState",(function(){return c.H})),n.d(s,"createChannel",(function(){return c.b})),n.d(s,"joinChannel",(function(){return c.q})),n.d(s,"leaveChannel",(function(){return c.r})),n.d(s,"deleteChannel",(function(){return c.d})),n.d(s,"createGroupChat",(function(){return c.c})),n.d(s,"editChatPhoto",(function(){return c.g})),n.d(s,"toggleChatPinned",(function(){return c.z})),n.d(s,"toggleChatArchived",(function(){return c.y})),n.d(s,"toggleDialogUnread",(function(){return c.A})),n.d(s,"fetchChatFolders",(function(){return c.i})),n.d(s,"editChatFolder",(function(){return c.f})),n.d(s,"deleteChatFolder",(function(){return c.e})),n.d(s,"fetchRecommendedChatFolders",(function(){return c.n})),n.d(s,"getChatByUsername",(function(){return c.o})),n.d(s,"togglePreHistoryHidden",(function(){return c.B})),n.d(s,"updateChatDefaultBannedRights",(function(){return c.F})),n.d(s,"updateChatMemberBannedRights",(function(){return c.G})),n.d(s,"updateChatTitle",(function(){return c.I})),n.d(s,"updateChatAbout",(function(){return c.D})),n.d(s,"toggleSignatures",(function(){return c.C})),n.d(s,"updateChatAdmin",(function(){return c.E})),n.d(s,"fetchGroupsForDiscussion",(function(){return c.l})),n.d(s,"setDiscussionGroup",(function(){return c.x})),n.d(s,"migrateChat",(function(){return c.s})),n.d(s,"openChatByInvite",(function(){return c.t})),n.d(s,"fetchMembers",(function(){return c.m})),n.d(s,"fetchMessages",(function(){return u.g})),n.d(s,"fetchMessage",(function(){return u.e})),n.d(s,"sendMessage",(function(){return u.v})),n.d(s,"pinMessage",(function(){return u.q})),n.d(s,"unpinAllMessages",(function(){return u.y})),n.d(s,"deleteMessages",(function(){return u.b})),n.d(s,"deleteHistory",(function(){return u.a})),n.d(s,"markMessageListRead",(function(){return u.o})),n.d(s,"markMessagesRead",(function(){return u.p})),n.d(s,"requestThreadInfoUpdate",(function(){return u.r})),n.d(s,"searchMessagesLocal",(function(){return u.u})),n.d(s,"searchMessagesGlobal",(function(){return u.t})),n.d(s,"fetchWebPagePreview",(function(){return u.j})),n.d(s,"editMessage",(function(){return u.d})),n.d(s,"forwardMessages",(function(){return u.l})),n.d(s,"loadPollOptionResults",(function(){return u.n})),n.d(s,"sendPollVote",(function(){return u.w})),n.d(s,"findFirstMessageIdAfterDate",(function(){return u.k})),n.d(s,"fetchPinnedMessages",(function(){return u.h})),n.d(s,"fetchScheduledHistory",(function(){return u.i})),n.d(s,"sendScheduledMessages",(function(){return u.x})),n.d(s,"rescheduleMessage",(function(){return u.s})),n.d(s,"deleteScheduledMessages",(function(){return u.c})),n.d(s,"fetchMessageLink",(function(){return u.f})),n.d(s,"fetchFullUser",(function(){return v})),n.d(s,"fetchNearestCountry",(function(){return A})),n.d(s,"fetchTopUsers",(function(){return I})),n.d(s,"fetchContactList",(function(){return P})),n.d(s,"fetchUsers",(function(){return C})),n.d(s,"updateContact",(function(){return S})),n.d(s,"deleteUser",(function(){return M})),n.d(s,"fetchProfilePhotos",(function(){return k})),n.d(s,"fetchStickerSets",(function(){return D})),n.d(s,"fetchRecentStickers",(function(){return B})),n.d(s,"fetchFavoriteStickers",(function(){return x})),n.d(s,"fetchFeaturedStickers",(function(){return j})),n.d(s,"faveSticker",(function(){return N})),n.d(s,"fetchStickers",(function(){return V})),n.d(s,"fetchSavedGifs",(function(){return q})),n.d(s,"searchStickers",(function(){return L})),n.d(s,"installStickerSet",(function(){return H})),n.d(s,"uninstallStickerSet",(function(){return K})),n.d(s,"searchGifs",(function(){return z})),n.d(s,"fetchAnimatedEmojis",(function(){return F})),n.d(s,"fetchStickersForEmoji",(function(){return G})),n.d(s,"fetchEmojiKeywords",(function(){return W})),n.d(s,"checkChatUsername",(function(){return Z})),n.d(s,"setChatUsername",(function(){return Y})),n.d(s,"updatePrivateLink",(function(){return Q})),n.d(s,"updateProfile",(function(){return ge})),n.d(s,"checkUsername",(function(){return he})),n.d(s,"updateUsername",(function(){return me})),n.d(s,"fetchBlockedContacts",(function(){return ve})),n.d(s,"blockContact",(function(){return Ae})),n.d(s,"unblockContact",(function(){return Ie})),n.d(s,"updateProfilePhoto",(function(){return ye})),n.d(s,"uploadProfilePhoto",(function(){return be})),n.d(s,"fetchWallpapers",(function(){return _e})),n.d(s,"uploadWallpaper",(function(){return we})),n.d(s,"fetchAuthorizations",(function(){return Pe})),n.d(s,"terminateAuthorization",(function(){return Ce})),n.d(s,"terminateAllAuthorizations",(function(){return Se})),n.d(s,"fetchNotificationExceptions",(function(){return Me})),n.d(s,"fetchNotificationSettings",(function(){return ke})),n.d(s,"updateContactSignUpNotification",(function(){return Ee})),n.d(s,"updateNotificationSettings",(function(){return Re})),n.d(s,"fetchLanguages",(function(){return Ue})),n.d(s,"fetchLangPack",(function(){return Oe})),n.d(s,"fetchPrivacySettings",(function(){return Te})),n.d(s,"setPrivacySettings",(function(){return xe})),n.d(s,"registerDevice",(function(){return De})),n.d(s,"unregisterDevice",(function(){return Be})),n.d(s,"getPasswordInfo",(function(){return ne})),n.d(s,"checkPassword",(function(){return ie})),n.d(s,"clearPassword",(function(){return ae})),n.d(s,"updatePassword",(function(){return re})),n.d(s,"updateRecoveryEmail",(function(){return oe})),n.d(s,"provideRecoveryEmailCode",(function(){return ce})),n.d(s,"answerCallbackButton",(function(){return Ne.a})),n.d(s,"validateRequestedInfo",(function(){return Fe})),n.d(s,"sendPaymentForm",(function(){return Le})),n.d(s,"getPaymentForm",(function(){return qe})),n.d(s,"getReceipt",(function(){return He}));var i=n(4),a=n(30),r=n(26),o=n(17),c=n(7),u=n(10),d=n(15),l=n.n(d),f=n(0),p=n(1),g=n(2),h=n(13),m=n(3),y=n(19),b=n(5),_=n(16);let w;async function v({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;const s=await Object(p.g)(new f.Api.users.GetFullUser({id:n}));if(!s)return;const i=Object(h.b)(s);w({"@type":"updateUser",id:e,user:{fullInfo:i.fullInfo}})}async function A(){const e=await Object(p.g)(new f.Api.help.GetNearestDc);return e?e.country:void 0}async function I({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetTopPeers({hash:e,correspondents:!0}));if(!(t instanceof f.Api.contacts.TopPeers))return;const n=t.users.map(h.a).filter(e=>!!e&&!e.isSelf),s=n.map(({id:e})=>e);return{hash:Object(g.q)(s),ids:s,users:n}}async function P({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetContacts({hash:e}));if(t&&!(t instanceof f.Api.contacts.ContactsNotModified))return t.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),{hash:Object(g.q)([t.savedCount,...t.contacts.map(({userId:e})=>e)]),users:t.users.map(h.a).filter(Boolean),chats:t.users.map(e=>Object(m.d)(e)).filter(Boolean)}}async function C({users:e}){const t=await Object(p.g)(new f.Api.users.GetUsers({id:e.map(({id:e,accessHash:t})=>Object(g.i)(e,t))}));if(t&&t.length)return t.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),t.map(h.a).filter(Boolean)}function S({phone:e,firstName:t,lastName:n}){return Object(p.g)(new f.Api.contacts.ImportContacts({contacts:[Object(g.e)({phone:e||"",firstName:t||"",lastName:n||""})]}))}async function M({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;await Object(p.g)(new f.Api.contacts.DeleteContacts({id:[n]}))&&w({"@type":"deleteUser",id:e})}async function k(e,t){if(e){const{id:t,accessHash:n}=e,s=await Object(p.g)(new f.Api.photos.GetUserPhotos({userId:Object(g.g)(t,n),limit:i.u,offset:0,maxId:l()("0")}));if(!s)return;return function(e){e.photos.forEach(_.b)}(s),{photos:s.photos.filter(e=>e instanceof f.Api.Photo).map(y.a)}}const n=await Object(u.u)({chatOrUser:t,type:"profilePhoto",limit:i.u});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map(e=>e.content.action.photo).filter(Boolean),users:a}}var E=n(22),R=n(9);let U,O,T;async function D({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetAllStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.AllStickersNotModified))return t.sets.forEach(e=>{e.thumbs&&e.thumbs.length&&(b.a.stickerSets[String(e.id)]=e)}),{hash:t.hash,sets:t.sets.map(E.b)}}async function B({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetRecentStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.RecentStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function x({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFavedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FavedStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function j({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFeaturedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FeaturedStickersNotModified))return{hash:t.hash,sets:t.sets.map(E.c)}}async function N({sticker:e,unfave:t}){const n=new f.Api.messages.FaveSticker({id:Object(g.f)(e),unfave:t});await Object(p.g)(n)&&U({"@type":"updateFavoriteStickers"})}async function V({stickerSetId:e,accessHash:t}){const n=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:Object(g.l)(e,t)}));var s;if(n)return{set:Object(E.b)(n.set),stickers:$(n.documents),packs:(s=n.packs,s.reduce((e,{emoticon:t,documents:n})=>(e[t]=n.map(e=>Object(E.a)(b.a.documents[String(e)])).filter(Boolean),e),{}))}}async function F(){const e=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:new f.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:Object(E.b)(e.set),stickers:$(e.documents)}}async function L({query:e,hash:t}){const n=await Object(p.g)(new f.Api.messages.SearchStickerSets({q:e,hash:t}));if(n&&!(n instanceof f.Api.messages.FoundStickerSetsNotModified))return{hash:n.hash,sets:n.sets.map(E.c)}}async function q({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetSavedGifs({hash:e}));if(t&&!(t instanceof f.Api.messages.SavedGifsNotModified))return{hash:t.hash,gifs:J(t.gifs)}}async function H({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.InstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function K({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.UninstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function z({query:e,offset:t=""}){if(!O){const e=await Object(p.g)(new f.Api.help.GetConfig);if(!e)return;const t=await Object(p.g)(new f.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof f.Api.User))return;O=new f.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await Object(p.g)(new f.Api.messages.GetInlineBotResults({bot:O,peer:new f.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map(e=>{if(e instanceof f.Api.BotInlineMediaResult)return e.document}).filter(Boolean);return{nextOffset:n.nextOffset,gifs:J(s)}}async function G({emoji:e,hash:t=0}){const n=await Object(p.g)(new f.Api.messages.GetStickers({emoticon:e,hash:t}));if(n&&!(n instanceof f.Api.messages.StickersNotModified))return{stickers:$(n.stickers),hash:n.hash}}async function W({language:e,fromVersion:t}){const n=await Object(p.g)(new f.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce((e,t)=>(e[t.keyword]=t.emoticons,e),{})}}function $(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(E.a)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}function J(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(R.m)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}async function Z({username:e}){try{return await Object(p.g)(new f.Api.channels.CheckUsername({channel:new f.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Y({chat:e,username:t}){await Object(p.g)(new f.Api.channels.UpdateUsername({channel:Object(g.g)(e.id,e.accessHash),username:t}))&&T({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Q({chat:e}){const t=await Object(p.g)(new f.Api.messages.ExportChatInvite({peer:Object(g.i)(e.id,e.accessHash)}));t&&t instanceof f.Api.ChatInviteExported&&T({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const X={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"},ee={};let te;async function ne(){const e=await Object(p.g)(new f.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function se(e){return te({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise((e,t)=>{ee.resolve=e,ee.reject=t})}async function ie(e){try{return await Object(p.h)({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return ue(e),!1}}async function ae(e){try{return await Object(p.h)({currentPassword:e}),!0}catch(e){return ue(e),!1}}async function re(e,t,n,s){try{return await Object(p.h)({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}async function oe(e,t){try{return await Object(p.h)({currentPassword:e,newPassword:e,email:t,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}function ce(e){ee.resolve(e)}function ue(e){let t;if(e instanceof f.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=X[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),te({"@type":"updateTwoFaError",message:t})}var de=n(24),le=n(18),fe=n(14);const pe=["ar","fa"];function ge({firstName:e,lastName:t,about:n}){return Object(p.g)(new f.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function he(e){return Object(p.g)(new f.Api.account.CheckUsername({username:e}))}function me(e){return Object(p.g)(new f.Api.account.UpdateUsername({username:e}))}async function ye(e){const t=await Object(p.i)(e);return Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function be(e){const t=await Object(p.i)(e);await Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function _e(e){const t=await Object(p.g)(new f.Api.account.GetWallPapers({hash:e}));if(!t||t instanceof f.Api.account.WallPapersNotModified)return;const n=t.wallpapers.filter(e=>e instanceof f.Api.WallPaper&&e.document instanceof f.Api.Document&&(!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return n.forEach(e=>{b.a.documents[String(e.document.id)]=e.document}),{hash:t.hash,wallpapers:n.map(de.b).filter(Boolean)}}async function we(e){const t=await Object(p.i)(e),n=await Object(p.g)(new f.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new f.Api.WallPaperSettings}));if(!(n&&n instanceof f.Api.WallPaper))return;const s=Object(de.b)(n);return s?(b.a.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function ve(){const e=await Object(p.g)(new f.Api.contacts.GetBlocked({limit:i.f}));if(e)return je(e),{users:e.users.map(h.a).filter(Boolean),chats:e.chats.map(e=>Object(m.d)(e,void 0,!0)).filter(Boolean),blockedIds:e.blocked.map(e=>Object(m.j)(e.peerId)),totalCount:e instanceof f.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function Ae(e){return Object(p.g)(new f.Api.contacts.Block({id:Object(g.o)(e)}))}function Ie(e,t){return Object(p.g)(new f.Api.contacts.Unblock({id:Object(g.i)(e,t)}))}async function Pe(){const e=await Object(p.g)(new f.Api.account.GetAuthorizations);if(e)return e.authorizations.map(de.a)}function Ce(e){return Object(p.g)(new f.Api.account.ResetAuthorization({hash:l()(e)}))}function Se(){return Object(p.g)(new f.Api.auth.ResetAuthorizations)}async function Me(){const e=await Object(p.g)(new f.Api.account.GetNotifyExceptions({compareSound:!0}),!0);(e instanceof f.Api.Updates||e instanceof f.Api.UpdatesCombined)&&je(e)}async function ke(){const[e,t,n,s]=await Promise.all([Object(p.g)(new f.Api.account.GetContactSignUpNotification),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyUsers})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyChats})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyBroadcasts}))]);if(!t||!n||!s)return!1;const{silent:i,muteUntil:a,showPreviews:r}=t,{silent:o,muteUntil:c,showPreviews:u}=n,{silent:d,muteUntil:l,showPreviews:g}=s;return{hasContactJoinedNotifications:!e,hasPrivateChatsNotifications:!(i||"number"==typeof a&&Date.now()<1e3*a),hasPrivateChatsMessagePreview:r,hasGroupNotifications:!(o||"number"==typeof c&&Date.now()<1e3*c),hasGroupMessagePreview:u,hasBroadcastNotifications:!(d||"number"==typeof l&&Date.now()<1e3*l),hasBroadcastMessagePreview:g}}function Ee(e){return Object(p.g)(new f.Api.account.SetContactSignUpNotification({silent:e}))}function Re(e,{isSilent:t,shouldShowPreviews:n}){let s;s="contact"===e?new f.Api.InputNotifyUsers:"group"===e?new f.Api.InputNotifyChats:new f.Api.InputNotifyBroadcasts;const i={showPreviews:n,silent:t,muteUntil:t?2**31-1:void 0};return Object(p.g)(new f.Api.account.UpdateNotifySettings({peer:s,settings:new f.Api.InputPeerNotifySettings(i)}))}async function Ue(){const e=await Object(p.g)(new f.Api.langpack.GetLanguages({langPack:i.i}));if(e)return e.map(le.b)}async function Oe({sourceLangPacks:e,langCode:t}){const n=(await Promise.all(e.map(e=>Object(p.g)(new f.Api.langpack.GetLangPack({langPack:e,langCode:pe.includes(t)?t+"-raw":t}))))).filter(Boolean).map(e=>Object(fe.a)(e.strings.map(le.b),"key"));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function Te(e){const t=Object(g.k)(e),n=await Object(p.g)(new f.Api.account.GetPrivacy({key:t}));if(n)return je(n),Object(de.d)(n.rules)}function De(e){const t=Object(p.e)().session.getAuthKey().getKey();return Object(p.g)(new f.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Be(e){return Object(p.g)(new f.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function xe(e,t){const n=Object(g.k)(e),s=[];switch(t.allowedUsers&&s.push(new f.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.allowedChats&&s.push(new f.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map(({id:e})=>-e)})),t.blockedUsers&&s.push(new f.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.blockedChats&&s.push(new f.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map(({id:e})=>-e)})),t.visibility){case"everybody":s.push(new f.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new f.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new f.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new f.Api.InputPrivacyValueDisallowAll)}const i=await Object(p.g)(new f.Api.account.SetPrivacy({key:n,rules:s}));if(i)return je(i),Object(de.d)(i.rules)}function je(e){e.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof f.Api.Chat||e instanceof f.Api.Channel)&&(b.a.chats[e.id]=e)})}var Ne=n(72);function Ve(e){if(e)return Object.values(e).map(e=>({id:e.id,title:e.title,amount:e.prices.reduce((e,t)=>e+Number(t.amount.value),0),prices:e.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}))}))}async function Fe({messageId:e,requestInfo:t,shouldSave:n}){const s=await Object(p.g)(new f.Api.payments.ValidateRequestedInfo({msgId:e,save:n||void 0,info:Object(g.p)(t)}));if(!s)return;const{id:i,shippingOptions:a}=s;return i?{id:i,shippingOptions:Ve(a)}:void 0}function Le({messageId:e,requestedInfoId:t,shippingOptionId:n,credentials:s}){return Object(p.g)(new f.Api.payments.SendPaymentForm({msgId:e,requestedInfoId:t,shippingOptionId:n,credentials:new f.Api.InputPaymentCredentials({save:s.save,data:new f.Api.DataJSON({data:JSON.stringify(s.data)})})}),!0)}async function qe({messageId:e}){const t=await Object(p.g)(new f.Api.payments.GetPaymentForm({msgId:e}));if(t)return function(e){const{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,nativeParams:a,savedInfo:r,invoice:o}=e,{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:y}=o,b=y.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),_=a?JSON.parse(a.data):{};return{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,savedInfo:r,invoice:{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:b},nativeParams:{needCardholderName:_.need_cardholder_name,needCountry:_.need_country,needZip:_.need_zip,publishableKey:_.publishable_key}}}(t)}async function He(e){const t=await Object(p.g)(new f.Api.payments.GetPaymentReceipt({msgId:e}));if(t)return function(e){const{invoice:t,info:n,shipping:s,currency:i,totalAmount:a,credentialsTitle:r}=e,{shippingAddress:o,phone:c,name:u}=n||{},{prices:d}=t,l=d.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}));let f,p;return s&&(f=s.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),p=s.title),{currency:i,prices:l,info:{shippingAddress:o,phone:c,name:u},totalAmount:Number(a.value),credentialsTitle:r,shippingPrices:f,shippingMethod:p}}(t)}let Ke;async function ze(e,t){Ke=e,Object(r.a)(Ze),Object(o.a)(Ze),Object(c.p)(Ze),Object(u.m)(Ze),function(e){w=e}(Ze),function(e){U=e}(Ze),function(e){T=e}(Ze),function(e){te=e}(Ze),await Object(p.f)(Ze,t)}const Ge=Object(a.c)((function(e){if(!Je||e!==$e)return;const t=Je;Je=void 0,t.forEach(Ke)}));let We,$e,Je;function Ze(e){Je?Je.push(e):Je=[e],We&&!i.b.has(e["@type"])||(We=Object(a.b)(Ge,i.c,!0),$e=Math.random()),We($e)}self.onerror=e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const Ye=new Map;function Qe(e){Xe({type:"update",update:e})}function Xe(e,t){t?postMessage(e,[t]):postMessage(e)}i.g&&console.log(">>> FINISH LOAD WORKER"),onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await ze(Qe,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:a}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Xe({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ye.set(e,t),a.push(t)}const t=await function(e,...t){return s[e](...t)}(n,...a),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Xe({type:"methodResponse",messageId:e,response:t},i)}catch(t){i.g&&console.error(t),e&&Xe({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ye.delete(e);break}case"cancelProgress":{const e=Ye.get(t.messageId);e&&(e.isCanceled=!0);break}}}}]); -//# sourceMappingURL=7c2292f972e10d28cc51.worker.js.map \ No newline at end of file +/*! For license information please see 8ede9bdfe3390ee397af.worker.js.LICENSE.txt */ +!function(e){var t={};function n(s){if(t[s])return t[s].exports;var i=t[s]={i:s,l:!1,exports:{}};return e[s].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=e,n.c=t,n.d=function(e,t,s){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(n.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(s,i,function(t){return e[t]}.bind(null,i));return s},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=111)}([function(e,t,n){const s=n(6),i=n(81),a=n(59),r=n(21),o=n(99),c=n(100),u=n(20),d=n(29),l=n(104),f=n(42),p=n(8);e.exports={Api:s,TelegramClient:i,sessions:l,connection:a,extensions:f,tl:r,version:o,events:c,utils:u,errors:d,helpers:p}},function(e,t,n){"use strict";n.d(t,"f",(function(){return M})),n.d(t,"a",(function(){return k})),n.d(t,"b",(function(){return E})),n.d(t,"e",(function(){return R})),n.d(t,"g",(function(){return T})),n.d(t,"c",(function(){return D})),n.d(t,"i",(function(){return B})),n.d(t,"h",(function(){return x})),n.d(t,"d",(function(){return j}));var s={};n.r(s),n.d(s,"Type",(function(){return m})),n.d(s,"fetch",(function(){return y})),n.d(s,"save",(function(){return b})),n.d(s,"clear",(function(){return _}));var i=n(0),a=n(42),r=n(4),o=n(17),c=n(26),u=n(9),d=n(41),l=n(11),f=n(5),p=n(2),g=n(34);const h=self.caches;let m;async function y(e,t,n){if(h)try{const s=new Request(t),i=await h.open(e),a=await i.match(s);if(!a)return;switch(n){case m.Text:return await a.text();case m.Blob:{const e=await a.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=a.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case m.Json:return await a.json();default:return}}catch(e){return void console.warn(e)}}async function b(e,t,n){if(h)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),i=new Request(t),a=new Response(s),r=await h.open(e);return await r.put(i,a)}catch(e){return void console.warn(e)}}async function _(e){try{if(!h)return;return await h.delete(e)}catch(e){return void console.warn(e)}}async function w({url:e,mediaFormat:t,start:n,end:a},o,c,u){const{data:h,mimeType:m,fullSize:y}=await async function(e,t,n,s,a,o,c){const u=e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!u)return;if("file"===u[1]){const e=await fetch(u[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d,g=u[2];const h=u[3]?u[3].replace("?size=",""):void 0;let m;"avatar"===u[1]||"profile"===u[1]?(d=Object(p.s)(Number(g)),g=Math.abs(Number(g))):d=u[1];switch(d){case"channel":case"chat":m=f.a.chats[g];break;case"user":m=f.a.users[g];break;case"msg":m=f.a.messages[g];break;case"sticker":case"gif":case"wallpaper":m=f.a.documents[g];break;case"photo":m=f.a.photos[g];break;case"stickerSet":m=f.a.stickerSets[g]}if(!m)return;if(["msg","sticker","gif","wallpaper","photo"].includes(d)){c===l.ApiMediaFormat.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(m,{sizeType:h,start:a,end:o,progressCallback:s,workers:r.k});let n,u;return m instanceof i.Api.Message?(n=function(e,t){if(!e||!e.media)return;if(e.media instanceof i.Api.MessageMediaPhoto)return"image/jpeg";if(e.media instanceof i.Api.MessageMediaDocument&&e.media.document instanceof i.Api.Document)return t?e.media.document.attributes.some(e=>e instanceof i.Api.DocumentAttributeSticker)?"image/webp":"image/jpeg":e.media.document.mimeType;return}(m,h),m.media instanceof i.Api.MessageMediaDocument&&m.media.document instanceof i.Api.Document&&(u=m.media.document.size)):m instanceof i.Api.Photo?n="image/jpeg":"sticker"===d&&h?n="image/webp":(n=m.mimeType,u=m.size),{mimeType:n,data:e,fullSize:u}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(m);return{mimeType:c===l.ApiMediaFormat.Lottie?"application/json":v(e),data:e}}{const e=await t.downloadProfilePhoto(m,"profile"===u[1]);return{mimeType:v(e),data:e}}}(e,o,c,u,n,a,t)||{};if(!h)return;const _=await async function(e,t,n){switch(t){case l.ApiMediaFormat.DataUri:return Object(g.a)(new Blob([e],{type:n}));case l.ApiMediaFormat.BlobUrl:return new Blob([e],{type:n});case l.ApiMediaFormat.Lottie:{const t=Object(d.inflate)(e,{to:"string"});return JSON.parse(t)}case l.ApiMediaFormat.Progressive:return e.buffer}return}(h,t,m);if(!_)return;const w=t!==l.ApiMediaFormat.Progressive&&(t!==l.ApiMediaFormat.BlobUrl||_.size<=r.o);if(!r.n&&s&&w){b(e.startsWith("avatar")?r.q:r.p,e,_)}return{prepared:t===l.ApiMediaFormat.Progressive?"":function(e){if(e instanceof Blob)return URL.createObjectURL(e);return e}(_),arrayBuffer:t===l.ApiMediaFormat.Progressive?_:void 0,mimeType:m,fullSize:y}}function v(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce((e,t)=>e+t.toString(16),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(m||(m={}));var A=n(13);a.Logger.setLevel(r.h?"debug":"warn");const I={build:e=>e};let P,C,S=!1;async function M(e,t){P=e,r.g&&console.log(">>> START INIT API"),C=new i.TelegramClient(new i.sessions.CallbackSession(t,U),"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||"Unknown UserAgent",appVersion:r.d+" Z",useWSS:!0,additionalDcsDisabled:r.l}),C.addEventHandler(O,I),C.addEventHandler(c.b,I);try{r.g&&console.log("[GramJs/client] CONNECTING"),await C.start({phoneNumber:o.g,phoneCode:o.e,password:o.f,firstAndLastNames:o.i,qrCode:o.h,onError:o.b}),r.g&&(console.log(">>> FINISH INIT API"),console.log("[GramJs/client] CONNECTED")),Object(o.c)(),P({"@type":"updateApiReady"}),j()}catch(e){throw r.g&&console.log("[GramJs/client] CONNECTING ERROR",e),e}}async function k(){await T(new i.Api.auth.LogOut),await C.destroy()}async function E(){await C.disconnect()}function R(){return C}function U(e){P({"@type":"updateSession",sessionData:e})}function O(e){e instanceof i.connection.UpdateConnectionState?S=e.state===i.connection.UpdateConnectionState.connected:e instanceof i.Api.UpdatesTooLong&&async function(){try{await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&P({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}()}async function T(e,t=!1,n=!1){if(S)try{r.g&&console.log("[GramJs/client] INVOKE "+e.className);const n=await C.invoke(e);if(r.g&&console.log("[GramJs/client] INVOKE RESPONSE "+e.className,n),t){let t;n instanceof i.Api.Updates||n instanceof i.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof i.Api.Updates||n.updates instanceof i.Api.UpdatesCombined)&&(t=n.updates),t?(!function(e){const t=[...e.users,...e.chats];e.updates.forEach(e=>{t&&(e._entities=t)})}(t),t.updates.forEach(t=>{Object(c.b)(t,e)})):n instanceof i.Api.UpdatesTooLong||Object(c.b)(n,e)}return n}catch(t){if(r.g&&(console.log("[GramJs/client] INVOKE ERROR "+e.className),console.error(t)),function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof i.Api.messages.SendMessage||t instanceof i.Api.messages.SendMedia||t instanceof i.Api.messages.SendMultiMedia),{message:s}=e;P({"@type":"error",error:{message:s,isSlowMode:n}})}(t,e),n)throw t;return}else r.g&&console.warn(`[GramJs/client] INVOKE ERROR ${e.className}: Client is not connected`)}function D(e,t){return w(e,C,S,t)}function B(e,t){return C.uploadFile({file:e,onProgress:t,workers:r.w})}function x(e){return C.updateTwoFaSettings(e)}async function j(){const e=await T(new i.Api.users.GetFullUser({id:new i.Api.InputUserSelf}));if(!(e&&e.user instanceof i.Api.User))return;f.a.users[e.user.id]=e.user;const t=Object(A.b)(e);Object(u.o)(t.id),Object(o.d)(t)}},function(e,t,n){"use strict";(function(e){n.d(t,"s",(function(){return d})),n.d(t,"o",(function(){return l})),n.d(t,"i",(function(){return f})),n.d(t,"g",(function(){return g})),n.d(t,"l",(function(){return h})),n.d(t,"f",(function(){return m})),n.d(t,"h",(function(){return y})),n.d(t,"j",(function(){return b})),n.d(t,"d",(function(){return _})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return v})),n.d(t,"n",(function(){return A})),n.d(t,"q",(function(){return I})),n.d(t,"t",(function(){return P})),n.d(t,"u",(function(){return C})),n.d(t,"c",(function(){return S})),n.d(t,"e",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"a",(function(){return E})),n.d(t,"p",(function(){return R})),n.d(t,"k",(function(){return U}));var s=n(15),i=n.n(s),a=n(0),r=n(8),o=n(11),c=n(5),u=n(14);function d(e){return e>0?"user":e<=-1e9?"channel":"chat"}function l(e){return e>0?new a.Api.PeerUser({userId:e}):e<=-1e9?new a.Api.PeerChannel({channelId:-e}):new a.Api.PeerChat({chatId:-e})}function f(e,t){return e>0||e<=-1e9?e>0?new a.Api.InputPeerUser({userId:e,accessHash:i()(t)}):new a.Api.InputPeerChannel({channelId:-e,accessHash:i()(t)}):new a.Api.InputPeerChat({chatId:-e})}function p(e){if(e>0){const{accessHash:t}=c.a.users[e]||{};return t?new a.Api.InputPeerUser({userId:e,accessHash:t}):void 0}if(e<=-1e9){const{accessHash:t}=c.a.chats[-e]||{};return t?new a.Api.InputPeerChannel({channelId:-e,accessHash:t}):void 0}return new a.Api.InputPeerChat({chatId:-e})}function g(e,t){return e>0?new a.Api.InputUser({userId:e,accessHash:i()(t)}):e<=-1e9?new a.Api.InputChannel({channelId:-e,accessHash:i()(t)}):-e}function h(e,t){return new a.Api.InputStickerSetID({id:i()(e),accessHash:i()(t)})}function m(e){const t=c.a.documents[e.id];if(t)return new a.Api.InputDocument(Object(u.b)(t,["id","accessHash","fileReference"]))}function y(e){const t=m(e);if(t)return new a.Api.InputMediaDocument({id:t})}function b(t,n){const{summary:s,quiz:i}=t,r=new a.Api.Poll({id:n,publicVoters:s.isPublic,question:s.question,answers:s.answers.map(({text:t,option:n})=>new a.Api.PollAnswer({text:t,option:e.from(n)})),quiz:s.quiz,multipleChoice:s.multipleChoice});if(!i)return new a.Api.InputMediaPoll({poll:r});const o=i.correctAnswers.map(t=>e.from(t)),{solution:c}=i,u=i.solutionEntities?i.solutionEntities.map(A):[];return new a.Api.InputMediaPoll({poll:r,correctAnswers:o,...c&&{solution:c,solutionEntities:u}})}function _(e){const{emoticon:t,contacts:n,nonContacts:s,groups:i,channels:r,bots:o,excludeArchived:c,excludeMuted:u,excludeRead:d,pinnedChatIds:l,includedChatIds:f,excludedChatIds:g}=e,h=l?l.map(p).filter(Boolean):[],m=f?f.map(p).filter(Boolean):[],y=g?g.map(p).filter(Boolean):[];return new a.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:i||void 0,bots:o||void 0,excludeArchived:c||void 0,excludeMuted:u||void 0,excludeRead:d||void 0,broadcasts:r||void 0,pinnedPeers:h,includePeers:m,excludePeers:y})}function w(){return Object(r.readBigIntFromBuffer)(Object(r.generateRandomBytes)(8),!0,!0)}function v(e,t,n){return new a.Api.Message({id:e,peerId:l(t),fromId:l(t),media:n.media})}function A(e){const{type:t,offset:n,length:s,url:i,userId:r}=e,u=r?c.a.users[r]:void 0;switch(t){case o.ApiMessageEntityTypes.Bold:return new a.Api.MessageEntityBold({offset:n,length:s});case o.ApiMessageEntityTypes.Italic:return new a.Api.MessageEntityItalic({offset:n,length:s});case o.ApiMessageEntityTypes.Underline:return new a.Api.MessageEntityUnderline({offset:n,length:s});case o.ApiMessageEntityTypes.Strike:return new a.Api.MessageEntityStrike({offset:n,length:s});case o.ApiMessageEntityTypes.Code:return new a.Api.MessageEntityCode({offset:n,length:s});case o.ApiMessageEntityTypes.Pre:return new a.Api.MessageEntityPre({offset:n,length:s,language:""});case o.ApiMessageEntityTypes.Blockquote:return new a.Api.MessageEntityBlockquote({offset:n,length:s});case o.ApiMessageEntityTypes.TextUrl:return new a.Api.MessageEntityTextUrl({offset:n,length:s,url:i});case o.ApiMessageEntityTypes.Url:return new a.Api.MessageEntityUrl({offset:n,length:s});case o.ApiMessageEntityTypes.Hashtag:return new a.Api.MessageEntityHashtag({offset:n,length:s});case o.ApiMessageEntityTypes.MentionName:return new a.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new a.Api.InputUser({userId:r,accessHash:u.accessHash})});default:return new a.Api.MessageEntityUnknown({offset:n,length:s})}}function I(e){let t=0;return e.forEach(e=>{t=(20261*t&2147483647)+e&2147483647}),t}function P(e){const{media:t}=e;return!!t&&(t instanceof a.Api.MessageMediaPhoto||t instanceof a.Api.MessageMediaDocument||t instanceof a.Api.MessageMediaWebPage&&t.webpage instanceof a.Api.WebPage&&t.webpage.photo instanceof a.Api.Photo)}function C(e){return"photo"in e.action&&e.action.photo instanceof a.Api.Photo}function S(e){if(e instanceof a.Api.PhotoEmpty)return new a.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new a.Api.ChatPhoto({dcId:t,photoId:n})}function M({phone:e,firstName:t,lastName:n}){return new a.Api.InputPhoneContact({clientId:i()(1),phone:e,firstName:t,lastName:n})}function k(e,t=0){return new a.Api.ChatBannedRights({...e,untilDate:t})}function E(e){return new a.Api.ChatAdminRights(e)}function R(e){const{shippingAddress:t}=e;return new a.Api.PaymentRequestedInfo({...e,shippingAddress:t?new a.Api.PostAddress(t):void 0})}function U(e){switch(e){case"phoneNumber":return new a.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new a.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new a.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new a.Api.InputPrivacyKeyForwards;case"chatInvite":return new a.Api.InputPrivacyKeyChatInvite}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"k",(function(){return b})),n.d(t,"e",(function(){return v})),n.d(t,"f",(function(){return A})),n.d(t,"g",(function(){return I})),n.d(t,"h",(function(){return P})),n.d(t,"a",(function(){return C})),n.d(t,"b",(function(){return S}));var s=n(0),i=n(14);function a(e){return e.hasOwnProperty("userId")}function r(e){return e.hasOwnProperty("chatId")}var o=n(18);function c(e,t=!1){const n=Boolean("min"in e&&e.min),i="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&v(e.photo),r=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:r,...i&&{accessHash:i},...a&&{avatarHash:a},...(e instanceof s.Api.Channel||e instanceof s.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 s.Api.Chat||e instanceof s.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...d(e),..."creator"in e&&{isCreator:e.creator},...l(e),...f(e)}}function u(e,t){const{peer:n,folderId:s,unreadMark:i,unreadCount:a,unreadMentionsCount:r,notifySettings:{silent:o,muteUntil:u},readOutboxMaxId:d,readInboxMaxId:l}=e,f=o||"number"==typeof u&&Date.now()<1e3*u;return{id:h(n),...s&&{folderId:s},type:y(t),title:_(n,t),lastReadOutboxMessageId:d,lastReadInboxMessageId:l,unreadCount:a,unreadMentionsCount:r,isMuted:f,...i&&{hasUnreadMark:!0},...c(t)}}function d(e){return e instanceof s.Api.Chat||e instanceof s.Api.Channel?{adminRights:Object(o.b)(e.adminRights),currentUserBannedRights:e instanceof s.Api.Channel?Object(o.b)(e.bannedRights):void 0,defaultBannedRights:Object(o.b)(e.defaultBannedRights)}:{}}function l(e){if(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden)return{isRestricted:!0};if(e instanceof s.Api.User){const t=e.restricted?p(e.restrictionReason):void 0;return void 0===t?{isRestricted:!1}:{isRestricted:e.restricted,restrictionReason:t}}if(e instanceof s.Api.Chat)return{isNotJoined:e.left,isRestricted:e.kicked};if(e instanceof s.Api.Channel){const t=e.restricted&&e.restrictionReason&&e.restrictionReason.some(e=>"all"===e.platform);return{isNotJoined:e.left,isRestricted:t,restrictionReason:p(e.restrictionReason)}}return{}}function f(e){return e instanceof s.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof s.Api.InputChannelEmpty)?{migratedTo:{chatId:h(e.migratedTo),...e.migratedTo instanceof s.Api.InputChannel&&{accessHash:e.migratedTo.accessHash.toString()}}}:{}}function p(e){if(!e)return;const t=e.find(({platform:e})=>"all"===e);return t?Object(i.b)(t,["reason","text"]):void 0}function g(e,t=!1,n=!1){if(e instanceof s.Api.Chat||e instanceof s.Api.Channel||e instanceof s.Api.User||n&&(e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChannelForbidden))return{id:e instanceof s.Api.User?e.id:-e.id,type:y(e),title:e instanceof s.Api.User?w(e):e.title,...c(e,t)}}function h(e){return a(e)?e.userId:r(e)?-e.chatId:-e.channelId}function m(e){return function(e){return e.hasOwnProperty("userId")}(e)?e.userId:function(e){return e.hasOwnProperty("chatId")}(e)?-e.chatId:function(e){return e.hasOwnProperty("channelId")}(e)?-e.channelId:void 0}function y(e){return e instanceof s.Api.User||e instanceof s.Api.UserEmpty?"chatTypePrivate":e instanceof s.Api.Chat||e instanceof s.Api.ChatForbidden||e instanceof s.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function b(e){return a(e)?"user"+e.userId:r(e)?"chat"+e.chatId:"chat"+e.channelId}function _(e,t){return a(e)?w(t):t.title}function w(e){return e.firstName?`${e.firstName}${e.lastName?" "+e.lastName:""}`:e.lastName||void 0}function v(e){if("photoId"in e)return e.photoId.toString()}function A(e){return{userId:e instanceof s.Api.ChannelParticipantBanned||e instanceof s.Api.ChannelParticipantLeft?h(e.peer):e.userId,inviterId:"inviterId"in e?e.inviterId:void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?e.kickedBy:void 0,promotedByUserId:"promotedBy"in e?e.promotedBy:void 0,bannedRights:"bannedRights"in e?Object(o.b)(e.bannedRights):void 0,adminRights:"adminRights"in e?Object(o.b)(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof s.Api.ChannelParticipantAdmin||e instanceof s.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof s.Api.ChannelParticipantCreator||e instanceof s.Api.ChatParticipantCreator)&&{isOwner:!0}}}function I(e){return e instanceof s.Api.ChatParticipants||e instanceof s.Api.channels.ChannelParticipants?e.participants.map(A).filter(Boolean):void 0}function P(e){let t="";if(!(e.action instanceof s.Api.SendMessageCancelAction))return e.action instanceof s.Api.SendMessageTypingAction?t="lng_user_typing":e.action instanceof s.Api.SendMessageRecordVideoAction?t="lng_send_action_record_video":e.action instanceof s.Api.SendMessageUploadVideoAction?t="lng_send_action_upload_video":e.action instanceof s.Api.SendMessageRecordAudioAction?t="lng_send_action_record_audio":e.action instanceof s.Api.SendMessageUploadAudioAction?t="lng_send_action_upload_audio":e.action instanceof s.Api.SendMessageUploadPhotoAction?t="lng_send_action_upload_photo":e.action instanceof s.Api.SendMessageUploadDocumentAction?t="lng_send_action_upload_file":e.action instanceof s.Api.SendMessageGeoLocationAction?t="selecting a location to share":e.action instanceof s.Api.SendMessageChooseContactAction?t="selecting a contact to share":e.action instanceof s.Api.SendMessageGamePlayAction?t="lng_playing_game":e.action instanceof s.Api.SendMessageRecordRoundAction?t="lng_send_action_record_round":e.action instanceof s.Api.SendMessageUploadRoundAction&&(t="lng_send_action_upload_round"),{action:t,...!(e instanceof s.Api.UpdateUserTyping)&&{userId:h(e.fromId)},timestamp:Date.now()}}function C(e){return{...Object(i.c)(e,["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"]),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(m).filter(Boolean),includedChatIds:e.includePeers.map(m).filter(Boolean),excludedChatIds:e.excludePeers.map(m).filter(Boolean)}}function S({filter:e,description:t}){return{...C(e),description:t}}},function(e,t,n){"use strict";n.d(t,"d",(function(){return s})),n.d(t,"g",(function(){return i})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return r})),n.d(t,"n",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"q",(function(){return u})),n.d(t,"o",(function(){return d})),n.d(t,"c",(function(){return l})),n.d(t,"b",(function(){return f})),n.d(t,"k",(function(){return p})),n.d(t,"w",(function(){return g})),n.d(t,"r",(function(){return h})),n.d(t,"t",(function(){return m})),n.d(t,"f",(function(){return y})),n.d(t,"u",(function(){return b})),n.d(t,"m",(function(){return _})),n.d(t,"s",(function(){return w})),n.d(t,"v",(function(){return v})),n.d(t,"a",(function(){return A})),n.d(t,"e",(function(){return I})),n.d(t,"j",(function(){return P})),n.d(t,"i",(function(){return C}));const s="1.0.7",i=!1,a=!1,r=!1,o=!1,c="tt-media",u="tt-media-avatars",d=524288,l=300,f=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),p=16,g=16,h=("undefined"!=typeof window&&window.innerHeight,200),m=50,y=100,b=40,_=1e9,w="MEMOJI_STICKER",v=777e3,A=0,I=1,P=777,C="android"},function(e,t,n){"use strict";t.a={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{}}},function(e,t,n){(function(t){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{parseTl:i,serializeBytes:a,serializeDate:r}=n(44),{toSignedLittleBuffer:o}=n(8),c=n(79),u=n(80),d="undefined"!=typeof self&&void 0!==self.localStorage;function l(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,n){switch(n){case"int":{const n=t.alloc(4);return n.writeInt32LE(e,0),n}case"long":return o(e,8);case"int128":return o(e,16);case"int256":return o(e,32);case"double":{const n=t.alloc(8);return n.writeDoubleLE(e,0),n}case"string":return a(e);case"Bool":return e?t.from("b5757299","hex"):t.from("379779bc","hex");case"true":return t.alloc(0);case"bytes":return a(e);case"date":return r(e);default:return e.getBytes()}}function p(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let i=0;i{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}(g("constructor",e.constructors),g("request",e.requests))}()}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.d(t,"p",(function(){return g})),n.d(t,"j",(function(){return h})),n.d(t,"k",(function(){return m})),n.d(t,"w",(function(){return y})),n.d(t,"h",(function(){return b})),n.d(t,"u",(function(){return _})),n.d(t,"v",(function(){return w})),n.d(t,"a",(function(){return v})),n.d(t,"H",(function(){return A})),n.d(t,"b",(function(){return I})),n.d(t,"q",(function(){return P})),n.d(t,"r",(function(){return C})),n.d(t,"d",(function(){return S})),n.d(t,"c",(function(){return M})),n.d(t,"g",(function(){return k})),n.d(t,"z",(function(){return E})),n.d(t,"y",(function(){return R})),n.d(t,"i",(function(){return U})),n.d(t,"n",(function(){return O})),n.d(t,"f",(function(){return T})),n.d(t,"e",(function(){return D})),n.d(t,"A",(function(){return B})),n.d(t,"o",(function(){return x})),n.d(t,"B",(function(){return j})),n.d(t,"F",(function(){return N})),n.d(t,"G",(function(){return V})),n.d(t,"E",(function(){return F})),n.d(t,"I",(function(){return L})),n.d(t,"D",(function(){return q})),n.d(t,"C",(function(){return H})),n.d(t,"m",(function(){return K})),n.d(t,"l",(function(){return z})),n.d(t,"x",(function(){return G})),n.d(t,"s",(function(){return W})),n.d(t,"t",(function(){return $}));var s=n(0),i=n(4),a=n(1),r=n(3),o=n(9),c=n(13),u=n(14),d=n(5),l=n(2),f=n(16);let p;function g(e){p=e}async function h({limit:e,offsetDate:t,archived:n,withPinned:d}){const l=await Object(a.g)(new s.Api.messages.GetDialogs({offsetPeer:new s.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?i.e:void 0,...d&&{excludePinned:!0}})),f=d?await Object(a.g)(new s.Api.messages.GetPinnedDialogs({folderId:n?i.e:void 0})):void 0;if(!l||l instanceof s.Api.messages.DialogsNotModified)return;Z(l),f&&Z(f);const p=Object(u.a)([...l.messages,...f?f.messages:[]].map(o.b).filter(Boolean),"chatId"),g={...J(l),...f&&J(f)},h=[],m={},y={},b=[...f?f.dialogs:[],...l.dialogs],_=[];b.forEach(e=>{if(!(e instanceof s.Api.Dialog)||!n&&e.folderId===i.e||n&&e.folderId!==i.e)return;const t=g[Object(r.k)(e.peer)],a=Object(r.c)(e,t);if(a.lastMessage=p[a.id],h.push(a),d&&e.pinned&&_.push(a.id),e.draft){const{formattedText:t,replyingToId:n}=Object(o.h)(e.draft)||{};t&&(m[a.id]=t),n&&(y[a.id]=n)}});const w=[...l.users,...f?f.users:[]].map(c.a).filter(Boolean),v=h.map(e=>e.id);let A;return A=l instanceof s.Api.messages.DialogsSlice?l.count:v.length,{chatIds:v,chats:h,users:w,draftsById:m,replyingToById:y,orderedPinnedIds:d?_:void 0,totalChatCount:A}}function m(e){const{id:t,accessHash:n,adminRights:i}=e;return Object(l.g)(t,n)instanceof s.Api.InputChannel?async function(e,t,n){const i=await Object(a.g)(new s.Api.channels.GetFullChannel({channel:Object(l.g)(e,t)}));if(!(i&&i.fullChat instanceof s.Api.ChannelFull))return;const{about:o,onlineCount:c,exportedInvite:u,slowmodeSeconds:d,slowmodeNextSendDate:f,migratedFromChatId:p,migratedFromMaxId:g,canViewParticipants:h,linkedChatId:m,hiddenPrehistory:y,call:b}=i.fullChat,_=u instanceof s.Api.ChatInviteExported?u.link:void 0,{members:w,users:v}=h&&await K(e,t)||{},{members:A,users:I}=h&&n&&await K(e,t,"kicked")||{},{members:P,users:C}=h&&n&&await K(e,t,"admin")||{};return{fullInfo:{about:o,onlineCount:c,inviteLink:_,slowMode:d?{seconds:d,nextSendDate:f}:void 0,migratedFrom:p?{chatId:Object(r.j)({chatId:p}),maxMessageId:g}:void 0,canViewMembers:h,isPreHistoryHidden:y,members:w,kickedMembers:A,adminMembers:P,groupCallId:b?b.id.toString():void 0,linkedChatId:m?Object(r.j)({chatId:m}):void 0},users:[...v||[],...I||[],...C||[]]}}(t,n,i):async function(e){const t=await Object(a.g)(new s.Api.messages.GetFullChat({chatId:Object(l.g)(e)}));if(!(t&&t.fullChat instanceof s.Api.ChatFull))return;Z(t);const{about:n,participants:i,exportedInvite:o}=t.fullChat,u=Object(r.g)(i),d=u?u.filter(({isAdmin:e,isOwner:t})=>e||t):void 0;return{fullInfo:{about:n,members:u,adminMembers:d,canViewMembers:!0,...o&&{inviteLink:o.link}},users:t.users.map(c.a).filter(Boolean)}}(t)}async function y({query:e}){const t=await Object(a.g)(new s.Api.contacts.Search({q:e}));if(!t)return;Z(t);const n=t.myResults.map(r.j),i=[...t.chats,...t.users].map(e=>Object(r.d)(e)).filter(Boolean),o=t.users.map(c.a).filter(e=>!!e&&!e.isSelf);return{localChats:i.filter(e=>n.includes(e.id)),localUsers:o.filter(e=>n.includes(e.id)),globalChats:i.filter(e=>!n.includes(e.id)),globalUsers:o.filter(e=>!n.includes(e.id))}}async function b({type:e,user:t}){let n;if("self"===e||"user"===e){const i=await Object(a.g)(new s.Api.users.GetUsers({id:["user"===e&&t?Object(l.g)(t.id,t.accessHash):new s.Api.InputUserSelf]}));if(!i||!i.length)return;[n]=i}else if("support"===e){const e=await Object(a.g)(new s.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const i=Object(r.d)(n,"support"===e);if(i)return p({"@type":"updateChat",id:i.id,chat:i}),{chatId:i.id}}async function _(e){const{id:t,accessHash:n}=e,i=await Object(a.g)(new s.Api.messages.GetPeerDialogs({peers:[new s.Api.InputDialogPeer({peer:Object(l.i)(t,n)})]}));if(!i)return;const c=i.dialogs[0];if(!(c&&c instanceof s.Api.Dialog))return;const u=J(i)[Object(r.k)(c.peer)];if(!u)return;Z(i);const d=Object(o.b)(i.messages[0]);p({"@type":"updateChat",id:t,chat:{...Object(r.c)(c,u),lastMessage:d}})}function w({chat:e,text:t,entities:n,replyToMsgId:i}){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:t,...n&&{entities:n.map(l.n)},replyToMsgId:i}))}function v(e){return Object(a.g)(new s.Api.messages.SaveDraft({peer:Object(l.i)(e.id,e.accessHash),message:""}))}async function A({chat:e,isMuted:t}){await Object(a.g)(new s.Api.account.UpdateNotifySettings({peer:new s.Api.InputNotifyPeer({peer:Object(l.i)(e.id,e.accessHash)}),settings:new s.Api.InputPeerNotifySettings({muteUntil:t?2**31-1:void 0})})),_(e)}async function I({title:e,about:t,users:n}){const o=await Object(a.g)(new s.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(o instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected channel creation update",o));const c=o.chats[0];if(!(c&&c instanceof s.Api.Channel))return void(i.g&&console.error("Created channel not found",o));const u=Object(r.d)(c);return await Object(a.g)(new s.Api.channels.InviteToChannel({channel:Object(l.g)(u.id,u.accessHash),users:n.map(({id:e,accessHash:t})=>Object(l.g)(e,t))})),u}function P({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.JoinChannel({channel:Object(l.g)(e,t)}),!0)}function C({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.LeaveChannel({channel:Object(l.g)(e,t)}),!0)}function S({channelId:e,accessHash:t}){return Object(a.g)(new s.Api.channels.DeleteChannel({channel:Object(l.g)(e,t)}),!0)}async function M({title:e,users:t}){const n=await Object(a.g)(new s.Api.messages.CreateChat({title:e,users:t.map(({id:e,accessHash:t})=>Object(l.g)(e,t))}),!0);if(!(n instanceof s.Api.Updates))return void(i.g&&console.error("Unexpected chat creation update",n));const o=n.chats[0];if(o&&o instanceof s.Api.Chat)return Object(r.d)(o);i.g&&console.error("Created chat not found",n)}async function k({chatId:e,accessHash:t,photo:n}){const i=await Object(a.i)(n),r=Object(l.g)(e,t);return Object(a.g)(r instanceof s.Api.InputChannel?new s.Api.channels.EditPhoto({channel:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}):new s.Api.messages.EditChatPhoto({chatId:r,photo:new s.Api.InputChatUploadedPhoto({file:i})}),!0)}async function E({chat:e,shouldBePinned:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.ToggleDialogPin({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),pinned:t||void 0}))&&p({"@type":"updateChatPinned",id:e.id,isPinned:t})}function R({chat:e,folderId:t}){const{id:n,accessHash:i}=e;return Object(a.g)(new s.Api.folders.EditPeerFolders({folderPeers:[new s.Api.InputFolderPeer({peer:Object(l.i)(n,i),folderId:t})]}),!0)}async function U(){const e=await Object(a.g)(new s.Api.messages.GetDialogFilters);if(e)return{byId:Object(u.a)(e.map(r.a),"id"),orderedIds:e.map(({id:e})=>e)}}async function O(){const e=await Object(a.g)(new s.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(r.b)}async function T({id:e,folderUpdate:t}){const n=Object(l.d)(t);await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&p({"@type":"updateChatFolder",id:e,folder:t})}async function D(e){const t=await Object(a.g)(new s.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await O();t&&p({"@type":"updateChatFolder",id:e,folder:void 0}),n&&p({"@type":"updateRecommendedChatFolders",folders:n})}async function B({chat:e,hasUnreadMark:t}){const{id:n,accessHash:i}=e;await Object(a.g)(new s.Api.messages.MarkDialogUnread({peer:new s.Api.InputDialogPeer({peer:Object(l.i)(n,i)}),unread:t||void 0}))&&p({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function x(e){const t=await Object(a.g)(new s.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:i}=t,o=i.length?Object(r.d)(i[0]):Object(r.d)(n[0]);return o?(Z(t),o):void 0}function j({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.TogglePreHistoryHidden({channel:r,enabled:t}),!0)}function N({chat:e,bannedRights:t}){const{id:n,accessHash:i}=e,r=Object(l.i)(n,i);return Object(a.g)(new s.Api.messages.EditChatDefaultBannedRights({peer:r,bannedRights:Object(l.b)(t)}),!0)}function V({chat:e,user:t,bannedRights:n}){const i=Object(l.g)(e.id,e.accessHash),r=Object(l.i)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditBanned({channel:i,participant:r,bannedRights:Object(l.b)(n)}),!0)}function F({chat:e,user:t,adminRights:n,customTitle:i=""}){const r=Object(l.g)(e.id,e.accessHash),o=Object(l.g)(t.id,t.accessHash);return Object(a.g)(new s.Api.channels.EditAdmin({channel:r,userId:o,adminRights:Object(l.a)(n),rank:i}),!0)}async function L(e,t){const n=Object(l.g)(e.id,e.accessHash);await Object(a.g)(n instanceof s.Api.InputChannel?new s.Api.channels.EditTitle({channel:n,title:t}):new s.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function q(e,t){await Object(a.g)(new s.Api.messages.EditChatAbout({peer:Object(l.i)(e.id,e.accessHash),about:t}))&&p({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function H({chat:e,isEnabled:t}){const{id:n,accessHash:i}=e,r=Object(l.g)(n,i);return Object(a.g)(new s.Api.channels.ToggleSignatures({channel:r,enabled:t}),!0)}async function K(e,t,n="recent",o){let u;switch(n){case"kicked":u=new s.Api.ChannelParticipantsKicked({q:""});break;case"admin":u=new s.Api.ChannelParticipantsAdmins;break;default:u=new s.Api.ChannelParticipantsRecent}const d=await Object(a.g)(new s.Api.channels.GetParticipants({channel:Object(l.g)(e,t),filter:u,offset:o,limit:i.r}));if(d&&!(d instanceof s.Api.channels.ChannelParticipantsNotModified))return Z(d),{members:Object(r.g)(d),users:d.users.map(c.a).filter(Boolean)}}async function z(){const e=await Object(a.g)(new s.Api.channels.GetGroupsForDiscussion);if(e)return Z(e),e.chats.map(e=>Object(r.d)(e))}function G({channel:e,chat:t}){return Object(a.g)(new s.Api.channels.SetDiscussionGroup({broadcast:Object(l.i)(e.id,e.accessHash),group:t?Object(l.i)(t.id,t.accessHash):new s.Api.InputChannelEmpty}))}async function W(e){const t=await Object(a.g)(new s.Api.messages.MigrateChat({chatId:Object(l.g)(e.id)}),!0);if(t&&t instanceof s.Api.Updates)return Z(t),Object(r.d)(t.chats[1]);i.g&&console.error("Unexpected channel creation update",t)}async function $(e){const t=await Object(a.g)(new s.Api.messages.CheckChatInvite({hash:e}));if(t)return t instanceof s.Api.ChatInvite?void await Object(a.g)(new s.Api.messages.ImportChatInvite({hash:e}),!0):Object(r.d)(t.chat)}function J(e){const t={};return e.chats.forEach(e=>{t["chat"+e.id]=e}),e.users.forEach(e=>{t["user"+e.id]=e}),t}function Z(e){"users"in e&&e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),"chats"in e&&e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),"messages"in e&&e.messages.forEach(e=>{e instanceof s.Api.Message&&Object(l.t)(e)&&Object(f.a)(e)})}},function(e,t,n){(function(t){const s=n(15),i=n(35);function a(e,n=!0,i=!1){let a=t.from(e);const r=a.length;n&&(a=a.reverse());let o=s(a.toString("hex"),16);return i&&Math.floor(o.toString("2").length/8)>=r&&(o=o.subtract(s(2).pow(s(8*r)))),o}function r(e,n=8){const i=s(e),a=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0},generateRandomBytes:c,generateKeyDataFromNonce:async function(e,n){e=r(e,16),n=r(n,32);const[s,i,a]=await Promise.all([u(t.concat([n,e])),u(t.concat([e,n])),u(t.concat([n,n]))]);return{key:t.concat([s,i.slice(0,12)]),iv:t.concat([i.slice(12,20),a,n.slice(0,4)])}},sha1:u,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 i=s.one,a=e;for(;t.greater(s.zero);){const e=t.remainder(s(2));t=t.divide(s(2)),e.eq(s.one)&&(i=i.multiply(a),i=i.remainder(n)),a=a.multiply(a),a=a.remainder(n)}return i},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise(t=>setTimeout(t,e)),getByteArray:function(e,t=!1){const n=e.toString(2).length,i=Math.floor((n+8-1)/8);return o(s(e),i,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const n=t.alloc(4*e.length);for(let t=0;t1?"s":""})`}}else if(e instanceof s.Api.MessageActionContactSignUp)o="%action_origin% joined Telegram";else if(e instanceof s.Api.MessageActionPaymentSent){const t=l(e.currency),n=(Number(e.totalAmount)/100).toFixed(2);o=`You successfully transferred ${t}${n} to shop for %product%`}else if(e instanceof s.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);o=`Voice chat ended (${t} min${t>1?"s":""})`}else o="Voice chat started";else o="%ACTION_NOT_IMPLEMENTED%";"photo"in e&&e.photo instanceof s.Api.Photo&&(Object(p.b)(e.photo),a=Object(c.a)(e.photo));return{text:o,type:u,targetUserId:d,targetChatId:f,photo:a}}(t.action,n,Boolean(t.post),a);u&&(o.action=u);const{replyToMsgId:d,replyToTopId:f}=t.replyTo||{},h=t.editDate&&!t.editHide,{inlineButtons:m,keyboardButtons:y}=function(e){const{id:t,replyMarkup:n,media:i}=e;if(!n)return i instanceof s.Api.MessageMediaWebPage&&i.webpage instanceof s.Api.WebPage&&"telegram_message"===i.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:i.webpage.url}]]}:void 0;if(!(n instanceof s.Api.ReplyKeyboardMarkup||n instanceof s.Api.ReplyInlineMarkup))return;const a=n.rows.map(({buttons:e})=>e.map(e=>{let n,a,{text:r}=e;return e instanceof s.Api.KeyboardButton?(n="command",a=r):e instanceof s.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof s.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof s.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof s.Api.KeyboardButtonBuy?(i instanceof s.Api.MessageMediaInvoice&&i.receiptMsgId&&(r="Receipt",a=i.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:r,messageId:t,value:a}}));return{[n instanceof s.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a}}(t)||{},b=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&Object(r.j)(e.savedFromPeer),s=e.fromId&&Object(r.j)(e.fromId);return{isChannelPost:Boolean(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,i),{replies:_,mediaUnread:w,postAuthor:v}=t,I=t.groupedId&&t.groupedId.toString(),C=Boolean(I)&&!(o.document||o.audio),S=t.replyMarkup instanceof s.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:a,content:o,date:t.date,senderId:n||t.out&&t.post&&g||e,views:t.views,isFromScheduled:t.fromScheduled,...d&&{replyToMessageId:d},...f&&{replyToTopMessageId:f},...b&&{forwardInfo:b},...h&&{isEdited:h},...w&&{isMediaUnread:w},...t.mentioned&&w&&{hasUnreadMention:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:m,...y&&{keyboardButtons:y},...S&&{shouldHideKeyboardButtons:S},...t.viaBotId&&{viaBotId:t.viaBotId},..._&&_.comments&&{threadInfo:B(_,t.id,e)},...v&&{adminTitle:v}}}function A(e,t){return{text:e,...t&&{entities:t.map(D)}}}function I(e){if(!(e instanceof s.Api.DraftMessageEmpty)&&e.message)return{formattedText:A(e.message,e.entities),replyingToId:e.replyToMsgId}}function P(e){const t=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;return Object(o.a)(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(!(e instanceof s.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof s.Api.Photo))return;if(e.ttlSeconds)return;return Object(c.a)(e.photo)}(e);if(n)return{photo:n};const i=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document instanceof s.Api.Document&&e.document.mimeType.startsWith("video")))return;return C(e.document)}(e);if(i)return{video:i};const r=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||t.voice)return;return{fileName:R(e.document,"audio"),...Object(a.b)(e.document,["size","mimeType"]),...Object(a.b)(t,["duration","performer","title"])}}(e);if(r)return{audio:r};const u=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document&&e.document instanceof s.Api.Document))return;const t=e.document.attributes.find(e=>e instanceof s.Api.DocumentAttributeAudio);if(!t||!t.voice)return;const{duration:n,waveform:i}=t;return{duration:n,waveform:i?Array.from(i):void 0}}(e);if(u)return{voice:u};const d=function(e){if(!(e instanceof s.Api.MessageMediaDocument&&e.document))return;if(e.ttlSeconds)return;return S(e.document)}(e);if(d)return{document:d};const f=function(e){if(!(e instanceof s.Api.MessageMediaContact))return;return Object(a.b)(e,["firstName","lastName","phoneNumber","userId"])}(e);if(f)return{contact:f};const p=function(e){if(!(e instanceof s.Api.MessageMediaPoll))return;return M(e.poll,e.results)}(e);if(p)return{poll:p};const g=E(e);if(g)return{webPage:g};const h=function(e){if(!(e instanceof s.Api.MessageMediaInvoice))return;return function(e){const{description:t,title:n,photo:s,test:i,totalAmount:a,currency:r,receiptMsgId:o}=e,c=l(r);return{text:t,title:n,photoUrl:s&&s.url,receiptMsgId:o,description:`${c}${(Number(a)/100).toFixed(2)} ${i?"TEST INVOICE":""}`}}(e)}(e);return h?{invoice:h}:void 0}function C(e){if(e instanceof s.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:i,size:a,attributes:r}=e,o=r.find(e=>e instanceof s.Api.DocumentAttributeVideo);if(!o)return;const u=r.find(e=>e instanceof s.Api.DocumentAttributeAnimated),{duration:d,w:l,h:f,supportsStreaming:p=!1,roundMessage:g=!1}=o;return{id:String(t),mimeType:n,duration:d,fileName:R(e,"video"),width:l,height:f,supportsStreaming:p,isRound:g,isGif:Boolean(u),thumbnail:Object(c.e)(i),size:a}}function S(e){if(!(e instanceof s.Api.Document))return;const{id:t,size:n,mimeType:i,date:a,thumbs:r}=e,o=r&&Object(c.e)(r);return{id:String(t),size:n,mimeType:i,timestamp:a,fileName:R(e),thumbnail:o}}function M(e,t){const{id:n,answers:s}=e,i=s.map(e=>({text:e.text,option:String.fromCharCode(...e.option)}));return{id:n.toString(),summary:{isPublic:e.publicVoters,...Object(a.b)(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:i},results:k(t)}}function k(e){const{results:t,totalVoters:n,recentVoters:s,solution:i,solutionEntities:a}=e;return{totalVoters:n,recentVoterIds:s,results:t&&t.map(({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})),solution:i,...a&&{solutionEntities:a.map(D)}}}function E(e){if(!(e instanceof s.Api.MessageMediaWebPage&&e.webpage instanceof s.Api.WebPage))return;const{id:t,photo:n,document:i}=e.webpage;return{id:Number(t),...Object(a.b)(e.webpage,["url","displayUrl","siteName","title","description"]),photo:n&&n instanceof s.Api.Photo?{id:String(n.id),thumbnail:Object(c.e)(n.sizes),sizes:n.sizes.filter(e=>e instanceof s.Api.PhotoSize).map(c.b)}:void 0,...i&&{hasDocument:!0}}}function R(e,t="file"){const{mimeType:n,attributes:i}=e,a=i.find(e=>e instanceof s.Api.DocumentAttributeFilename);if(a)return a.fileName;const r=n.split("/")[1];return`${t}${String(e.id)}.${r}`}function U(e,t,n,s,i,a,r,o,c,d){const l=h++,f=i&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:i,size:a}=e;if(e.quick){const{width:r,height:o,duration:c}=e.quick;return i.startsWith("image/")?{photo:{id:"temp",sizes:[],thumbnail:{width:r,height:o,dataUri:""},blobUrl:n}}:{video:{id:"temp",mimeType:i,duration:c||0,fileName:t,width:r,height:o,blobUrl:n,...s&&{thumbnail:{width:r,height:o,dataUri:s}},size:a}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=Object(u.a)(n,63);return{voice:{duration:t,waveform:s}}}return i.startsWith("audio/")?{audio:{mimeType:i,fileName:t,size:a,duration:200}}:{document:{mimeType:i,fileName:t,size:a,...s&&{previewBlobUrl:s}}}}(i),p="chatTypeChannel"===e.type;return{id:l,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...a&&{sticker:a},...r&&{video:r},...o&&T(o,l)},date:d||Math.round(Date.now()/1e3),isOutgoing:!p,senderId:g,...s&&{replyToMessageId:s},...c&&{groupedId:c,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}function O(e,t){const n=h++,{content:s,chatId:i,id:a,senderId:r,groupedId:o,isInAlbum:c}=t,u=s.audio,d=e.id===g&&(i!==e.id||t.forwardInfo)&&!u;return{id:n,chatId:e.id,content:s,date:Math.round(Date.now()/1e3),isOutgoing:!d&&"chatTypeChannel"!==e.type,senderId:g,sendingState:"messageSendingStatePending",...r!==g&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:i,fromMessageId:a,senderUserId:r}},groupedId:o,isInAlbum:c}}function T(e,t){return{poll:{id:t.toString(),summary:Object(a.b)(e.summary,["question","answers"]),results:{}}}}function D(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function B(e,t,n){const{channelId:s,replies:a,maxId:o,readMaxId:c,recentRepliers:u}=e;if(s===i.j)return;return{threadId:t,...n!==s?{chatId:Object(r.j)({channelId:s}),originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:o,lastReadInboxMessageId:c,...u&&{recentReplierIds:u.map(r.j)}}}},function(e,t,n){"use strict";(function(e){n.d(t,"m",(function(){return y})),n.d(t,"g",(function(){return b})),n.d(t,"e",(function(){return _})),n.d(t,"v",(function(){return v})),n.d(t,"d",(function(){return I})),n.d(t,"s",(function(){return P})),n.d(t,"q",(function(){return S})),n.d(t,"y",(function(){return M})),n.d(t,"b",(function(){return k})),n.d(t,"c",(function(){return E})),n.d(t,"a",(function(){return R})),n.d(t,"o",(function(){return U})),n.d(t,"p",(function(){return O})),n.d(t,"r",(function(){return T})),n.d(t,"u",(function(){return D})),n.d(t,"t",(function(){return B})),n.d(t,"j",(function(){return x})),n.d(t,"w",(function(){return j})),n.d(t,"n",(function(){return N})),n.d(t,"l",(function(){return V})),n.d(t,"k",(function(){return F})),n.d(t,"i",(function(){return L})),n.d(t,"x",(function(){return q})),n.d(t,"f",(function(){return H})),n.d(t,"h",(function(){return z}));var s=n(0),i=n(11),a=n(4),r=n(1),o=n(9),c=n(13),u=n(2),d=n(5),l=n(3),f=n(34),p=n(16),g=n(33),h=n(7);let m;function y(e){m=e}async function b({chat:e,threadId:t,...n}){const a=t===i.MAIN_THREAD_ID?s.Api.messages.GetHistory:s.Api.messages.GetReplies;let d;try{d=await Object(r.g)(new a({peer:Object(u.i)(e.id,e.accessHash),...t!==i.MAIN_THREAD_ID&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&m({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!d||d instanceof s.Api.messages.MessagesNotModified||!d.messages)return;K(d);const f=d.messages.map(o.b).filter(Boolean),p=d.users.map(c.a).filter(Boolean),g=d.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=f.map(({threadInfo:e})=>e).filter(Boolean);return{messages:f,users:p,chats:g,threadInfos:h}}async function _({chat:e,messageId:t}){const n="channel"===Object(u.s)(e.id),a=await Object(r.g)(n?new s.Api.channels.GetMessages({channel:Object(u.g)(e.id,e.accessHash),id:[new s.Api.InputMessageID({id:t})]}):new s.Api.messages.GetMessages({id:[new s.Api.InputMessageID({id:t})]}));if(!a||a instanceof s.Api.messages.MessagesNotModified)return;const d=a.messages[0];if(!d)return;if(d instanceof s.Api.MessageEmpty)return i.MESSAGE_DELETED;const l=d&&Object(o.b)(d);if(!l)return;d instanceof s.Api.Message&&Object(p.a)(d);return{message:l,users:a.users.map(c.a).filter(Boolean)}}let w=Promise.resolve();function v({chat:e,text:t,entities:n,replyingTo:i,attachment:c,sticker:l,gif:f,poll:p,isSilent:g,scheduledAt:h,groupedId:y,noWebPage:b},_){const v=Object(o.g)(e,t,n,i,c,l,f,p,y,h);m({"@type":v.isScheduled?"newScheduledMessage":"newMessage",id:v.id,chatId:e.id,message:v}),setTimeout(()=>{m({"@type":v.isScheduled?"updateScheduledMessage":"updateMessage",id:v.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})},1e3);const I=Object(u.r)();if(d.a.localMessages[I.toString()]=v,y)return function({chat:e,text:t,entities:n,replyingTo:i,attachment:o,groupedId:c,isSilent:d,scheduledAt:l},f,p,g){let h=-1;A[c]||(A[c]={counter:0,singleMediaByIndex:{}});h=A[c].counter++;const m=w;return w=(async()=>{let y;try{y=await C(p,o,g)}catch(e){return a.g&&console.warn(e),A[c].counter--,void await m}const b=await async function(e,t){const n=await Object(r.g)(new s.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof s.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof s.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaPhoto({id:new s.Api.InputPhoto({id:e,accessHash:t,fileReference:i})})}if(n instanceof s.Api.MessageMediaDocument&&n.document&&n.document instanceof s.Api.Document){const{document:{id:e,accessHash:t,fileReference:i}}=n;return new s.Api.InputMediaDocument({id:new s.Api.InputDocument({id:e,accessHash:t,fileReference:i})})}return}(Object(u.i)(e.id,e.accessHash),y);if(await m,!b)return A[c].counter--,void(a.g&&console.warn("Failed to upload grouped media"));if(A[c].singleMediaByIndex[h]=new s.Api.InputSingleMedia({media:b,randomId:f,message:t||"",entities:n?n.map(u.n):void 0}),Object.keys(A[c].singleMediaByIndex).length{let o;if(c)try{o=await C(v,c,_)}catch(e){return a.g&&console.warn(e),void await P}else l?o=Object(u.h)(l):f?o=Object(u.h)(f):p&&(o=Object(u.j)(p,I));await P;const d=o?s.Api.messages.SendMedia:s.Api.messages.SendMessage;await Object(r.g)(new d({clearDraft:!0,message:t||"",entities:n?n.map(u.n):void 0,peer:Object(u.i)(e.id,e.accessHash),randomId:I,...g&&{silent:g},...h&&{scheduleDate:h},...i&&{replyToMsgId:i},...o&&{media:o},...b&&{noWebpage:b}}),!0)})(),w}const A={};async function I({chat:e,message:t,text:n,entities:i,noWebPage:a}){const o=1e3*t.date>Date.now(),c={content:{...t.content,...n&&{text:{text:n,entities:i}}}};m({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:c}),d.a.localMessages[t.id]={...t,...c};const l=i&&i.map(u.n);await Object(r.g)(new s.Api.messages.EditMessage({message:n||"",entities:l,peer:Object(u.i)(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function P({chat:e,message:t,scheduledAt:n}){await Object(r.g)(new s.Api.messages.EditMessage({peer:Object(u.i)(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function C(t,n,i){const{filename:a,blobUrl:o,mimeType:c,quick:u,voice:d}=n,l=await Object(f.b)(o,a),p=e=>{i.isCanceled?p.isCanceled=!0:i(e,t.id)},h=await Object(r.i)(l,p),m=[new s.Api.DocumentAttributeFilename({fileName:a})];if(u){if(c.startsWith("image/"))return new s.Api.InputMediaUploadedPhoto({file:h});{const{width:e,height:t,duration:n}=u;void 0!==n&&m.push(new s.Api.DocumentAttributeVideo({duration:n,w:e,h:t}))}}if(d){const{duration:t,waveform:n}=d,{data:i}=Object(g.a)(n,63);m.push(new s.Api.DocumentAttributeAudio({voice:!0,duration:t,waveform:e.from(i)}))}return new s.Api.InputMediaUploadedDocument({file:h,mimeType:c,attributes:m})}async function S({chat:e,messageId:t,isUnpin:n,isOneSide:i,isSilent:a}){await Object(r.g)(new s.Api.messages.UpdatePinnedMessage({peer:Object(u.i)(e.id,e.accessHash),id:t,...n&&{unpin:!0},...i&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function M({chat:e}){await Object(r.g)(new s.Api.messages.UnpinAllMessages({peer:Object(u.i)(e.id,e.accessHash)}),!0)}async function k({chat:e,messageIds:t,shouldDeleteForAll:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteMessages({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&m({"@type":"deleteMessages",ids:t,...i&&{chatId:e.id}})}async function E({chat:e,messageIds:t}){await Object(r.g)(new s.Api.messages.DeleteScheduledMessages({peer:Object(u.i)(e.id,e.accessHash),id:t}))&&m({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function R({chat:e,shouldDeleteForAll:t,maxId:n}){const i="channel"===Object(u.s)(e.id);await Object(r.g)(i?new s.Api.channels.DeleteHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n}):new s.Api.messages.DeleteHistory({peer:Object(u.i)(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&m({"@type":"deleteHistory",chatId:e.id})}async function U({chat:e,threadId:t,maxId:n}){const a="channel"===Object(u.s)(e.id);a&&t===i.MAIN_THREAD_ID?await Object(r.g)(new s.Api.channels.ReadHistory({channel:Object(u.g)(e.id,e.accessHash),maxId:n})):a?await Object(r.g)(new s.Api.messages.ReadDiscussion({peer:Object(u.i)(e.id,e.accessHash),msgId:t,readMaxId:n})):await Object(r.g)(new s.Api.messages.ReadHistory({peer:Object(u.i)(e.id,e.accessHash),maxId:n})),t===i.MAIN_THREAD_ID?Object(h.u)(e):T({chat:e,threadId:t})}async function O({chat:e,messageIds:t}){const n="channel"===Object(u.s)(e.id);await Object(r.g)(n?new s.Api.channels.ReadMessageContents({channel:Object(u.g)(e.id,e.accessHash),id:t}):new s.Api.messages.ReadMessageContents({id:t})),m({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function T({chat:e,threadId:t}){const[n,i]=await Promise.all([Object(r.g)(new s.Api.messages.GetDiscussionMessage({peer:Object(u.i)(e.id,e.accessHash),msgId:t})),Object(r.g)(new s.Api.messages.GetReplies({peer:Object(u.i)(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=Object(p.c)(n.messages[0]);if(!a)return;m({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:i instanceof s.Api.messages.ChannelMessages?i.count:void 0},firstMessageId:i&&"messages"in i&&i.messages.length?i.messages[0].id:void 0});n.chats.map(e=>Object(l.d)(e)).filter(Boolean).forEach(e=>{m({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})}async function D({chatOrUser:e,type:t,query:n,topMessageId:i,minDate:a,maxDate:d,...l}){let f;switch(t){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"profilePhoto":f=new s.Api.InputMessagesFilterChatPhotos;break;case"text":default:f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:f,q:n||"",topMsgId:i,minDate:a,maxDate:d,...l}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K(p);const g=p.messages.map(o.b).filter(Boolean),h=p.users.map(c.a).filter(Boolean);let m,y=g.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(y=p.count,g.length&&(m=g[g.length-1].id)),{messages:g,users:h,totalCount:y,nextOffsetId:m}}async function B({query:e,offsetRate:t=0,limit:n,type:i="text",minDate:u,maxDate:d}){let f;switch(i){case"media":f=new s.Api.InputMessagesFilterPhotoVideo;break;case"documents":f=new s.Api.InputMessagesFilterDocument;break;case"links":f=new s.Api.InputMessagesFilterUrl;break;case"audio":f=new s.Api.InputMessagesFilterMusic;break;case"voice":f=new s.Api.InputMessagesFilterVoice;break;case"text":default:if(!(e||d&&u))return;f=new s.Api.InputMessagesFilterEmpty}const p=await Object(r.g)(new s.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new s.Api.InputPeerEmpty,limit:n,filter:f,folderId:a.a,minDate:u,maxDate:d}));if(!p||p instanceof s.Api.messages.MessagesNotModified||!p.messages)return;K({chats:p.chats,users:p.users,messages:p.messages});const g=p.chats.map(e=>Object(l.d)(e)).filter(Boolean),h=p.users.map(c.a).filter(Boolean),m=p.messages.map(o.b).filter(Boolean);let y,b=m.length;return(p instanceof s.Api.messages.MessagesSlice||p instanceof s.Api.messages.ChannelMessages)&&(b=p.count,m.length&&(y=m[m.length-1].id)),{messages:m,users:h,chats:g,totalCount:b,nextRate:"nextRate"in p&&p.nextRate?p.nextRate:y}}async function x({message:e}){const t=await Object(r.g)(new s.Api.messages.GetWebPagePreview({message:e}));return t&&Object(o.n)(t)}async function j({chat:t,messageId:n,options:i}){const{id:a,accessHash:o}=t;await Object(r.g)(new s.Api.messages.SendVote({peer:Object(u.i)(a,o),msgId:n,options:i.map(t=>e.from(t))}),!0)}async function N({chat:t,messageId:n,option:i,offset:a,limit:o,shouldResetVoters:d}){const{id:l,accessHash:f}=t,p=await Object(r.g)(new s.Api.messages.GetPollVotes({peer:Object(u.i)(l,f),id:n,...i&&{option:e.from(i)},...a&&{offset:a},...o&&{limit:o}}));if(!p)return;K({chats:[],users:p.users,messages:[]});const g=p.users.map(c.a).filter(Boolean),h=p.votes.map(e=>({userId:e.userId,date:e.date}));return{count:p.count,votes:h,users:g,nextOffset:p.nextOffset,shouldResetVoters:d}}async function V({fromChat:e,toChat:t,messages:n}){const i=n.map(({id:e})=>e),a=n.map(u.r);n.forEach((e,n)=>{const s=Object(o.f)(t,e);d.a.localMessages[String(a[n])]=s,m({"@type":"newMessage",id:s.id,chatId:t.id,message:s})}),await Object(r.g)(new s.Api.messages.ForwardMessages({fromPeer:Object(u.i)(e.id,e.accessHash),toPeer:Object(u.i)(t.id,t.accessHash),randomId:a,id:i}),!0)}async function F({chat:e,timestamp:t}){const n=await Object(r.g)(new s.Api.messages.GetHistory({peer:Object(u.i)(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof s.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function L({chat:e,hash:t=0}){const{id:n,accessHash:i}=e,a=await Object(r.g)(new s.Api.messages.GetScheduledHistory({peer:Object(u.i)(n,i),hash:t}));if(!a||a instanceof s.Api.messages.MessagesNotModified||!a.messages)return;K(a);const c=a.messages.map(o.b).filter(Boolean);return{messages:c,hash:Object(u.q)(c.map(e=>e.id))}}async function q({chat:e,ids:t}){const{id:n,accessHash:i}=e;await Object(r.g)(new s.Api.messages.SendScheduledMessages({peer:Object(u.i)(n,i),id:t}),!0)}function H({chat:e,message:t}){return Object(r.g)(new s.Api.channels.ExportMessageLink({id:t.id,channel:Object(u.g)(e.id,e.accessHash),...t.isInAlbum&&{grouped:!0},...t.threadInfo&&t.threadInfo.topMessageId!==t.id&&{thread:!0}}))}function K(e){e.users.forEach(e=>{e instanceof s.Api.User&&(d.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof s.Api.Chat||e instanceof s.Api.Channel)&&(d.a.chats[e.id]=e)}),e.messages.forEach(e=>{(e instanceof s.Api.Message&&Object(u.t)(e)||e instanceof s.Api.MessageService&&Object(u.u)(e))&&Object(p.a)(e)})}async function z({chat:e}){const t=await Object(r.g)(new s.Api.messages.Search({peer:Object(u.i)(e.id,e.accessHash),filter:new s.Api.InputMessagesFilterPinned,q:"",limit:a.t}));if(!t||t instanceof s.Api.messages.MessagesNotModified||!t.messages)return;K(t);return{messages:t.messages.map(o.b).filter(Boolean),users:t.users.map(c.a).filter(Boolean),chats:t.chats.map(e=>Object(l.d)(e)).filter(Boolean)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";var s=n(64);n.o(s,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return s.ApiMediaFormat})),n.o(s,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return s.ApiMessageEntityTypes})),n.o(s,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return s.MAIN_THREAD_ID})),n.o(s,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return s.MESSAGE_DELETED}));var i=n(65);n.o(i,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return i.ApiMediaFormat})),n.o(i,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return i.ApiMessageEntityTypes})),n.o(i,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return i.MAIN_THREAD_ID})),n.o(i,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return i.MESSAGE_DELETED}));var a=n(66);n.d(t,"ApiMessageEntityTypes",(function(){return a.a})),n.d(t,"MAIN_THREAD_ID",(function(){return a.b})),n.d(t,"MESSAGE_DELETED",(function(){return a.c}));var r=n(67);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat}));var o=n(68);n.d(t,"ApiMediaFormat",(function(){return o.a}));n(69),n(70),n(71)},function(e,t,n){"use strict";(function(e){var s=n(73),i=n(74),a=n(75);function r(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(r()=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|e}function g(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return F(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(s)return F(e).length;t=(""+t).toLowerCase(),s=!0}}function h(e,t,n){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return E(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return M(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function m(e,t,n){var s=e[t];e[t]=e[n],e[n]=s}function y(e,t,n,s,i){if(0===e.length)return-1;if("string"==typeof n?(s=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,s)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,s,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,s,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,s,i){var a,r=1,o=e.length,c=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;r=2,o/=2,c/=2,n/=2}function u(e,t){return 1===r?e[t]:e.readUInt16BE(t*r)}if(i){var d=-1;for(a=n;ao&&(n=o-c),a=n;a>=0;a--){for(var l=!0,f=0;fi&&(s=i):s=i;var a=t.length;if(a%2!=0)throw new TypeError("Invalid hex string");s>a/2&&(s=a/2);for(var r=0;r>8,i=n%256,a.push(i),a.push(s);return a}(t,e.length-n),e,n,s)}function C(e,t,n){return 0===t&&n===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,n))}function S(e,t,n){n=Math.min(e.length,n);for(var s=[],i=t;i239?4:u>223?3:u>191?2:1;if(i+l<=n)switch(l){case 1:u<128&&(d=u);break;case 2:128==(192&(a=e[i+1]))&&(c=(31&u)<<6|63&a)>127&&(d=c);break;case 3:a=e[i+1],r=e[i+2],128==(192&a)&&128==(192&r)&&(c=(15&u)<<12|(63&a)<<6|63&r)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:a=e[i+1],r=e[i+2],o=e[i+3],128==(192&a)&&128==(192&r)&&128==(192&o)&&(c=(15&u)<<18|(63&a)<<12|(63&r)<<6|63&o)>65535&&c<1114112&&(d=c)}null===d?(d=65533,l=1):d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|1023&d),s.push(d),i+=l}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var n="",s=0;for(;s0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},c.prototype.compare=function(e,t,n,s,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||n>e.length||s<0||i>this.length)throw new RangeError("out of range index");if(s>=i&&t>=n)return 0;if(s>=i)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(i>>>=0)-(s>>>=0),r=(n>>>=0)-(t>>>=0),o=Math.min(a,r),u=this.slice(s,i),d=e.slice(t,n),l=0;li)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var a=!1;;)switch(s){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return v(this,e,t,n);case"latin1":case"binary":return A(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),a=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function M(e,t,n){var s="";n=Math.min(e.length,n);for(var i=t;is)&&(n=s);for(var i="",a=t;an)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,s,i,a){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function T(e,t,n,s){t<0&&(t=65535+t+1);for(var i=0,a=Math.min(e.length-n,2);i>>8*(s?i:1-i)}function D(e,t,n,s){t<0&&(t=4294967295+t+1);for(var i=0,a=Math.min(e.length-n,4);i>>8*(s?i:3-i)&255}function B(e,t,n,s,i,a){if(n+s>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function x(e,t,n,s,a){return a||B(e,0,n,4),i.write(e,t,n,s,23,4),n+4}function j(e,t,n,s,a){return a||B(e,0,n,8),i.write(e,t,n,s,52,8),n+8}c.prototype.slice=function(e,t){var n,s=this.length;if((e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(t=void 0===t?s:~~t)<0?(t+=s)<0&&(t=0):t>s&&(t=s),t0&&(i*=256);)s+=this[e+--t]*i;return s},c.prototype.readUInt8=function(e,t){return t||U(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||U(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||U(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=this[e],i=1,a=0;++a=(i*=128)&&(s-=Math.pow(2,8*t)),s},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||U(e,t,this.length);for(var s=t,i=1,a=this[e+--s];s>0&&(i*=256);)a+=this[e+--s]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readInt8=function(e,t){return t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||U(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||U(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||U(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||U(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,s){(e=+e,t|=0,n|=0,s)||O(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,a=0;for(this[t]=255&e;++a=0&&(a*=256);)this[t+i]=e/a&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):D(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=0,r=1,o=0;for(this[t]=255&e;++a>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,s){if(e=+e,t|=0,!s){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var a=n-1,r=1,o=0;for(this[t+a]=255&e;--a>=0&&(r*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/r>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):T(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):T(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):D(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):D(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,s){if(n||(n=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(a<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(r+1===s){(t-=3)>-1&&a.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&a.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function L(e){return s.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,n,s){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}}).call(this,n(43))},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return o}));var s=n(0);function i(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:i}=e;return{...a(e.user),fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,...i&&{botDescription:i.description}}}}function a(e){if(!(e instanceof s.Api.User))return;const{id:t,firstName:n,lastName:i}=e,a=e.photo instanceof s.Api.UserProfilePhoto?String(e.photo.photoId):void 0;return{id:t,isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:r(e),...n&&{firstName:n},...i&&{lastName:i},username:e.username||"",phoneNumber:e.phone||"",status:o(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a}}}function r(e){return e.bot?"userTypeBot":e.deleted?"userTypeDeleted":"userTypeRegular"}function o(e){return!e||e instanceof s.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof s.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof s.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof s.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof s.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}},function(e,t,n){"use strict";function s(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function i(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),{})}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a}))},function(e,t,n){(function(e){var s,i=function(e){"use strict";var t=1e7,n=9007199254740992,s=l(n),a="function"==typeof BigInt;function r(e,t,n,s){return void 0===e?r[0]:void 0!==t&&(10!=+t||n)?F(e,t,n,s):z(e)}function o(e,t){this.value=e,this.sign=t,this.isSmall=!1}function c(e){this.value=e,this.sign=e<0,this.isSmall=!0}function u(e){this.value=e}function d(e){return-n0?Math.floor(e):Math.ceil(e)}function m(e,n){var s,i,a=e.length,r=n.length,o=new Array(a),c=0,u=t;for(i=0;i=u?1:0,o[i]=s-c*u;for(;i0&&o.push(c),o}function y(e,t){return e.length>=t.length?m(e,t):m(t,e)}function b(e,n){var s,i,a=e.length,r=new Array(a),o=t;for(i=0;i0;)r[i++]=n%o,n=Math.floor(n/o);return r}function _(e,t){var n,s,i=e.length,a=t.length,r=new Array(i),o=0;for(n=0;n0;)r[i++]=c%o,c=Math.floor(c/o);return r}function I(e,t){for(var n=[];t-- >0;)n.push(0);return n.concat(e)}function P(e,n,s){return new o(e=0;--n)i=(a=1e7*i+e[n])-(s=h(a/t))*t,o[n]=0|s;return[o,0|i]}function M(e,n){var s,i=z(n);if(a)return[new u(e.value/i.value),new u(e.value%i.value)];var d,m=e.value,y=i.value;if(0===y)throw new Error("Cannot divide by zero");if(e.isSmall)return i.isSmall?[new c(h(m/y)),new c(m%y)]:[r[0],e];if(i.isSmall){if(1===y)return[e,r[0]];if(-1==y)return[e.negate(),r[0]];var b=Math.abs(y);if(b=0;i--){for(s=p-1,b[i+l]!==m&&(s=Math.floor((b[i+l]*p+b[i+l-1])/m)),a=0,r=0,c=_.length,o=0;oc&&(i=1e7*(i+1)),n=Math.ceil(i/a);do{if(k(r=A(t,n),d)<=0)break;n--}while(n);u.push(n),d=_(d,r)}return u.reverse(),[f(u),f(d)]}(m,y))[0];var I=e.sign!==i.sign,P=s[1],C=e.sign;return"number"==typeof d?(I&&(d=-d),d=new c(d)):d=new o(d,I),"number"==typeof P?(C&&(P=-P),P=new c(P)):P=new o(P,C),[d,P]}function k(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}function E(e){var t=e.abs();return!t.isUnit()&&(!!(t.equals(2)||t.equals(3)||t.equals(5))||!(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))&&(!!t.lesser(49)||void 0))}function R(e,t){for(var n,s,a,r=e.prev(),o=r,c=0;o.isEven();)o=o.divide(2),c++;e:for(s=0;s=0?s=_(e,t):(s=_(t,e),n=!n),"number"==typeof(s=f(s))?(n&&(s=-s),new c(s)):new o(s,n)}(n,s,this.sign)},o.prototype.minus=o.prototype.subtract,c.prototype.subtract=function(e){var t=z(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var s=t.value;return t.isSmall?new c(n-s):w(s,Math.abs(n),n>=0)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(e){return new u(this.value-z(e).value)},u.prototype.minus=u.prototype.subtract,o.prototype.negate=function(){return new o(this.value,!this.sign)},c.prototype.negate=function(){var e=this.sign,t=new c(-this.value);return t.sign=!e,t},u.prototype.negate=function(){return new u(-this.value)},o.prototype.abs=function(){return new o(this.value,!1)},c.prototype.abs=function(){return new c(Math.abs(this.value))},u.prototype.abs=function(){return new u(this.value>=0?this.value:-this.value)},o.prototype.multiply=function(e){var n,s,i,a=z(e),c=this.value,u=a.value,d=this.sign!==a.sign;if(a.isSmall){if(0===u)return r[0];if(1===u)return this;if(-1===u)return this.negate();if((n=Math.abs(u))0?function e(t,n){var s=Math.max(t.length,n.length);if(s<=30)return v(t,n);s=Math.ceil(s/2);var i=t.slice(s),a=t.slice(0,s),r=n.slice(s),o=n.slice(0,s),c=e(a,o),u=e(i,r),d=e(y(a,i),y(o,r)),l=y(y(c,I(_(_(d,c),u),s)),I(u,2*s));return p(l),l}(c,u):v(c,u),d)},o.prototype.times=o.prototype.multiply,c.prototype._multiplyBySmall=function(e){return d(e.value*this.value)?new c(e.value*this.value):P(Math.abs(e.value),l(Math.abs(this.value)),this.sign!==e.sign)},o.prototype._multiplyBySmall=function(e){return 0===e.value?r[0]:1===e.value?this:-1===e.value?this.negate():P(Math.abs(e.value),this.value,this.sign!==e.sign)},c.prototype.multiply=function(e){return z(e)._multiplyBySmall(this)},c.prototype.times=c.prototype.multiply,u.prototype.multiply=function(e){return new u(this.value*z(e).value)},u.prototype.times=u.prototype.multiply,o.prototype.square=function(){return new o(C(this.value),!1)},c.prototype.square=function(){var e=this.value*this.value;return d(e)?new c(e):new o(C(l(Math.abs(this.value))),!1)},u.prototype.square=function(e){return new u(this.value*this.value)},o.prototype.divmod=function(e){var t=M(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=c.prototype.divmod=o.prototype.divmod,o.prototype.divide=function(e){return M(this,e)[0]},u.prototype.over=u.prototype.divide=function(e){return new u(this.value/z(e).value)},c.prototype.over=c.prototype.divide=o.prototype.over=o.prototype.divide,o.prototype.mod=function(e){return M(this,e)[1]},u.prototype.mod=u.prototype.remainder=function(e){return new u(this.value%z(e).value)},c.prototype.remainder=c.prototype.mod=o.prototype.remainder=o.prototype.mod,o.prototype.pow=function(e){var t,n,s,i=z(e),a=this.value,o=i.value;if(0===o)return r[1];if(0===a)return r[0];if(1===a)return r[1];if(-1===a)return i.isEven()?r[1]:r[-1];if(i.sign)return r[0];if(!i.isSmall)throw new Error("The exponent "+i.toString()+" is too large.");if(this.isSmall&&d(t=Math.pow(a,o)))return new c(h(t));for(n=this,s=r[1];!0&o&&(s=s.times(n),--o),0!==o;)o/=2,n=n.square();return s},c.prototype.pow=o.prototype.pow,u.prototype.pow=function(e){var t=z(e),n=this.value,s=t.value,i=BigInt(0),a=BigInt(1),o=BigInt(2);if(s===i)return r[1];if(n===i)return r[0];if(n===a)return r[1];if(n===BigInt(-1))return t.isEven()?r[1]:r[-1];if(t.isNegative())return new u(i);for(var c=this,d=r[1];(s&a)===a&&(d=d.times(c),--s),s!==i;)s/=o,c=c.square();return d},o.prototype.modPow=function(e,t){if(e=z(e),(t=z(t)).isZero())throw new Error("Cannot take modPow with modulus 0");var n=r[1],s=this.mod(t);for(e.isNegative()&&(e=e.multiply(r[-1]),s=s.modInv(t));e.isPositive();){if(s.isZero())return r[0];e.isOdd()&&(n=n.multiply(s).mod(t)),e=e.divide(2),s=s.square().mod(t)}return n},u.prototype.modPow=c.prototype.modPow=o.prototype.modPow,o.prototype.compareAbs=function(e){var t=z(e),n=this.value,s=t.value;return t.isSmall?1:k(n,s)},c.prototype.compareAbs=function(e){var t=z(e),n=Math.abs(this.value),s=t.value;return t.isSmall?n===(s=Math.abs(s))?0:n>s?1:-1:-1},u.prototype.compareAbs=function(e){var t=this.value,n=z(e).value;return(t=t>=0?t:-t)===(n=n>=0?n:-n)?0:t>n?1:-1},o.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:k(n,s)*(this.sign?-1:1)},o.prototype.compareTo=o.prototype.compare,c.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=z(e),n=this.value,s=t.value;return t.isSmall?n==s?0:n>s?1:-1:n<0!==t.sign?n<0?-1:1:n<0?1:-1},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,n=z(e).value;return t===n?0:t>n?1:-1},u.prototype.compareTo=u.prototype.compare,o.prototype.equals=function(e){return 0===this.compare(e)},u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals=o.prototype.eq=o.prototype.equals,o.prototype.notEquals=function(e){return 0!==this.compare(e)},u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals=o.prototype.neq=o.prototype.notEquals,o.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater=o.prototype.gt=o.prototype.greater,o.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser=o.prototype.lt=o.prototype.lesser,o.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals=o.prototype.geq=o.prototype.greaterOrEquals,o.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals=o.prototype.leq=o.prototype.lesserOrEquals,o.prototype.isEven=function(){return 0==(1&this.value[0])},c.prototype.isEven=function(){return 0==(1&this.value)},u.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},o.prototype.isOdd=function(){return 1==(1&this.value[0])},c.prototype.isOdd=function(){return 1==(1&this.value)},u.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},o.prototype.isPositive=function(){return!this.sign},c.prototype.isPositive=function(){return this.value>0},u.prototype.isPositive=c.prototype.isPositive,o.prototype.isNegative=function(){return this.sign},c.prototype.isNegative=function(){return this.value<0},u.prototype.isNegative=c.prototype.isNegative,o.prototype.isUnit=function(){return!1},c.prototype.isUnit=function(){return 1===Math.abs(this.value)},u.prototype.isUnit=function(){return this.abs().value===BigInt(1)},o.prototype.isZero=function(){return!1},c.prototype.isZero=function(){return 0===this.value},u.prototype.isZero=function(){return this.value===BigInt(0)},o.prototype.isDivisibleBy=function(e){var t=z(e);return!t.isZero()&&(!!t.isUnit()||(0===t.compareAbs(2)?this.isEven():this.mod(t).isZero()))},u.prototype.isDivisibleBy=c.prototype.isDivisibleBy=o.prototype.isDivisibleBy,o.prototype.isPrime=function(e){var t=E(this);if(void 0!==t)return t;var n=this.abs(),s=n.bitLength();if(s<=64)return R(n,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var a=Math.log(2)*s.toJSNumber(),r=Math.ceil(!0===e?2*Math.pow(a,2):a),o=[],c=0;c-n?new c(e-1):new o(s,!0)},u.prototype.prev=function(){return new u(this.value-BigInt(1))};for(var U=[1];2*U[U.length-1]<=t;)U.push(2*U[U.length-1]);var O=U.length,T=U[O-1];function D(e){return Math.abs(e)<=t}function B(e,t,n){t=z(t);for(var s=e.isNegative(),a=t.isNegative(),r=s?e.not():e,o=a?t.not():t,c=0,u=0,d=null,l=null,f=[];!r.isZero()||!o.isZero();)c=(d=M(r,T))[1].toJSNumber(),s&&(c=T-1-c),u=(l=M(o,T))[1].toJSNumber(),a&&(u=T-1-u),r=d[0],o=l[0],f.push(n(c,u));for(var p=0!==n(s?1:0,a?1:0)?i(-1):i(0),g=f.length-1;g>=0;g-=1)p=p.multiply(T).add(i(f[g]));return p}o.prototype.shiftLeft=function(e){var t=z(e).toJSNumber();if(!D(t))throw new Error(String(t)+" is too large for shifting.");if(t<0)return this.shiftRight(-t);var n=this;if(n.isZero())return n;for(;t>=O;)n=n.multiply(T),t-=O-1;return n.multiply(U[t])},u.prototype.shiftLeft=function(e){return e=z(e),new u(this.value<=O;){if(s.isZero()||s.isNegative()&&s.isUnit())return s;s=(t=M(s,T))[1].isNegative()?t[0].prev():t[0],n-=O-1}return(t=M(s,U[n]))[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=function(e){return e=z(e),new u(this.value>>e.value)},c.prototype.shiftRight=o.prototype.shiftRight,o.prototype.not=function(){return this.negate().prev()},u.prototype.not=c.prototype.not=o.prototype.not,o.prototype.and=function(e){return B(this,e,(function(e,t){return e&t}))},u.prototype.and=c.prototype.and=o.prototype.and,o.prototype.or=function(e){return B(this,e,(function(e,t){return e|t}))},u.prototype.or=c.prototype.or=o.prototype.or,o.prototype.xor=function(e){return B(this,e,(function(e,t){return e^t}))},u.prototype.xor=c.prototype.xor=o.prototype.xor;function x(e){var n=e.value,s="number"==typeof n?n|1<<30:"bigint"==typeof n?n|BigInt(1<<30):n[0]+n[1]*t|1073758208;return s&-s}function j(e,t){return e=z(e),t=z(t),e.greater(t)?e:t}function N(e,t){return e=z(e),t=z(t),e.lesser(t)?e:t}function V(e,t){if(e=z(e).abs(),t=z(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var n,s,i=r[1];e.isEven()&&t.isEven();)n=N(x(e),x(t)),e=e.divide(n),t=t.divide(n),i=i.multiply(n);for(;e.isEven();)e=e.divide(x(e));do{for(;t.isEven();)t=t.divide(x(t));e.greater(t)&&(s=t,t=e,e=s),t=t.subtract(e)}while(!t.isZero());return i.isUnit()?e:e.multiply(i)}o.prototype.bitLength=function(){var e=this;return e.compareTo(i(0))<0&&(e=e.negate().subtract(i(1))),0===e.compareTo(i(0))?i(0):i(function e(t,n){if(n.compareTo(t)<=0){var s=e(t,n.square(n)),a=s.p,r=s.e,o=a.multiply(n);return o.compareTo(t)<=0?{p:o,e:2*r+1}:{p:a,e:2*r}}return{p:i(1),e:0}}(e,i(2)).e).add(i(1))},u.prototype.bitLength=c.prototype.bitLength=o.prototype.bitLength;var F=function(e,t,n,s){n=n||"0123456789abcdefghijklmnopqrstuvwxyz",e=String(e),s||(e=e.toLowerCase(),n=n.toLowerCase());var i,a=e.length,r=Math.abs(t),o={};for(i=0;i=r)){if("1"===d&&1===r)continue;throw new Error(d+" is not a valid digit in base "+t+".")}}t=z(t);var c=[],u="-"===e[0];for(i=u?1:0;i"!==e[i]&&i=0;s--)i=i.add(e[s].times(a)),a=a.times(t);return n?i.negate():i}function q(e,t){if((t=i(t)).isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var n=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return n.unshift([1]),{value:[].concat.apply([],n),isNegative:!1}}var s=!1;if(e.isNegative()&&t.isPositive()&&(s=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:s};for(var a,r=[],o=e;o.isNegative()||o.compareAbs(t)>=0;){a=o.divmod(t),o=a.quotient;var c=a.remainder;c.isNegative()&&(c=t.minus(c).abs(),o=o.next()),r.push(c.toJSNumber())}return r.push(o.toJSNumber()),{value:r.reverse(),isNegative:s}}function H(e,t,n){var s=q(e,t);return(s.isNegative?"-":"")+s.value.map((function(e){return function(e,t){return e<(t=t||"0123456789abcdefghijklmnopqrstuvwxyz").length?t[e]:"<"+e+">"}(e,n)})).join("")}function K(e){if(d(+e)){var t=+e;if(t===h(t))return a?new u(BigInt(t)):new c(t);throw new Error("Invalid integer: "+e)}var n="-"===e[0];n&&(e=e.slice(1));var s=e.split(/e/i);if(s.length>2)throw new Error("Invalid integer: "+s.join("e"));if(2===s.length){var i=s[1];if("+"===i[0]&&(i=i.slice(1)),(i=+i)!==h(i)||!d(i))throw new Error("Invalid integer: "+i+" is not a valid exponent.");var r=s[0],l=r.indexOf(".");if(l>=0&&(i-=r.length-l-1,r=r.slice(0,l)+r.slice(l+1)),i<0)throw new Error("Cannot include negative exponent part for integers");e=r+=new Array(i+1).join("0")}if(!/^([0-9][0-9]*)$/.test(e))throw new Error("Invalid integer: "+e);if(a)return new u(BigInt(n?"-"+e:e));for(var f=[],g=e.length,m=g-7;g>0;)f.push(+e.slice(m,g)),(m-=7)<0&&(m=0),g-=7;return p(f),new o(f,n)}function z(e){return"number"==typeof e?function(e){if(a)return new u(BigInt(e));if(d(e)){if(e!==h(e))throw new Error(e+" is not an integer.");return new c(e)}return K(e.toString())}(e):"string"==typeof e?K(e):"bigint"==typeof e?new u(e):e}o.prototype.toArray=function(e){return q(this,e)},c.prototype.toArray=function(e){return q(this,e)},u.prototype.toArray=function(e){return q(this,e)},o.prototype.toString=function(e,t){if(void 0===e&&(e=10),10!==e)return H(this,e,t);for(var n,s=this.value,i=s.length,a=String(s[--i]);--i>=0;)n=String(s[i]),a+="0000000".slice(n.length)+n;return(this.sign?"-":"")+a},c.prototype.toString=function(e,t){return void 0===e&&(e=10),10!=e?H(this,e,t):String(this.value)},u.prototype.toString=c.prototype.toString,u.prototype.toJSON=o.prototype.toJSON=c.prototype.toJSON=function(){return this.toString()},o.prototype.valueOf=function(){return parseInt(this.toString(),10)},o.prototype.toJSNumber=o.prototype.valueOf,c.prototype.valueOf=function(){return this.value},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=u.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var G=0;G<1e3;G++)r[G]=z(G),G>0&&(r[-G]=z(-G));return r.one=r[1],r.zero=r[0],r.minusOne=r[-1],r.max=j,r.min=N,r.gcd=V,r.lcm=function(e,t){return e=z(e).abs(),t=z(t).abs(),e.divide(V(e,t)).multiply(t)},r.isInstance=function(e){return e instanceof o||e instanceof c||e instanceof u},r.randBetween=function(e,n,s){e=z(e),n=z(n);var i=s||Math.random,a=N(e,n),o=j(e,n).subtract(a).add(1);if(o.isSmall)return a.add(Math.floor(i()*o));for(var c=q(o,t).value,u=[],d=!0,l=0;l{r.resolve=e,r.reject=t})}function d(e=!1){return o({...y("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise((e,t)=>{r.resolve=e,r.reject=t})}function l(e){return o({...y("authorizationStateWaitPassword"),hint:e}),new Promise(e=>{r.resolve=e})}function f(){return o(y("authorizationStateWaitRegistration")),new Promise(e=>{r.resolve=e})}function p(e){return o({...y("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise((e,t)=>{r.reject=t})}function g(e){let t;if(e instanceof s.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=a[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),o({"@type":"updateAuthorizationError",message:t})}function h(){o(y("authorizationStateReady"))}function m(e){o({"@type":"updateCurrentUser",currentUser:e})}function y(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function b(e){r.resolve&&r.resolve(e)}function _(e){r.resolve&&r.resolve(e)}function w(e){r.resolve&&r.resolve(e)}function v(e){const{firstName:t,lastName:n}=e;r.resolve&&r.resolve([t,n])}function A(){r.reject&&r.reject(new Error("RESTART_AUTH"))}function I(){r.reject&&r.reject(new Error("RESTART_AUTH_WITH_QR"))}},function(e,t,n){"use strict";function s(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function i(e){if(!e)return;const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:i,classType:a,...r}=e;return r}n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i}))},function(e,t,n){"use strict";n.d(t,"e",(function(){return c})),n.d(t,"c",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return f}));var s=n(0),i=n(20),a=n(18);function r(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 o={w:100,h:100};function c(e,t){if(!e||!e.length)return;const n=e.find(e=>e instanceof s.Api.PhotoStrippedSize);if(!n)return;const r=e.filter(e=>e instanceof s.Api.PhotoSize),{w:c,h:u}=r&&r.length?r[r.length-1]:o,{bytes:d}=n;return{dataUri:Object(a.a)(t&&"image/jpeg"!==t?d:Object(i.strippedPhotoToJpg)(d),void 0,t),width:c,height:u}}function u(e){const{w:t,h:n,bytes:s}=e;return{dataUri:Object(a.a)(s,void 0,"image/webp"),width:t,height:n}}function d(e,t){const{w:n,h:s}=t;return{dataUri:"data:image/svg+xml;utf8,"+r(e.bytes,n,s),width:n,height:s}}function l(e){const t=e.sizes.filter(e=>e instanceof s.Api.PhotoSize||e instanceof s.Api.PhotoSizeProgressive).map(f);return{id:String(e.id),thumbnail:c(e.sizes),sizes:t}}function f(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}},function(e,t,n){(function(t){const{constructors:s}=n(21),i=t.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),a=t.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error("Invalid message type: "+e.constructor.name)}},getInputPeer:function e(t,n=!0,i=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof s.User){if(t.isSelf&&n)return new s.InputPeerSelf;if(void 0===t.accessHash&&i)throw new Error("User without accessHash or min info cannot be input");return new s.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof s.Chat||t instanceof s.ChatEmpty||t instanceof s.ChatForbidden)return new s.InputPeerChat({chatId:t.id});if(t instanceof s.Channel){if(void 0===t.accessHash&&i)throw new TypeError("Channel without accessHash or min info cannot be input");return new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof s.ChannelForbidden?new s.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof s.InputUser?new s.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof s.InputChannel?new s.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof s.UserEmpty?new s.InputPeerEmpty:t instanceof s.UserFull?e(t.user):t instanceof s.ChatFull?new s.InputPeerChat({chatId:t.id}):t instanceof s.PeerChat?new s.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof s.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof s.Chat||e instanceof s.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=1572864e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const n=t.from(i);return n[164]=e[1],n[166]=e[2],t.concat([n,e.slice(3),a])},getDC:function(e){switch(e){case 1:return{id:1,ipAddress:"pluto.web.telegram.org",port:443};case 2:return{id:2,ipAddress:"venus.web.telegram.org",port:443};case 3:return{id:3,ipAddress:"aurora.web.telegram.org",port:443};case 4:return{id:4,ipAddress:"vesta.web.telegram.org",port:443};case 5:return{id:5,ipAddress:"flora.web.telegram.org",port:443};default:throw new Error("Cannot find the DC with the ID of "+e)}}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(6),{serializeBytes:i,serializeDate:a}=n(44);e.exports={constructors:s,requests:s,serializeBytes:i,serializeDate:a}},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return u}));var s=n(0),i=n(4),a=n(19),r=n(5);function o(e){if(e instanceof s.Api.DocumentEmpty)return;const t=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeSticker);if(!t)return;const n=e.attributes.find(e=>e instanceof s.Api.DocumentAttributeImageSize),r=t.stickerset,o=t.alt,c="application/x-tgsticker"===e.mimeType,u=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoCachedSize),d=e.thumbs&&e.thumbs.find(e=>e instanceof s.Api.PhotoPathSize),l=u?Object(a.c)(u):d&&n?Object(a.d)(d,n):void 0,{w:f,h:p}=u||n||{};return{id:String(e.id),stickerSetId:r.id?String(r.id):i.s,stickerSetAccessHash:String(r.accessHash),emoji:o,isAnimated:c,width:f,height:p,thumbnail:l}}function c(e){const{archived:t,animated:n,installedDate:s,id:i,accessHash:a,title:r,thumbs:o,count:c,hash:u}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(i),accessHash:String(a),title:r,hasThumbnail:Boolean(o&&o.length),count:c,hash:u}}function u(e){const t=c(e.set),n=e instanceof s.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach(e=>{if(e instanceof s.Api.Document){const n=o(e);n&&(t.covers.push(n),r.a.documents[String(e.id)]=e)}}),t}},function(e,t){class n extends Error{constructor(){super("The read operation was cancelled.")}}class s 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 i 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 r extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=" Caused by "+e.className,super(n),this.message=n,this.code=t}}var c,u,d;d={16:"msg_id too low (most likely, client time is wrong it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted).",17:"msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",32:"msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno).",33:"msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",48:"Incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it).",64:"Invalid container."},(u="ErrorMessages")in(c=o)?Object.defineProperty(c,u,{value:d,enumerable:!0,configurable:!0,writable:!0}):c[u]=d,e.exports={ReadCancelledError:n,TypeNotFoundError:s,InvalidChecksumError:i,InvalidBufferError:a,SecurityError:r,CdnFileTamperedError:class extends r{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return u}));var s=n(0),i=n(9),a=n(14);function r(e){if(e instanceof s.Api.WallPaperNoFile)return;const{slug:t}=e,n=Object(i.a)(e.document);return n?{slug:t,document:n}:void 0}function o(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...Object(a.b)(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function c(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}function u(e){let t,n,i,a,r;return e.forEach(e=>{e instanceof s.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof s.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof s.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof s.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof s.Api.PrivacyValueAllowUsers?n=e.users:e instanceof s.Api.PrivacyValueDisallowUsers?a=e.users:e instanceof s.Api.PrivacyValueAllowChatParticipants?i=e.chats.map(e=>-e):e instanceof s.Api.PrivacyValueDisallowChatParticipants&&(r=e.chats.map(e=>-e))}),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:i||[],blockUserIds:a||[],blockChatIds:r||[]}}},function(e,t,n){const{TypeNotFoundError:s}=n(23),{coreObjects:i}=n(54),{tlobjects:a}=n(49),{readBigIntFromBuffer:r}=n(8);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return r(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error("Invalid boolean code "+e.toString("16"))}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=a[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;ne instanceof s.Api.User).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}),n.filter(e=>e instanceof s.Api.Chat||e instanceof s.Api.Channel).map(e=>Object(r.d)(e)).forEach(e=>{e&&h({"@type":"updateChat",id:e.id,chat:e})})),e instanceof s.Api.UpdateNewScheduledMessage?h({"@type":y.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):h({"@type":y.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t}),e.message instanceof s.Api.MessageService){const{action:n}=e.message;if(n instanceof s.Api.MessageActionChatEditTitle)h({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof s.Api.MessageActionChatEditPhoto){const i=Object(c.c)(n.photo),a=Object(r.e)(i),o=Math.abs(Object(f.c)(e.message));u.a.chats[o]&&(u.a.chats[o].photo=i),Object(f.b)(n.photo),a&&h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof s.Api.Photo&&{newProfilePhoto:Object(g.a)(n.photo)}})}else if(n instanceof s.Api.MessageActionChatDeletePhoto){const n=Math.abs(Object(f.c)(e.message));u.a.chats[n]&&(u.a.chats[n].photo=new s.Api.ChatPhotoEmpty),h({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof s.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&e.id===n.userId)&&h({"@type":"updateChatLeave",id:t.chatId}):n instanceof s.Api.MessageActionChatAddUser&&e._entities&&e._entities.some(e=>e instanceof s.Api.User&&!!e.self&&n.users.includes(e.id))&&h({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof s.Api.UpdateEditMessage||e instanceof s.Api.UpdateEditChannelMessage){if(e.message instanceof s.Api.MessageEmpty)return void(l.g&&console.error("Unexpected update:",e.className,e));e.message instanceof s.Api.Message&&Object(c.t)(e.message)&&Object(f.a)(e.message);const t=Object(a.b)(e.message);h({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof s.Api.UpdateDeleteMessages)h({"@type":"deleteMessages",ids:e.messages});else if(e instanceof s.Api.UpdateDeleteScheduledMessages)h({"@type":"deleteScheduledMessages",ids:e.messages,chatId:Object(r.i)(e.peer)});else if(e instanceof s.Api.UpdateDeleteChannelMessages){const t=Object(r.j)({channelId:e.channelId}),n=e.messages,i=n.filter(e=>u.a.messages[`${t}-${e}`]),a=n.filter(e=>!u.a.messages[`${t}-${e}`]),o=n.map(e=>{const n=u.a.messages[`${t}-${e}`];return n&&n instanceof s.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0}).filter(Boolean);i.length&&h({"@type":"deleteMessages",ids:i,chatId:t}),o.length&&h({"@type":"deleteProfilePhotos",ids:o,chatId:t}),a.length&&setTimeout(()=>{h({"@type":"deleteMessages",ids:a,chatId:t})},1e3)}else if((t instanceof s.Api.messages.SendMessage||t instanceof s.Api.messages.SendMedia||t instanceof s.Api.messages.SendMultiMedia||t instanceof s.Api.messages.ForwardMessages)&&(e instanceof s.Api.UpdateMessageID||e instanceof s.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const i=n&&u.a.localMessages[n.toString()];if(!i)throw new Error("Local message not found");let r;if(e instanceof s.Api.UpdateShortSentMessage){i.content.text&&e.entities&&(r={text:Object(a.j)(i.content.text.text,e.entities)}),e.media&&(r={...r,...Object(a.i)(e.media)});const t=Object(c.m)(e.id,i.chatId,e);Object(c.t)(t)&&Object(f.a)(t)}y.add(e.id);const o="date"in e&&1e3*e.dateString.fromCharCode(...e))});else if(e instanceof s.Api.UpdateChannelMessageViews)h({"@type":"updateMessage",chatId:Object(r.j)({channelId:e.channelId}),id:e.id,message:{views:e.views}});else if(e instanceof s.Api.UpdateReadHistoryInbox)h({"@type":"updateChatInbox",id:Object(r.j)(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadHistoryOutbox)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateReadChannelInbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof s.Api.UpdateReadChannelOutbox)h({"@type":"updateChat",id:Object(r.j)({channelId:e.channelId}),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof s.Api.UpdateDialogPinned&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChatPinned",id:Object(r.j)(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof s.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter(e=>e instanceof s.Api.DialogPeer).map(e=>Object(r.j)(e.peer)):[];h({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof s.Api.UpdateFolderPeers)e.folderPeers.forEach(e=>{const{folderId:t,peer:n}=e;h({"@type":"updateChatListType",id:Object(r.j)(n),folderId:t})});else if(e instanceof s.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Object(r.a)(n):void 0;h({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof s.Api.UpdateDialogFilterOrder)h({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof s.Api.UpdateChatParticipants){const t=Object(r.g)(e.participants);h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.participants.chatId}),replacedMembers:t})}else if(e instanceof s.Api.UpdateChatParticipantAdd){const t=Object(r.f)(Object(i.b)(e,["userId","inviterId","date"]));h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),addedMember:t})}else if(e instanceof s.Api.UpdateChatParticipantDelete){const{userId:t}=e;h({"@type":"updateChatMembers",id:Object(r.j)({chatId:e.chatId}),deletedMemberId:t})}else if(e instanceof s.Api.UpdatePinnedMessages||e instanceof s.Api.UpdatePinnedChannelMessages){const t=e instanceof s.Api.UpdatePinnedMessages?e.peer:{channelId:e.channelId},n=Object(r.j)(t);h({"@type":"updatePinnedIds",chatId:n,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof s.Api.UpdateNotifySettings&&e.peer instanceof s.Api.NotifyPeer){const{silent:t,muteUntil:n,showPreviews:s,sound:i}=e.notifySettings,a=t||"number"==typeof n&&Date.now()<1e3*n;h({"@type":"updateNotifyExceptions",id:Object(r.j)(e.peer.peer),isMuted:a,...""===i&&{isSilent:!0},...void 0!==s&&{shouldShowPreviews:Boolean(s)}})}else if(e instanceof s.Api.UpdateUserTyping||e instanceof s.Api.UpdateChatUserTyping){const t=e instanceof s.Api.UpdateUserTyping?e.userId:Object(r.j)({chatId:e.chatId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannelUserTyping){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChatTypingStatus",id:t,typingStatus:Object(r.h)(e)})}else if(e instanceof s.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find(e=>e instanceof s.Api.Channel||e instanceof s.Api.ChannelForbidden);if(n instanceof s.Api.Channel){const t=Object(r.d)(n);t&&(h({"@type":"updateChat",id:t.id,chat:t}),h({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:Object(r.j)({channelId:e.channelId})}))}else if(n instanceof s.Api.ChannelForbidden){const t=Object(r.j)({channelId:e.channelId});h({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),h({"@type":"updateChatLeave",id:t})}else 0===t.length&&h({"@type":"resetMessages",id:Object(r.j)({chatId:e.channelId})})}else if(e instanceof s.Api.UpdateDialogUnreadMark&&e.peer instanceof s.Api.DialogPeer)h({"@type":"updateChat",id:Object(r.j)(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof s.Api.UpdateChatDefaultBannedRights)h({"@type":"updateChat",id:Object(r.j)(e.peer),chat:{defaultBannedRights:Object(d.b)(e.defaultBannedRights)}});else if(e instanceof s.Api.UpdateUserStatus){const{userId:t,status:n}=e;h({"@type":"updateUserStatus",userId:t,status:Object(o.c)(n)})}else if(e instanceof s.Api.UpdateUserName){const t=u.a.users[e.userId],n=t&&t.mutualContact&&!t.self?Object(i.b)(e,["username"]):Object(i.b)(e,["firstName","lastName","username"]);h({"@type":"updateUser",id:e.userId,user:n})}else if(e instanceof s.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=Object(r.e)(n);u.a.users[t]&&(u.a.users[t].photo=n),h({"@type":"updateUser",id:t,user:{avatarHash:s}})}else if(e instanceof s.Api.UpdateUserPhone){const{userId:t,phone:n}=e;h({"@type":"updateUser",id:t,user:{phoneNumber:n}})}else if(e instanceof s.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;t&&t.length&&(t.filter(e=>e instanceof s.Api.User&&!e.contact).forEach(e=>{h({"@type":"deleteUser",id:e.id})}),t.filter(e=>e instanceof s.Api.User&&e.contact).map(o.a).forEach(e=>{e&&h({"@type":"updateUser",id:e.id,user:e})}))}else if(e instanceof s.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:i}}=e,a="NotifyUsers"===i?"contact":"NotifyChats"===i?"group":"NotifyBroadcasts"===i?"broadcast":void 0;if(!a)return;h({"@type":"updateNotifySettings",peerType:a,isSilent:Boolean(n||"number"==typeof s&&Date.now()<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof s.Api.UpdatePeerBlocked)h({"@type":"updatePeerBlocked",id:Object(r.j)(e.peerId),isBlocked:e.blocked});else if(e instanceof s.Api.UpdatePrivacy){const t=Object(p.c)(e.key);t&&h({"@type":"updatePrivacy",key:t,rules:Object(p.d)(e.rules)})}else if(e instanceof s.Api.UpdateContactsReset)h({"@type":"updateResetContactList"});else if(e instanceof s.Api.UpdateFavedStickers)h({"@type":"updateFavoriteStickers"});else if(l.g){const t="object"==typeof e&&"className"in e?e.className:e;console.warn("[GramJs/updater] Unexpected update:",t)}}},function(e,t,n){const s=n(48);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}}},function(e,t,n){(function(t){const{sha1:s,toSignedLittleBuffer:i,readBufferFromBigInt:a,readBigIntFromBuffer:r}=n(8),o=n(25),{sleep:c}=n(8);class u{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new o(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 u)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await s(this._key);const t=new o(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await c(20)}getKey(){return this._key}async calcNewNonceHash(e,n){e=i(e,32);const o=t.alloc(1);o.writeUInt8(n,0);const c=t.concat([e,t.concat([o,a(this.auxHash,8,!0)])]),u=(await s(c)).slice(4,20);return r(u,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=u}).call(this,n(12).Buffer)},function(e,t,n){const{RPCError:s}=n(36),{rpcErrorRe:i}=n(47);const a=n(23),r=n(36),o=n(47);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of i){const i=e.errorMessage.match(n);if(i){return new s({request:t,capture:2===i.length?parseInt(i[1],10):void 0})}}return new s(e.errorMessage,t)},...a,...r,...o}},function(e,t,n){"use strict";function s(e,t,n=!0){let s,i,a;return(...r)=>{i=!0,a=r,s||(n&&(i=!1,e(...a)),s=self.setInterval(()=>{if(!i)return self.clearInterval(s),void(s=void 0);i=!1,e(...a)},t))}}function i(e){return a(r,e)}function a(e,t){let n,s=!1;return(...i)=>{n=i,s||(s=!0,e(()=>{s=!1,t(...n)}))}}function r(e){Promise.resolve().then(e)}n.d(t,"b",(function(){return s})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return o}));const o=e=>new Promise(t=>{setTimeout(()=>t(),e)})},function(e,t,n){(function(t){const s=n(15),{constructors:i}=n(21),{readBigIntFromBuffer:a,readBufferFromBigInt:r,sha256:o,bigIntMod:c,modExp:u,generateRandomBytes:d}=n(8),l=n(35);function f(e,n){if(!t.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(n))throw new Error("Changing passwords unsupported")}function p(e){return t.concat([t.alloc(256-e.length),e])}function g(e){return r(e,256,!1)}function h(e,t){const n=t.subtract(e);return!(n.lesser(s(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function m(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=d(256),n=a(e,!1),i=u(s(_),n,b);if(h(i,b)){const e=g(i),r=a(await o(t.concat([e,P])),!1);if(r.greater(s(0)))return[n,e,r]}}})(),U=c(w.subtract(M),b);if(!h(U,b))throw new Error("bad gB");const O=R.multiply(v),T=k.add(O),D=u(U,T,b),[B,x,j,N,V]=await Promise.all([o(g(D)),o(A),o(I),o(r.salt1),o(r.salt2)]),F=await o(t.concat([m(x,j),N,V,E,P,B]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:t.from(E),M1:F})},computeDigest:async function(e,t){try{f(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return g(u(s(e.g),a(await y(e,t),!1),a(e.p,!1)))}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){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{inflate:i}=n(41),{serializeBytes:a}=n(21);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{const s=new FileReader;s.onload=e=>{const{result:s}=e.target||{};"string"==typeof s&&t(s),n(new Error("Failed to read blob"))},s.onerror=n,s.readAsDataURL(e)})}async function a(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}},function(e,t,n){(function(t){const s=n(45).default,{i2ab:i,ab2i:a}=n(77),{getWords:r}=n(78);class o{constructor(e){this.setBytes(e)}setBytes(e){e=t.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 c{constructor(e,t){t instanceof o||(t=new o(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new s(r(e))}update(e){return this.encrypt(e)}encrypt(e){const n=t.from(e);for(let e=0;e{s[e]&&r[e]&&(this._authKeys[e]=new i(t.from(s[e].data),t.from(r[e].data)))})}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey="GramJs-session-"+Date.now()),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(n=>{const s=this._authKeys[n];s._key&&(t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash)}),t}async _loadFromSessionString(){const[,e,n]=this._sessionString.split(":"),s=Number(e),{ipAddress:r,port:o}=a.getDC(s);this.setDC(s,r,o);const c=new i;await c.setKey(t.from(n,"hex"),!0),this.setAuthKey(c,s)}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")}}}).call(this,n(12).Buffer)},function(e,t,n){e.exports=function e(t,n,s){function i(r,o){if(!n[r]){if(!t[r]){if(a)return a(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[r]={exports:{}};t[r][0].call(u.exports,(function(e){return i(t[r][1][e]||e)}),u,u.exports,e,t,n,s)}return n[r].exports}for(var a=!1,r=0;r=252?6:o>=248?5:o>=240?4:o>=224?3:o>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&a||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r>>6,t[r++]=128|63&n):n<65536?(t[r++]=224|n>>>12,t[r++]=128|n>>>6&63,t[r++]=128|63&n):(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63,t[r++]=128|n>>>6&63,t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n4)u[s++]=65533,n+=a-1;else{for(i&=2===a?31:3===a?15:7;a>1&&n1?u[s++]=65533:i<65536?u[s++]=i:(i-=65536,u[s++]=55296|i>>10&1023,u[s++]=56320|1023&i)}return c(u,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,s){for(var i=65535&e|0,a=e>>>16&65535|0,r=0;0!==n;){n-=r=n>2e3?2e3:n;do{a=a+(i=i+t[s++]|0)|0}while(--r);i%=65521,a%=65521}return i|a<<16|0}},{}],4:[function(e,t,n){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){"use strict";var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var a=s,r=i+n;e^=-1;for(var o=i;o>>8^a[255&(e^t[o])];return-1^e}},{}],6:[function(e,t,n){"use strict";t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){"use strict";t.exports=function(e,t){var n,s,i,a,r,o,c,u,d,l,f,p,g,h,m,y,b,_,w,v,A,I,P,C,S;n=e.state,s=e.next_in,C=e.input,i=s+(e.avail_in-5),a=e.next_out,S=e.output,r=a-(t-e.avail_out),o=a+(e.avail_out-257),c=n.dmax,u=n.wsize,d=n.whave,l=n.wnext,f=n.window,p=n.hold,g=n.bits,h=n.lencode,m=n.distcode,y=(1<>>=w=_>>>24,g-=w,0==(w=_>>>16&255))S[a++]=65535&_;else{if(!(16&w)){if(0==(64&w)){_=h[(65535&_)+(p&(1<>>=w,g-=w),g<15&&(p+=C[s++]<>>=w=_>>>24,g-=w,!(16&(w=_>>>16&255))){if(0==(64&w)){_=m[(65535&_)+(p&(1<c){e.msg="invalid distance too far back",n.mode=30;break e}if(p>>>=w,g-=w,A>(w=a-r)){if((w=A-w)>d&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(I=0,P=f,0===l){if(I+=u-w,w2;)S[a++]=P[I++],S[a++]=P[I++],S[a++]=P[I++],v-=3;v&&(S[a++]=P[I++],v>1&&(S[a++]=P[I++]))}else{I=a-A;do{S[a++]=S[I++],S[a++]=S[I++],S[a++]=S[I++],v-=3}while(v>2);v&&(S[a++]=S[I++],v>1&&(S[a++]=S[I++]))}break}}break}}while(s>3,p&=(1<<(g-=v<<3))-1,e.next_in=s,e.next_out=a,e.avail_in=s>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(852),t.distcode=t.distdyn=new s.Buf32(592),t.sane=1,t.back=-1,0):-2}function l(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,d(e)):-2}function f(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?-2:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,l(e))):-2}function p(e,t){var n,s;return e?(s=new u,e.state=s,s.window=null,0!==(n=f(e,t))&&(e.state=null),n):-2}var g,h,m=!0;function y(e){if(m){var t;for(g=new s.Buf32(512),h=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(o(1,e.lens,0,288,g,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;o(2,e.lens,0,32,h,0,e.work,{bits:5}),m=!1}e.lencode=g,e.lenbits=9,e.distcode=h,e.distbits=5}function b(e,t,n,i){var a,r=e.state;return null===r.window&&(r.wsize=1<=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):((a=r.wsize-r.wnext)>i&&(a=i),s.arraySet(r.window,t,n-i,a,r.wnext),(i-=a)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=a,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,n.check=a(n.check,B,2,0),h=0,m=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&h)){e.msg="unknown compression method",n.mode=30;break}if(m-=4,R=8+(15&(h>>>=4)),0===n.wbits)n.wbits=R;else if(R>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<>8&1),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=3;case 3:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>8&255,B[2]=h>>>16&255,B[3]=h>>>24&255,n.check=a(n.check,B,4,0)),h=0,m=0,n.mode=4;case 4:for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>8),512&n.flags&&(B[0]=255&h,B[1]=h>>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0,n.mode=5;case 5:if(1024&n.flags){for(;m<16;){if(0===p)break e;p--,h+=u[l++]<>>8&255,n.check=a(n.check,B,2,0)),h=0,m=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&((v=n.length)>p&&(v=p),v&&(n.head&&(R=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,u,l,v,R)),512&n.flags&&(n.check=a(n.check,u,v,l)),p-=v,l+=v,n.length-=v),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===p)break e;v=0;do{R=u[l+v++],n.head&&R&&n.length<65536&&(n.head.name+=String.fromCharCode(R))}while(R&&v>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;m<32;){if(0===p)break e;p--,h+=u[l++]<>>=7&m,m-=7&m,n.mode=27;break}for(;m<3;){if(0===p)break e;p--,h+=u[l++]<>>=1)){case 0:n.mode=14;break;case 1:if(y(n),n.mode=20,6===t){h>>>=2,m-=2;break e}break;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}h>>>=2,m-=2;break;case 14:for(h>>>=7&m,m-=7&m;m<32;){if(0===p)break e;p--,h+=u[l++]<>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&h,h=0,m=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(v=n.length){if(v>p&&(v=p),v>g&&(v=g),0===v)break e;s.arraySet(d,u,l,v,f),p-=v,l+=v,g-=v,f+=v,n.length-=v;break}n.mode=12;break;case 17:for(;m<14;){if(0===p)break e;p--,h+=u[l++]<>>=5,m-=5,n.ndist=1+(31&h),h>>>=5,m-=5,n.ncode=4+(15&h),h>>>=4,m-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have>>=3,m-=3}for(;n.have<19;)n.lens[x[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,O={bits:n.lenbits},U=o(0,n.lens,0,19,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=P,m-=P,n.lens[n.have++]=S;else{if(16===S){for(T=P+2;m>>=P,m-=P,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}R=n.lens[n.have-1],v=3+(3&h),h>>>=2,m-=2}else if(17===S){for(T=P+3;m>>=P)),h>>>=3,m-=3}else{for(T=P+7;m>>=P)),h>>>=7,m-=7}if(n.have+v>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;v--;)n.lens[n.have++]=R}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,O={bits:n.lenbits},U=o(1,n.lens,0,n.nlen,n.lencode,0,n.work,O),n.lenbits=O.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,O={bits:n.distbits},U=o(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,O),n.distbits=O.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(p>=6&&g>=258){e.next_out=f,e.avail_out=g,e.next_in=l,e.avail_in=p,n.hold=h,n.bits=m,r(e,w),f=e.next_out,d=e.output,g=e.avail_out,l=e.next_in,u=e.input,p=e.avail_in,h=n.hold,m=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;C=(D=n.lencode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,n.length=S,0===C){n.mode=26;break}if(32&C){n.back=-1,n.mode=12;break}if(64&C){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&C,n.mode=22;case 22:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;C=(D=n.distcode[h&(1<>>16&255,S=65535&D,!((P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>M)])>>>16&255,S=65535&D,!(M+(P=D>>>24)<=m);){if(0===p)break e;p--,h+=u[l++]<>>=M,m-=M,n.back+=M}if(h>>>=P,m-=P,n.back+=P,64&C){e.msg="invalid distance code",n.mode=30;break}n.offset=S,n.extra=15&C,n.mode=24;case 24:if(n.extra){for(T=n.extra;m>>=n.extra,m-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===g)break e;if(v=w-g,n.offset>v){if((v=n.offset-v)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}v>n.wnext?(v-=n.wnext,A=n.wsize-v):A=n.wnext-v,v>n.length&&(v=n.length),I=n.window}else I=d,A=f-n.offset,v=n.length;v>g&&(v=g),g-=v,n.length-=v;do{d[f++]=I[A++]}while(--v);0===n.length&&(n.mode=21);break;case 26:if(0===g)break e;d[f++]=n.length,g--,n.mode=21;break;case 27:if(n.wrap){for(;m<32;){if(0===p)break e;p--,h|=u[l++]<=1&&0===B[S];S--);if(M>S&&(M=S),0===S)return u[d++]=20971520,u[d++]=20971520,f.bits=1,0;for(C=1;C0&&(0===e||1!==S))return-1;for(x[1]=0,I=1;I<15;I++)x[I+1]=x[I]+B[I];for(P=0;P852||2===e&&U>592)return 1;for(;;){_=I-E,l[P]b?(w=j[N+l[P]],v=T[D+l[P]]):(w=96,v=0),p=1<>E)+(g-=p)]=_<<24|w<<16|v|0}while(0!==g);for(p=1<>=1;if(0!==p?(O&=p-1,O+=p):O=0,P++,0==--B[I]){if(I===S)break;I=t[n+l[P]]}if(I>M&&(O&m)!==h){for(0===E&&(E=M),y+=C,R=1<<(k=I-E);k+E852||2===e&&U>592)return 1;u[h=O&m]=M<<24|k<<16|y-d|0}}return 0!==O&&(u[y+O]=I-E<<24|64<<16|0),f.bits=M,0}},{"../utils/common":1}],10:[function(e,t,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){"use strict";var s=e("./zlib/inflate"),i=e("./utils/common"),a=e("./utils/strings"),r=e("./zlib/constants"),o=e("./zlib/messages"),c=e("./zlib/zstream"),u=e("./zlib/gzheader"),d=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(o[n]);if(this.header=new u,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=a.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(o[n])}function f(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||o[n.err];return n.result}l.prototype.push=function(e,t){var n,o,c,u,l,f=this.strm,p=this.options.chunkSize,g=this.options.dictionary,h=!1;if(this.ended)return!1;o=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?f.input=a.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?f.input=new Uint8Array(e):f.input=e,f.next_in=0,f.avail_in=f.input.length;do{if(0===f.avail_out&&(f.output=new i.Buf8(p),f.next_out=0,f.avail_out=p),(n=s.inflate(f,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===h&&(n=r.Z_OK,h=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),this.ended=!0,!1;f.next_out&&(0!==f.avail_out&&n!==r.Z_STREAM_END&&(0!==f.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=a.utf8border(f.output,f.next_out),u=f.next_out-c,l=a.buf2string(f.output,c),f.next_out=u,f.avail_out=p-u,u&&i.arraySet(f.output,f.output,c,u,0),this.onData(l)):this.onData(i.shrinkBuf(f.output,f.next_out)))),0===f.avail_in&&0===f.avail_out&&(h=!0)}while((f.avail_in>0||0===f.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),f.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=l,n.inflate=f,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},n.ungzip=f},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")},function(e,t,n){const s=n(46),i=n(58),a=n(25),r=n(60),o=n(57),c=n(61);e.exports={BinaryWriter:i,BinaryReader:a,MessagePacker:o,AsyncQueue:c,Logger:s,PromisedWebSockets:r}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){(function(t){const n=e=>e.replace(/(?:^|_)([a-z])/g,(e,t)=>t.toUpperCase()).replace(/_/g,""),s=e=>e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_","")),i=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),a=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let r;function o(e){r||(r=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}()),t.isBuffer(e)||(e=t.from(e));let n=-1;for(let t=0;t>>8}return(-1^n)>>>0}const c=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),c(e,t,n)),n},u=(e,i)=>{const a=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!a)throw new Error("Cannot parse TLObject "+e);const r=c(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),u={name:a[1],constructorId:parseInt(a[2],16),argsConfig:{},subclassOfId:o(a[3]),result:a[3],isFunction:i,namespace:void 0};if(!u.constructorId){const e="";let n;n=Object.values(u.argsConfig).length?" "+Object.keys(u.argsConfig).map(e=>e.toString()).join(" "):"";const s=`${u.name}${e}${n} = ${u.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===u.name&&u.name,u.constructorId=o(t.from(s,"utf8"))}for(const[e,t,n]of r)void 0===e&&(u.argsConfig[s(t)]=d(t,n));return u.name.includes(".")&&([u.namespace,u.name]=u.name.split(/\.(.+)/)),u.name=n(u.name),u};function d(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:c,parseTl:function*(e,t,n=[],s=i){(n||[]).reduce((e,t)=>({...e,[t.name]:t}),{});const r=[],o={},c={},d=e;let l=!1;for(let e of d.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;l="functions"===e}else try{const t=u(e,l);if(s.has(t.constructorId))continue;r.push(t),t.isFunction||(c[t.result]||(c[t.result]=[]),o[t.name]=t,c[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of r)if(a.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of r)yield e},buildArgConfig:d,fromLine:u,CORE_TYPES:i,serializeDate:function(e){if(!e)return t.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const n=t.alloc(4);return n.writeInt32LE(e,0),n}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof t)){if("string"!=typeof e)throw Error("Bytes or str expected, not "+e.constructor.name);e=t.from(e)}const n=[];let s;return e.length<254?(s=(e.length+1)%4,0!==s&&(s=4-s),n.push(t.from([e.length])),n.push(e)):(s=e.length%4,0!==s&&(s=4-s),n.push(t.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),n.push(e)),n.push(t.alloc(s).fill(0)),t.concat(n)},snakeToCamelCase:n,variableSnakeToCamelCase:s}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"CTR",(function(){return y})),n.d(t,"IGE",(function(){return m}));var s=new Uint8Array(256),i=new Uint8Array(256),a=new Uint32Array(256),r=new Uint32Array(256),o=new Uint32Array(256),c=new Uint32Array(256),u=new Uint32Array(256),d=new Uint32Array(256),l=new Uint32Array(256),f=new Uint32Array(256);function p(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(var t=e.length%4;t<=4;t++)e+="\0x00";var n=new Uint32Array(e.length/4);for(t=0;t>7),m[h[_]^_]=_;for(;!s[y];y^=e||1)n=(n=b^b<<1^b<<2^b<<3^b<<4)>>8^255&n^99,s[y]=n,i[n]=y,g=16843009*h[t=h[e=h[y]]]^65537*t^257*e^16843008*y,p=257*h[n]^16843008*n,a[y]=p=p<<24^p>>>8,r[y]=p=p<<24^p>>>8,o[y]=p=p<<24^p>>>8,c[y]=p=p<<24^p>>>8,u[n]=g=g<<24^g>>>8,d[n]=g=g<<24^g>>>8,l[n]=g=g<<24^g>>>8,f[n]=g=g<<24^g>>>8,b=m[b]||1}();var h=function(){function e(e){var t=p(e);if(4!==t.length&&6!==t.length&&8!==t.length)throw new Error("Invalid key size");this.encKey=new Uint32Array(4*t.length+28),this.decKey=new Uint32Array(4*t.length+28),this.encKey.set(t);for(var n,i=1,a=t.length;a<4*t.length+28;a++)n=this.encKey[a-1],(a%t.length==0||8===t.length&&a%t.length==4)&&(n=s[n>>>24]<<24^s[n>>16&255]<<16^s[n>>8&255]<<8^s[255&n],a%t.length==0&&(n=n<<8^n>>>24^i<<24,i=i<<1^283*(i>>7))),this.encKey[a]=this.encKey[a-t.length]^n;for(var r=0;a;r++,a--)n=this.encKey[3&r?a:a-4],this.decKey[r]=a<=4||r<4?n:u[s[n>>>24]]^d[s[n>>16&255]]^l[s[n>>8&255]]^f[s[255&n]]}return e.prototype.encrypt=function(e){for(var t,n,i,u=p(e),d=new Uint32Array(4),l=u[0]^this.encKey[0],f=u[1]^this.encKey[1],g=u[2]^this.encKey[2],h=u[3]^this.encKey[3],m=this.encKey.length/4-2,y=4,b=0;b>>24]^r[f>>16&255]^o[g>>8&255]^c[255&h]^this.encKey[y],n=a[f>>>24]^r[g>>16&255]^o[h>>8&255]^c[255&l]^this.encKey[y+1],i=a[g>>>24]^r[h>>16&255]^o[l>>8&255]^c[255&f]^this.encKey[y+2],h=a[h>>>24]^r[l>>16&255]^o[f>>8&255]^c[255&g]^this.encKey[y+3],l=t,f=n,g=i,y+=4;for(b=0;b<4;b++)d[b]=s[l>>>24]<<24^s[f>>16&255]<<16^s[g>>8&255]<<8^s[255&h]^this.encKey[y++],t=l,l=f,f=g,g=h,h=t;return d},e.prototype.decrypt=function(e){for(var t,n,s,a=p(e),r=new Uint32Array(4),o=a[0]^this.decKey[0],c=a[3]^this.decKey[1],g=a[2]^this.decKey[2],h=a[1]^this.decKey[3],m=this.decKey.length/4-2,y=4,b=0;b>>24]^d[c>>16&255]^l[g>>8&255]^f[255&h]^this.decKey[y],n=u[c>>>24]^d[g>>16&255]^l[h>>8&255]^f[255&o]^this.decKey[y+1],s=u[g>>>24]^d[h>>16&255]^l[o>>8&255]^f[255&c]^this.decKey[y+2],h=u[h>>>24]^d[o>>16&255]^l[c>>8&255]^f[255&g]^this.decKey[y+3],o=t,c=n,g=s,y+=4;for(b=0;b<4;b++)r[3&-b]=i[o>>>24]<<24^i[c>>16&255]<<16^i[g>>8&255]<<8^i[255&h]^this.decKey[y++],t=o,o=c,c=g,g=h,h=t;return r},e}(),m=function(){function e(e,t,n){void 0===n&&(n=16),this.key=p(e),this.iv=p(t),this.cipher=new h(e),this.blockSize=n/4}return e.prototype.encrypt=function(e,t){for(var n=p(e),s=t||new Uint32Array(n.length),i=this.iv.subarray(this.blockSize,this.iv.length),a=this.iv.subarray(0,this.blockSize),r=new Uint32Array(this.blockSize),o=0;o=this.blockSize&&this.incrementCounter(),i&&(a-=i,i=0)}return this.offset=(this.offset+n.length%4)%4,s},e.prototype.decrypt=function(e,t){return this.encrypt(e,t)},e.prototype.incrementCounter=function(){for(var e=this.counter.length-1;e>=0&&!(++this.counter[e]<4294967295);e--);},e}();t.default=h},function(e,t,n){(function(t){let n;class s{constructor(e){n||(n=e||"debug"),this.isBrowser=void 0===t||"renderer"===t.type||!0===t.browser||t.__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){n=e}canSend(e){return s.levels.indexOf(n)>=s.levels.indexOf(e)}warn(e){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){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,t,s){n&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(t,e),s):console.log(s+this.format(t,e)+this.colors.end))}}var i,a,r;r=["error","warn","info","debug"],(a="levels")in(i=s)?Object.defineProperty(i,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):i[a]=r,e.exports=s}).call(this,n(83))},function(e,t,n){const{RPCError:s,InvalidDCError:i,FloodError:a,BadRequestError:r}=n(36);class o extends i{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 i{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 u extends a{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 a{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 l extends a{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 f extends i{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 p extends i{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 g extends r{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 h=[[/FILE_MIGRATE_(\d+)/,f],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,l],[/FLOOD_WAIT_(\d+)/,d],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,u],[/USER_MIGRATE_(\d+)/,o],[/NETWORK_MIGRATE_(\d+)/,p],[/EMAIL_UNCONFIRMED_(\d+)/,g]];e.exports={rpcErrorRe:h,FileMigrateError:f,FloodTestPhoneWaitError:l,FloodWaitError:d,PhoneMigrateError:c,SlowModeWaitError:u,UserMigrateError:o,NetworkMigrateError:p,EmailUnconfirmedError:g}},function(e,t){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")}}},function(e,t,n){const s=n(6),i={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)i[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))i[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:128,tlobjects:i}},function(e,t,n){const s=n(51),i=n(52),a=n(8),r=n(28),o=n(56),c=n(55),u=n(38),d=n(32),l=n(86),{MsgsAck:f,upload:p,MsgsStateInfo:g,Pong:h}=n(21).constructors,m=n(57),y=n(25),{UpdateConnectionState:b}=n(59),{BadMessageError:_}=n(23),{BadServerSalt:w,BadMsgNotification:v,MsgDetailedInfo:A,MsgNewDetailedInfo:I,NewSessionCreated:P,FutureSalts:C,MsgsStateReq:S,MsgResendReq:M,MsgsAllInfo:k}=n(21).constructors,{SecurityError:E}=n(23),{InvalidBufferError:R}=n(23),{LogOut:U}=n(21).requests.auth,{RPCMessageToError:O}=n(29),{TypeNotFoundError:T}=n(23);class D{constructor(e,t){const n={...D.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._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new r,this._state=new i(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[u.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[d.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[w.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[I.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[f.CONSTRUCTOR_ID]:this._handleAck.bind(this),[C.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[S.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this._connection=e;for(let e=0;e1024)throw new u("Server replied with the wrong message padding");const y=f.tgReadObject();return new c(p,g,y)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=s(Math.floor(e)).shiftLeft(s(32)).or(s(t).shiftLeft(s(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(s(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,i=Math.floor((new Date).getTime()/1e3),a=e.shiftRight(s(32));return this.timeOffset=a-i,this.timeOffset!==n&&(this._lastMsgId=s(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}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const{IGE:s}=n(45),i=n(8);e.exports=class{constructor(e,t){this.ige=new s(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const n=e.length%16;return n&&(e=t.concat([e,i.generateRandomBytes(16-n)])),i.convertToLittle(this.ige.encrypt(e))}}}).call(this,n(12).Buffer)},function(e,t,n){const s=n(37),i=n(55),a=n(38),r=n(32),o={[i.CONSTRUCTOR_ID]:i,[r.CONSTRUCTOR_ID]:r,[a.CONSTRUCTOR_ID]:a};e.exports={TLMessage:s,RPCResult:i,MessageContainer:a,GZIPPacked:r,coreObjects:o}},function(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{RpcError:i}=n(21).constructors,a=n(32);class r{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===i.CONSTRUCTOR_ID?new r(t,void 0,i.fromReader(e)):n===a.CONSTRUCTOR_ID?new r(t,(await a.fromReader(e)).data):(e.seek(-4),new r(t,e.read(),void 0))}}s(r,"CONSTRUCTOR_ID",4082920705),s(r,"classType","constructor"),e.exports=r},function(e,t,n){(function(t){const s=n(15),i=n(53),a=n(28),r=n(84),o=n(85),c=n(8),{constructors:u,requests:d}=n(21),l=n(25),{SecurityError:f}=n(23);e.exports=async function(e,n){let p=c.generateRandomBytes(16);const g=c.readBigIntFromBuffer(p,!1,!0),h=await e.send(new d.ReqPqMulti({nonce:g}));if(n.debug("Starting authKey generation step 1"),!(h instanceof u.ResPQ))throw new Error("Step 1 answer was "+h);if(h.nonce.neq(g))throw new f("Step 1 invalid nonce from server");const m=c.readBigIntFromBuffer(h.pq,!1,!0);n.debug("Finished authKey generation step 1"),n.debug("Starting authKey generation step 2");let{p:y,q:b}=r.factorize(m);y=c.getByteArray(y),b=c.getByteArray(b),p=c.generateRandomBytes(32);const _=c.readBigIntFromBuffer(p,!0,!0),w=new u.PQInnerData({pq:c.getByteArray(m),p:y,q:b,nonce:h.nonce,serverNonce:h.serverNonce,newNonce:_});let v,A;for(const e of h.serverPublicKeyFingerprints)if(v=await o.encrypt(e.toString(),w.getBytes()),void 0!==v){A=e;break}if(void 0===v)throw new f("Step 2 could not find a valid key for fingerprints");const I=await e.send(new d.ReqDHParams({nonce:h.nonce,serverNonce:h.serverNonce,p:y,q:b,publicKeyFingerprint:A,encryptedData:v}));if(!(I instanceof u.ServerDHParamsOk||I instanceof u.ServerDHParamsFail))throw new Error("Step 2.1 answer was "+I);if(I.nonce.neq(h.nonce))throw new f("Step 2 invalid nonce from server");if(I.serverNonce.neq(h.serverNonce))throw new f("Step 2 invalid server nonce from server");if(I instanceof u.ServerDHParamsFail){const e=await c.sha1(c.toSignedLittleBuffer(_,32).slice(4,20)),t=c.readBigIntFromBuffer(e,!0,!0);if(I.newNonceHash.neq(t))throw new f("Step 2 invalid DH fail nonce from server")}if(!(I instanceof u.ServerDHParamsOk))throw new Error("Step 2.2 answer was "+I);n.debug("Finished authKey generation step 2"),n.debug("Starting authKey generation step 3");const{key:P,iv:C}=await c.generateKeyDataFromNonce(h.serverNonce,_);if(I.encryptedAnswer.length%16!=0)throw new f("Step 3 AES block size mismatch");const S=new i(P,C),M=S.decryptIge(I.encryptedAnswer),k=new l(M);k.read(20);const E=k.tgReadObject();if(!(E instanceof u.ServerDHInnerData))throw new Error("Step 3 answer was "+E);if(E.nonce.neq(h.nonce))throw new f("Step 3 Invalid nonce in encrypted answer");if(E.serverNonce.neq(h.serverNonce))throw new f("Step 3 Invalid server nonce in encrypted answer");const R=c.readBigIntFromBuffer(E.dhPrime,!1,!1),U=c.readBigIntFromBuffer(E.gA,!1,!1),O=E.serverTime-Math.floor((new Date).getTime()/1e3),T=c.readBigIntFromBuffer(c.generateRandomBytes(256),!1,!1),D=c.modExp(s(E.g),T,R),B=c.modExp(U,T,R),x=new u.ClientDHInnerData({nonce:h.nonce,serverNonce:h.serverNonce,retryId:0,gB:c.getByteArray(D,!1)}).getBytes(),j=t.concat([await c.sha1(x),x]),N=S.encryptIge(j),V=await e.send(new d.SetClientDHParams({nonce:h.nonce,serverNonce:h.serverNonce,encryptedData:N})),F=[u.DhGenOk,u.DhGenRetry,u.DhGenFail];if(!(V instanceof F[0]||V instanceof F[1]||V instanceof F[2]))throw new Error("Step 3.1 answer was "+V);const{name:L}=V.constructor;if(V.nonce.neq(h.nonce))throw new f(`Step 3 invalid ${L} nonce from server`);if(V.serverNonce.neq(h.serverNonce))throw new f(`Step 3 invalid ${L} server nonce from server`);const q=new a;await q.setKey(c.getByteArray(B));const H=1+F.indexOf(V.constructor),K=await q.calcNewNonceHash(_,H);if(V["newNonceHash"+H].neq(K))throw new f("Step 3 invalid new nonce hash");if(!(V instanceof u.DhGenOk))throw new Error("Step 3.2 answer was "+V);return n.debug("Finished authKey generation step 3"),{authKey:q,timeOffset:O}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){const s=n(38),i=n(37),a=n(58);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){this._queue.push(e),this.setReady(!0),e&&(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,n=new a(t.alloc(0));const r=[];let o=0;for(;this._queue.length&&r.length<=s.MAXIMUM_LENGTH;){const e=this._queue.shift();if(o+=e.data.length+i.SIZE_OVERHEAD,o<=s.MAXIMUM_SIZE){let t;e.after&&(t=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(n,e.data,"request"===e.request.classType,t),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),r.push(e)}else{if(r.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"),o=0}}if(r.length){if(r.length>1){const i=t.alloc(8);i.writeUInt32LE(s.CONSTRUCTOR_ID,0),i.writeInt32LE(r.length,4),e=t.concat([i,n.getValue()]),n=new a(t.alloc(0));const o=await this._state.writeDataAsMessage(n,e,!1);for(const e of r)e.containerId=o}return e=n.getValue(),{batch:r,data:e}}}rejectAll(){this._pendingStates.forEach(e=>{e.reject(new Error("Disconnect"))})}}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){e.exports=class{constructor(e){this._stream=e}write(e){this._stream=t.concat([this._stream,e])}getValue(){return this._stream}}}).call(this,n(12).Buffer)},function(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 i=n(51),a=n(56),r=n(50);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(87);e.exports={Connection:c,ConnectionTCPFull:u,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:i,doAuthentication:a,MTProtoSender:r,UpdateConnectionState:o}},function(e,t,n){(function(t){const{Mutex:s}=n(88),i=new s,a=n(90).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(){this.client=void 0,this.closed=!0}async readExactly(e){let n=t.alloc(0);for(;;){const s=await this.read(e);if(n=t.concat([n,s]),!(e-=s.length))return n}}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=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),e}getWebSocketLink(e,t){return 443===t?`wss://${e}:${t}/apiws`:`ws://${e}:${t}/apiws`}connect(e,n){return this.stream=t.alloc(0),this.canRead=new Promise(e=>{this.resolveRead=e}),this.closed=!1,this.website=this.getWebSocketLink(n,e),this.client=new a(this.website,"binary"),new Promise((e,t)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{t(e)},this.client.onclose=()=>{this.resolveRead(!1),this.closed=!0},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=>{const n=await i.acquire();try{const s=e.data instanceof ArrayBuffer?t.from(e.data):t.from(await new Response(e.data).arrayBuffer());this.stream=t.concat([this.stream,s]),this.resolveRead(!0)}finally{n()}}}}}).call(this,n(12).Buffer)},function(e,t){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}}},function(e,t,n){(function(t){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 i=n(15),{readBufferFromBigInt:a}=n(8),{Connection:r,PacketCodec:o}=n(39);class c extends o{constructor(e){super(e),this.tag=c.tag,this.obfuscateTag=c.obfuscateTag}encodePacket(e){let n=e.length>>2;if(n<127){const e=t.alloc(1);e.writeUInt8(n,0),n=e}else n=t.concat([t.from("7f","hex"),a(i(n),3)]);return t.concat([n,e])}async readPacket(e){let n=(await e.read(1))[0];return n>=127&&(n=t.concat([await e.read(3),t.alloc(1)]).readInt32LE(0)),e.read(n<<2)}}s(c,"tag",t.from("ef","hex")),s(c,"obfuscateTag",t.from("efefefef","hex"));e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),s(this,"PacketCodecClass",c)}},AbridgedPacketCodec:c}}).call(this,n(12).Buffer)},function(e,t,n){(function(t){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{generateRandomBytes:i}=n(8),{ObfuscatedConnection:a}=n(39),{AbridgedPacketCodec:r}=n(62),o=n(94);class c{constructor(e){s(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 n=[t.from("50567247","hex"),t.from("474554","hex"),t.from("504f5354","hex"),t.from("eeeeeeee","hex")];let s;for(;;)if(s=i(64),239!==s[0]&&!s.slice(4,8).equals(t.alloc(4))){let e=!0;for(const t of n)if(t.equals(s.slice(0,4))){e=!1;break}if(e)break}s=s.toJSON().data;const a=t.from(s.slice(8,56)).reverse(),r=t.from(s.slice(8,40)),c=t.from(s.slice(40,56)),u=t.from(a.slice(0,32)),d=t.from(a.slice(32,48)),l=new o(r,c),f=new o(u,d);return s=t.concat([t.from(s.slice(0,56)),e.obfuscateTag,t.from(s.slice(60))]),s=t.concat([t.from(s.slice(0,56)),t.from(l.encrypt(s).slice(56,64)),t.from(s.slice(64))]),{random:s,encryptor:l,decryptor:f}}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 a{constructor(...e){super(...e),s(this,"ObfuscatedIO",c),s(this,"PacketCodecClass",r)}}}}).call(this,n(12).Buffer)},function(e,t){},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return i})),n.d(t,"c",(function(){return a})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(s||(s={}));const i=-1,a="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let s;n.d(t,"a",(function(){return s})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(s||(s={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return r}));var s=n(1),i=n(0),a=n(2);async function r({chatId:t,accessHash:n,messageId:r,data:o}){const c=await Object(s.g)(new i.Api.messages.GetBotCallbackAnswer({peer:Object(a.i)(t,n),msgId:r,data:e.from(o)}));if(c)return c}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";t.byteLength=function(e){var t=u(e),n=t[0],s=t[1];return 3*(n+s)/4-s},t.toByteArray=function(e){var t,n,s=u(e),r=s[0],o=s[1],c=new a(function(e,t,n){return 3*(t+n)/4-n}(0,r,o)),d=0,l=o>0?r-4:r;for(n=0;n>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===o&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[d++]=255&t);1===o&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,a=[],r=0,o=n-i;ro?o:r+16383));1===i?(t=e[n-1],a.push(s[t>>2]+s[t<<4&63]+"==")):2===i&&(t=(e[n-2]<<8)+e[n-1],a.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"="));return a.join("")};for(var s=[],i=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=r.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e,t,n){for(var i,a,r=[],o=t;o>18&63]+s[a>>12&63]+s[a>>6&63]+s[63&a]);return r.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){t.read=function(e,t,n,s,i){var a,r,o=8*i-s-1,c=(1<>1,d=-7,l=n?i-1:0,f=n?-1:1,p=e[t+l];for(l+=f,a=p&(1<<-d)-1,p>>=-d,d+=o;d>0;a=256*a+e[t+l],l+=f,d-=8);for(r=a&(1<<-d)-1,a>>=-d,d+=s;d>0;r=256*r+e[t+l],l+=f,d-=8);if(0===a)a=1-u;else{if(a===c)return r?NaN:1/0*(p?-1:1);r+=Math.pow(2,s),a-=u}return(p?-1:1)*r*Math.pow(2,a-s)},t.write=function(e,t,n,s,i,a){var r,o,c,u=8*a-i-1,d=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:a-1,g=s?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,r=d):(r=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-r))<1&&(r--,c*=2),(t+=r+l>=1?f/c:f*Math.pow(2,1-l))*c>=2&&(r++,c/=2),r+l>=d?(o=0,r=d):r+l>=1?(o=(t*c-1)*Math.pow(2,i),r+=l):(o=t*Math.pow(2,l-1)*Math.pow(2,i),r=0));i>=8;e[n+p]=255&o,p+=g,o/=256,i-=8);for(r=r<0;e[n+p]=255&r,p+=g,r/=256,u-=8);e[n+p-g]|=128*h}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(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++]=i>>16&255,t[n++]=i>>8&255,t[n++]=255&i}return t.buffer}function i(e){return e.buffer}function a(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;enew p.InvokeWithLayer({layer:l,query:new p.InitConnection({apiId:this.apiId,deviceModel:r.deviceModel||s.type().toString()||"Unknown",systemVersion:r.systemVersion||s.release().toString()||"1.0",appVersion:r.appVersion||"1.0",langCode:r.langCode,langPack:"",systemLangCode:r.systemLangCode,query:e,proxy:void 0})}),this._args=r,this._config=void 0,this.phoneCodeHashes=[],this._borrowedSenderPromises={},this._additionalDcsDisabled=r.additionalDcsDisabled}async connect(){await this._initSession(),this._sender=new g(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});const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log);await this._sender.connect(e),this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new p.help.GetConfig({}))),this._updateLoop()}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]":"venus.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;this.isConnected();){await c.sleep(3e3);try{await S(()=>{return e=this._sender.send(new p.Ping({pingId:c.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)})),t=1500,Promise.race([e,c.sleep(t).then(()=>Promise.reject(new Error("TIMEOUT")))]);var e,t},3,100)}catch(e){return await this.disconnect(),void this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new p.updates.GetState)}catch(e){}}}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._borrowedSenderPromises).map(e=>e.then(e=>{if(e)return e.disconnect()}))),this._borrowedSenderPromises={}}async destroy(){await this.disconnect(),this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info("Reconnecting to new data center "+e);const t=u.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}_cleanupBorrowedSender(e){delete this._borrowedSenderPromises[e]}_borrowExportedSender(e){if(this._additionalDcsDisabled)return;let t=this._borrowedSenderPromises[e];return t||(t=this._createExportedSender(e),this._borrowedSenderPromises[e]=t,t.then(t=>{t||delete this._borrowedSenderPromises[e]})),t}async _createExportedSender(e){const t=u.getDC(e),n=new g(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._cleanupBorrowedSender.bind(this)});for(let s=0;s<5;s++)try{if(await n.connect(new this._connection(t.ipAddress,t.port,e,this._log)),this.session.dcId!==e){this._log.info("Exporting authorization for data center "+t.ipAddress);const s=await this.invoke(new p.auth.ExportAuthorization({dcId:e})),i=this._initWith(new p.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await n.send(i)}return n.dcId=e,n}catch(e){await n.disconnect()}}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof f.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof f.MessageMediaWebPage&&n.webpage instanceof f.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof f.MessageMediaPhoto||n instanceof f.Photo?this._downloadPhoto(n,t):n instanceof f.MessageMediaDocument||n instanceof f.Document?this._downloadDocument(n,t):n instanceof f.MessageMediaContact?this._downloadContact(n,t):n instanceof f.WebDocument||n instanceof f.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,i,a;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 f.UserProfilePhoto||s instanceof f.ChatPhoto)return i=s.dcId,a=new f.InputPeerPhotoFileLocation({peer:u.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(a,{dcId:i})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new f.InputStickerSetThumb({stickerset:new f.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=v.indexOf(t);se.type===v[s]),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof f.PhotoStrippedSize?u.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof f.MessageMediaPhoto&&(e=e.photo),!(e instanceof f.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof f.PhotoSizeEmpty?void 0:n instanceof f.PhotoCachedSize||n instanceof f.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new f.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 f.MessageMediaDocument&&(e=e.document),!(e instanceof f.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 f.PhotoCachedSize||n instanceof f.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new f.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")}_downloadWebDocument(e,t){throw new Error("not implemented")}async invoke(e){if("request"!==e.classType)throw new Error("You can only invoke MTProtoRequests");this._lastRequest=(new Date).getTime();let t=0;for(t=0;t1)for(var n=1;n{d[i(e.slice(-8),!0,!0)]=t}),e.exports={encrypt:async function(e,n){const u=d[e];if(!u)return;const l=o(235-n.length),f=t.concat([await r(n),n,l]),p=i(f,!1),g=c(p,s(u.e),u.n);return a(g,256,!1)}}}).call(this,n(12).Buffer)},function(e,t){e.exports=class{constructor(e,t){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}},function(e,t,n){const{Connection:s}=n(39),{ConnectionTCPFull:i}=n(93),{ConnectionTCPAbridged:a}=n(62),{ConnectionTCPObfuscated:r}=n(63);e.exports={Connection:s,ConnectionTCPFull:i,ConnectionTCPAbridged:a,ConnectionTCPObfuscated:r}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=n(89);t.Mutex=s.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(){this._queue=[],this._pending=!1}return e.prototype.isLocked=function(){return this._pending},e.prototype.acquire=function(){var e=this,t=new Promise((function(t){return e._queue.push(t)}));return this._pending||this._dispatchNext(),t},e.prototype.runExclusive=function(e){return this.acquire().then((function(t){var n;try{n=e()}catch(e){throw t(),e}return Promise.resolve(n).then((function(e){return t(),e}),(function(e){throw t(),e}))}))},e.prototype._dispatchNext=function(){this._queue.length>0?(this._pending=!0,this._queue.shift()(this._dispatchNext.bind(this))):this._pending=!1},e}();t.default=s},function(e,t,n){(function(t){var s=function(){return this||void 0===t?this:t}(),i=s.WebSocket||s.MozWebSocket,a=n(91);function r(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(r,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?r:null,version:a}}).call(this,n(43))},function(e,t,n){e.exports=n(92).version},function(e){e.exports=JSON.parse('{"_args":[["websocket@1.0.30","/Users/alexander/dev/telegram-tt"]],"_from":"websocket@1.0.30","_id":"websocket@1.0.30","_inBundle":false,"_integrity":"sha512-aO6klgaTdSMkhfl5VVJzD5fm+Srhh5jLYbS15+OiI1sN6h/RU/XW6WN9J1uVIpUKNmsTvT3Hs35XAFjn9NMfOw==","_location":"/websocket","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"websocket@1.0.30","name":"websocket","escapedName":"websocket","rawSpec":"1.0.30","saveSpec":null,"fetchSpec":"1.0.30"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/websocket/-/websocket-1.0.30.tgz","_spec":"1.0.30","_where":"/Users/alexander/dev/telegram-tt","author":{"name":"Brian McKelvey","email":"theturtle32@gmail.com","url":"https://github.com/theturtle32"},"browser":"lib/browser.js","bugs":{"url":"https://github.com/theturtle32/WebSocket-Node/issues"},"config":{"verbose":false},"contributors":[{"name":"Iñaki Baz Castillo","email":"ibc@aliax.net","url":"http://dev.sipdoc.net"}],"dependencies":{"debug":"^2.2.0","nan":"^2.14.0","typedarray-to-buffer":"^3.1.5","yaeti":"^0.0.6"},"description":"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.","devDependencies":{"buffer-equal":"^1.0.0","faucet":"^0.0.1","gulp":"^4.0.2","gulp-jshint":"^2.0.4","jshint":"^2.0.0","jshint-stylish":"^2.2.1","tape":"^4.9.1"},"directories":{"lib":"./lib"},"engines":{"node":">=0.10.0"},"homepage":"https://github.com/theturtle32/WebSocket-Node","keywords":["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],"license":"Apache-2.0","main":"index","name":"websocket","repository":{"type":"git","url":"git+https://github.com/theturtle32/WebSocket-Node.git"},"scripts":{"gulp":"gulp","install":"(node-gyp rebuild 2> builderror.log) || (exit 0)","test":"faucet test/unit"},"version":"1.0.30"}')},function(e,t){},function(e,t,n){(function(t){const s=n(35);e.exports=class{constructor(e,n){if(!t.isBuffer(e)||!t.isBuffer(n)||16!==n.length)throw new Error("Key and iv need to be a buffer");this.cipher=s.createCipheriv("AES-256-CTR",e,n)}encrypt(e){return t.from(this.cipher.update(e))}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),n.d(t,"authFlow",(function(){return u})),n.d(t,"checkAuthorization",(function(){return d}));var s=n(6),i=n.n(s),a=n(20),r=n.n(a),o=n(8),c=n(31);async function u(e,t,n){const s="phoneNumber"in n?await l(e,t,n):await async function(e,t,n){const{apiId:s,apiHash:a}=t,{botAuthToken:r}=n,{user:o}=await e.invoke(new i.a.auth.ImportBotAuthorization({apiId:s,apiHash:a,botAuthToken:r}));return o}(e,t,n);e._log.info("Signed in successfully as",r.a.getDisplayName(s))}async function d(e){try{return await e.invoke(new i.a.updates.GetState),!0}catch(e){return!1}}async function l(e,t,n){let s,a,r,o=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return f(e,t,n);throw s}else s=n.phoneNumber;const i=await p(e,t,s,n.forceSMS);if(a=i.phoneCodeHash,o=i.isCodeViaApp,"string"!=typeof a)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,u=!1;for(;;)try{try{r=await n.phoneCode(o)}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n)}if(!r)throw new Error("Code is empty");const d=await e.invoke(new i.a.auth.SignIn({phoneNumber:s,phoneCodeHash:a,phoneCode:r}));if(d instanceof i.a.auth.AuthorizationSignUpRequired){u=!0,c=d.termsOfService;break}return d.user}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);n.onError(s)}if(u)for(;;)try{const[t,r]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:o}=await e.invoke(new i.a.auth.SignUp({phoneNumber:s,phoneCodeHash:a,firstName:t,lastName:r}));return c&&await e.invoke(new i.a.help.AcceptTermsOfService({id:c.id})),o}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),l(e,t,n)}async function f(e,t,n){let s=!1;const a=(async()=>{for(;!s;){const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(!(t instanceof i.a.auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:a}=t;await Promise.race([n.qrCode({token:s,expires:a}),Object(o.sleep)(3e4)])}})(),r=new Promise(t=>{e.addEventHandler(e=>{e instanceof i.a.UpdateLoginToken&&t()},{build:e=>e})});try{await Promise.race([r,a])}catch(s){if("RESTART_AUTH"===s.message)return l(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new i.a.auth.ExportLoginToken({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(t instanceof i.a.auth.LoginTokenSuccess&&t.authorization instanceof i.a.auth.Authorization)return t.authorization.user;if(t instanceof i.a.auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new i.a.auth.ImportLoginToken({token:t.token}));if(n instanceof i.a.auth.LoginTokenSuccess&&n.authorization instanceof i.a.auth.Authorization)return n.authorization.user}}catch(s){if("SESSION_PASSWORD_NEEDED"===s.message)return g(e,t,n);throw s}throw void 0}async function p(e,t,n,s=!1){try{const{apiId:a,apiHash:r}=t,o=await e.invoke(new i.a.auth.SendCode({phoneNumber:n,apiId:a,apiHash:r,settings:new i.a.CodeSettings}));if(!s||o.type instanceof i.a.auth.SentCodeTypeSms)return{phoneCodeHash:o.phoneCodeHash,isCodeViaApp:o.type instanceof i.a.auth.SentCodeTypeApp};const c=await e.invoke(new i.a.auth.ResendCode({phoneNumber:n,phoneCodeHash:o.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof i.a.auth.SentCodeTypeApp}}catch(i){if("AUTH_RESTART"===i.message)return p(e,t,n,s);throw i}}async function g(e,t,n){for(;;)try{const t=await e.invoke(new i.a.account.GetPassword),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const a=await Object(c.computeCheck)(t,s),{user:r}=await e.invoke(new i.a.auth.CheckPassword({password:a}));return r}catch(e){n.onError(e)}}},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"downloadFile",(function(){return u}));var s=n(6),i=n.n(s),a=n(20),r=n(8);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}class c{constructor(e){this.maxWorkers=e,o(this,"deferred",void 0),o(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=function(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function u(t,n,s){let{partSizeKb:o,end:u}=s;const{fileSize:d,workers:l=1}=s,{dcId:f,progressCallback:p,start:g=0}=s;u=u&&u{try{const s=await Promise.race([await y.send(new i.a.upload.GetFile({location:n,offset:w,limit:e,precise:t||void 0})),Object(r.sleep)(15e3).then(()=>Promise.reject(new Error("REQUEST_TIMEOUT")))]);if(p){if(p.isCanceled)throw new Error("USER_CANCELED");A+=1/m,p(A)}return!u&&s.bytes.lengthu)break}const I=(await Promise.all(_)).filter(Boolean),P=u?u+1-g:void 0;return e.concat(I,P)}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"uploadFile",(function(){return o}));var s=n(6),i=n.n(s),a=n(8),r=n(20);async function o(t,n){const{file:s,onProgress:o}=n;let{workers:c}=n;const{name:u,size:d}=s,l=Object(a.readBigIntFromBuffer)(Object(a.generateRandomBytes)(8),!0,!0),f=d>10485760,p=1024*Object(r.getAppropriatedPartSize)(d),g=Math.floor((d+p-1)/p),h=e.from(await function(e){return new Response(e).arrayBuffer()}(s)),m=await t._borrowExportedSender(t.session.dcId);c&&d||(c=1),c>=g&&(c=g);let y=0;o&&o(y);for(let e=0;eg&&(n=g);for(let s=e;s{if(await m.send(f?new i.a.upload.SaveBigFilePart({fileId:l,filePart:s,fileTotalParts:g,bytes:e}):new i.a.upload.SaveFilePart({fileId:l,filePart:s,bytes:e})),o){if(o.isCanceled)throw new Error("USER_CANCELED");y+=1/g,o(y)}})())}try{await Promise.race([await Promise.all(t),Object(a.sleep)(15e3*c).then(()=>Promise.reject(new Error("TIMEOUT")))])}catch(t){if("TIMEOUT"===t.message){console.warn("Upload timeout. Retrying..."),e-=c;continue}throw t}}return f?new i.a.InputFileBig({id:l,parts:g,name:u}):new i.a.InputFile({id:l,parts:g,name:u,md5Checksum:""})}}.call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"updateTwoFaSettings",(function(){return u}));var s=n(6),i=n.n(s),a=n(8),r=n(31),o=n(29),c=n.n(o);async function u(t,{isCheckPassword:n,currentPassword:s,newPassword:o,hint:u="",email:d,emailCodeCallback:l,onEmailCodeError:f}){if(!o&&!s)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(d&&(!l||!f))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await t.invoke(new i.a.account.GetPassword);p.newAlgo instanceof i.a.PasswordKdfAlgoUnknown||(p.newAlgo.salt1=e.concat([p.newAlgo.salt1,Object(a.generateRandomBytes)(32)])),!p.hasPassword&&s&&(s=void 0);const g=s?await Object(r.computeCheck)(p,s):new i.a.InputCheckPasswordEmpty;if(n)await t.invoke(new i.a.auth.CheckPassword({password:g}));else try{await t.invoke(new i.a.account.UpdatePasswordSettings({password:g,newSettings:new i.a.account.PasswordInputSettings({newAlgo:p.newAlgo,newPasswordHash:o?await Object(r.computeDigest)(p.newAlgo,o):e.alloc(0),hint:u,email:d,newSecureSettings:void 0})}))}catch(e){if(!(e instanceof c.a.EmailUnconfirmedError))throw e;for(;;)try{const n=await l(e.codeLength);if(!n)throw new Error("Code is empty");await t.invoke(new i.a.account.ConfirmPasswordEmail({code:n}));break}catch(e){f(e)}}}}.call(this,n(12).Buffer)},function(e,t){e.exports="0.0.2"},function(e,t,n){const s=n(101),i=n(102);class a extends Error{}e.exports={NewMessage:s,StopPropagation:a,Raw:i}},function(e,t){},function(e,t,n){const{EventBuilder:s}=n(103);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},function(e,t){e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},function(e,t,n){const s=n(27),i=n(105),a=n(106),r=n(107),o=n(108),c=n(110);e.exports={Memory:s,StringSession:i,CacheApiSession:a,LocalStorageSession:r,IdbSession:o,CallbackSession:c}},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(25);class r extends s{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new a(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 t.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=t.from([this.dcId]),n=t.from(this.serverAddress),s=t.alloc(2);s.writeInt16BE(n.length,0);const i=t.alloc(2);return i.writeInt16BE(this.port,0),"1"+r.encode(t.concat([e,s,n,i,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}).call(this,n(12).Buffer)},function(e,t,n){const s=n(40);e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open("GramJs")).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open("GramJs"),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("GramJs")).put(t,n)}}},function(e,t,n){const s=n(40);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)}}},function(e,t,n){const s=n(109),i=n(40);e.exports=class extends i{_delete(){return s.del("GramJs:"+this._storageKey)}_fetchFromCache(){return s.get("GramJs:"+this._storageKey)}_saveToCache(e){return s.set("GramJs:"+this._storageKey,e)}}},function(e,t,n){"use strict";function s(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}function i(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const i=s(n);return(e,n)=>i.then(s=>n(s.transaction(t,e).objectStore(t)))}let a;function r(){return a||(a=i("keyval-store","keyval")),a}function o(e,t=r()){return t("readonly",t=>s(t.get(e)))}function c(e,t,n=r()){return n("readwrite",n=>(n.put(t,e),s(n.transaction)))}function u(e,t=r()){return t("readwrite",t=>(e.forEach(e=>t.put(e[1],e[0])),s(t.transaction)))}function d(e,t=r()){return t("readonly",t=>Promise.all(e.map(e=>s(t.get(e)))))}function l(e,t,n=r()){return n("readwrite",n=>new Promise((i,a)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),i(s(n.transaction))}catch(e){a(e)}}}))}function f(e,t=r()){return t("readwrite",t=>(t.delete(e),s(t.transaction)))}function p(e=r()){return e("readwrite",e=>(e.clear(),s(e.transaction)))}function g(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},s(e.transaction)))}function h(e=r()){const t=[];return g(e,e=>t.push(e.key)).then(()=>t)}function m(e=r()){const t=[];return g(e,e=>t.push(e.value)).then(()=>t)}function y(e=r()){const t=[];return g(e,e=>t.push([e.key,e.value])).then(()=>t)}n.r(t),n.d(t,"clear",(function(){return p})),n.d(t,"createStore",(function(){return i})),n.d(t,"del",(function(){return f})),n.d(t,"entries",(function(){return y})),n.d(t,"get",(function(){return o})),n.d(t,"getMany",(function(){return d})),n.d(t,"keys",(function(){return h})),n.d(t,"promisifyRequest",(function(){return s})),n.d(t,"set",(function(){return c})),n.d(t,"setMany",(function(){return u})),n.d(t,"update",(function(){return l})),n.d(t,"values",(function(){return m}))},function(e,t,n){(function(t){const s=n(27),i=n(28),a=n(20);e.exports=class extends s{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:n,hashes:s}=this._sessionData,{ipAddress:r,port:o}=a.getDC(e);this.setDC(e,r,o,!0),await Promise.all(Object.keys(n).map(async e=>{const a="string"==typeof n[e]?t.from(n[e],"hex"):t.from(n[e]);if(s[e]){const n="string"==typeof s[e]?t.from(s[e],"hex"):t.from(s[e]);this._authKeys[e]=new i(a,n)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)}))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach(t=>{const n=this._authKeys[t];n&&n._key&&(e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex"))}),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}}).call(this,n(12).Buffer)},function(e,t,n){"use strict";n.r(t);var s={};n.r(s),n.d(s,"destroy",(function(){return p.a})),n.d(s,"disconnect",(function(){return p.b})),n.d(s,"downloadMedia",(function(){return p.c})),n.d(s,"fetchCurrentUser",(function(){return p.d})),n.d(s,"provideAuthPhoneNumber",(function(){return o.l})),n.d(s,"provideAuthCode",(function(){return o.j})),n.d(s,"provideAuthPassword",(function(){return o.k})),n.d(s,"provideAuthRegistration",(function(){return o.m})),n.d(s,"restartAuth",(function(){return o.n})),n.d(s,"restartAuthWithQr",(function(){return o.o})),n.d(s,"fetchChats",(function(){return c.j})),n.d(s,"fetchFullChat",(function(){return c.k})),n.d(s,"searchChats",(function(){return c.w})),n.d(s,"requestChatUpdate",(function(){return c.u})),n.d(s,"saveDraft",(function(){return c.v})),n.d(s,"clearDraft",(function(){return c.a})),n.d(s,"fetchChat",(function(){return c.h})),n.d(s,"updateChatMutedState",(function(){return c.H})),n.d(s,"createChannel",(function(){return c.b})),n.d(s,"joinChannel",(function(){return c.q})),n.d(s,"leaveChannel",(function(){return c.r})),n.d(s,"deleteChannel",(function(){return c.d})),n.d(s,"createGroupChat",(function(){return c.c})),n.d(s,"editChatPhoto",(function(){return c.g})),n.d(s,"toggleChatPinned",(function(){return c.z})),n.d(s,"toggleChatArchived",(function(){return c.y})),n.d(s,"toggleDialogUnread",(function(){return c.A})),n.d(s,"fetchChatFolders",(function(){return c.i})),n.d(s,"editChatFolder",(function(){return c.f})),n.d(s,"deleteChatFolder",(function(){return c.e})),n.d(s,"fetchRecommendedChatFolders",(function(){return c.n})),n.d(s,"getChatByUsername",(function(){return c.o})),n.d(s,"togglePreHistoryHidden",(function(){return c.B})),n.d(s,"updateChatDefaultBannedRights",(function(){return c.F})),n.d(s,"updateChatMemberBannedRights",(function(){return c.G})),n.d(s,"updateChatTitle",(function(){return c.I})),n.d(s,"updateChatAbout",(function(){return c.D})),n.d(s,"toggleSignatures",(function(){return c.C})),n.d(s,"updateChatAdmin",(function(){return c.E})),n.d(s,"fetchGroupsForDiscussion",(function(){return c.l})),n.d(s,"setDiscussionGroup",(function(){return c.x})),n.d(s,"migrateChat",(function(){return c.s})),n.d(s,"openChatByInvite",(function(){return c.t})),n.d(s,"fetchMembers",(function(){return c.m})),n.d(s,"fetchMessages",(function(){return u.g})),n.d(s,"fetchMessage",(function(){return u.e})),n.d(s,"sendMessage",(function(){return u.v})),n.d(s,"pinMessage",(function(){return u.q})),n.d(s,"unpinAllMessages",(function(){return u.y})),n.d(s,"deleteMessages",(function(){return u.b})),n.d(s,"deleteHistory",(function(){return u.a})),n.d(s,"markMessageListRead",(function(){return u.o})),n.d(s,"markMessagesRead",(function(){return u.p})),n.d(s,"requestThreadInfoUpdate",(function(){return u.r})),n.d(s,"searchMessagesLocal",(function(){return u.u})),n.d(s,"searchMessagesGlobal",(function(){return u.t})),n.d(s,"fetchWebPagePreview",(function(){return u.j})),n.d(s,"editMessage",(function(){return u.d})),n.d(s,"forwardMessages",(function(){return u.l})),n.d(s,"loadPollOptionResults",(function(){return u.n})),n.d(s,"sendPollVote",(function(){return u.w})),n.d(s,"findFirstMessageIdAfterDate",(function(){return u.k})),n.d(s,"fetchPinnedMessages",(function(){return u.h})),n.d(s,"fetchScheduledHistory",(function(){return u.i})),n.d(s,"sendScheduledMessages",(function(){return u.x})),n.d(s,"rescheduleMessage",(function(){return u.s})),n.d(s,"deleteScheduledMessages",(function(){return u.c})),n.d(s,"fetchMessageLink",(function(){return u.f})),n.d(s,"fetchFullUser",(function(){return v})),n.d(s,"fetchNearestCountry",(function(){return A})),n.d(s,"fetchTopUsers",(function(){return I})),n.d(s,"fetchContactList",(function(){return P})),n.d(s,"fetchUsers",(function(){return C})),n.d(s,"updateContact",(function(){return S})),n.d(s,"deleteUser",(function(){return M})),n.d(s,"fetchProfilePhotos",(function(){return k})),n.d(s,"fetchStickerSets",(function(){return D})),n.d(s,"fetchRecentStickers",(function(){return B})),n.d(s,"fetchFavoriteStickers",(function(){return x})),n.d(s,"fetchFeaturedStickers",(function(){return j})),n.d(s,"faveSticker",(function(){return N})),n.d(s,"fetchStickers",(function(){return V})),n.d(s,"fetchSavedGifs",(function(){return q})),n.d(s,"searchStickers",(function(){return L})),n.d(s,"installStickerSet",(function(){return H})),n.d(s,"uninstallStickerSet",(function(){return K})),n.d(s,"searchGifs",(function(){return z})),n.d(s,"fetchAnimatedEmojis",(function(){return F})),n.d(s,"fetchStickersForEmoji",(function(){return G})),n.d(s,"fetchEmojiKeywords",(function(){return W})),n.d(s,"checkChatUsername",(function(){return Z})),n.d(s,"setChatUsername",(function(){return Y})),n.d(s,"updatePrivateLink",(function(){return Q})),n.d(s,"updateProfile",(function(){return ge})),n.d(s,"checkUsername",(function(){return he})),n.d(s,"updateUsername",(function(){return me})),n.d(s,"fetchBlockedContacts",(function(){return ve})),n.d(s,"blockContact",(function(){return Ae})),n.d(s,"unblockContact",(function(){return Ie})),n.d(s,"updateProfilePhoto",(function(){return ye})),n.d(s,"uploadProfilePhoto",(function(){return be})),n.d(s,"fetchWallpapers",(function(){return _e})),n.d(s,"uploadWallpaper",(function(){return we})),n.d(s,"fetchAuthorizations",(function(){return Pe})),n.d(s,"terminateAuthorization",(function(){return Ce})),n.d(s,"terminateAllAuthorizations",(function(){return Se})),n.d(s,"fetchNotificationExceptions",(function(){return Me})),n.d(s,"fetchNotificationSettings",(function(){return ke})),n.d(s,"updateContactSignUpNotification",(function(){return Ee})),n.d(s,"updateNotificationSettings",(function(){return Re})),n.d(s,"fetchLanguages",(function(){return Ue})),n.d(s,"fetchLangPack",(function(){return Oe})),n.d(s,"fetchPrivacySettings",(function(){return Te})),n.d(s,"setPrivacySettings",(function(){return xe})),n.d(s,"registerDevice",(function(){return De})),n.d(s,"unregisterDevice",(function(){return Be})),n.d(s,"getPasswordInfo",(function(){return ne})),n.d(s,"checkPassword",(function(){return ie})),n.d(s,"clearPassword",(function(){return ae})),n.d(s,"updatePassword",(function(){return re})),n.d(s,"updateRecoveryEmail",(function(){return oe})),n.d(s,"provideRecoveryEmailCode",(function(){return ce})),n.d(s,"answerCallbackButton",(function(){return Ne.a})),n.d(s,"validateRequestedInfo",(function(){return Fe})),n.d(s,"sendPaymentForm",(function(){return Le})),n.d(s,"getPaymentForm",(function(){return qe})),n.d(s,"getReceipt",(function(){return He}));var i=n(4),a=n(30),r=n(26),o=n(17),c=n(7),u=n(10),d=n(15),l=n.n(d),f=n(0),p=n(1),g=n(2),h=n(13),m=n(3),y=n(19),b=n(5),_=n(16);let w;async function v({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;const s=await Object(p.g)(new f.Api.users.GetFullUser({id:n}));if(!s)return;const i=Object(h.b)(s);w({"@type":"updateUser",id:e,user:{fullInfo:i.fullInfo}})}async function A(){const e=await Object(p.g)(new f.Api.help.GetNearestDc);return e?e.country:void 0}async function I({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetTopPeers({hash:e,correspondents:!0}));if(!(t instanceof f.Api.contacts.TopPeers))return;const n=t.users.map(h.a).filter(e=>!!e&&!e.isSelf),s=n.map(({id:e})=>e);return{hash:Object(g.q)(s),ids:s,users:n}}async function P({hash:e=0}){const t=await Object(p.g)(new f.Api.contacts.GetContacts({hash:e}));if(t&&!(t instanceof f.Api.contacts.ContactsNotModified))return t.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),{hash:Object(g.q)([t.savedCount,...t.contacts.map(({userId:e})=>e)]),users:t.users.map(h.a).filter(Boolean),chats:t.users.map(e=>Object(m.d)(e)).filter(Boolean)}}async function C({users:e}){const t=await Object(p.g)(new f.Api.users.GetUsers({id:e.map(({id:e,accessHash:t})=>Object(g.i)(e,t))}));if(t&&t.length)return t.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),t.map(h.a).filter(Boolean)}function S({phone:e,firstName:t,lastName:n}){return Object(p.g)(new f.Api.contacts.ImportContacts({contacts:[Object(g.e)({phone:e||"",firstName:t||"",lastName:n||""})]}))}async function M({id:e,accessHash:t}){const n=Object(g.g)(e,t);if(!(n instanceof f.Api.InputUser))return;await Object(p.g)(new f.Api.contacts.DeleteContacts({id:[n]}))&&w({"@type":"deleteUser",id:e})}async function k(e,t){if(e){const{id:t,accessHash:n}=e,s=await Object(p.g)(new f.Api.photos.GetUserPhotos({userId:Object(g.g)(t,n),limit:i.u,offset:0,maxId:l()("0")}));if(!s)return;return function(e){e.photos.forEach(_.b)}(s),{photos:s.photos.filter(e=>e instanceof f.Api.Photo).map(y.a)}}const n=await Object(u.u)({chatOrUser:t,type:"profilePhoto",limit:i.u});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map(e=>e.content.action.photo).filter(Boolean),users:a}}var E=n(22),R=n(9);let U,O,T;async function D({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetAllStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.AllStickersNotModified))return t.sets.forEach(e=>{e.thumbs&&e.thumbs.length&&(b.a.stickerSets[String(e.id)]=e)}),{hash:t.hash,sets:t.sets.map(E.b)}}async function B({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetRecentStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.RecentStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function x({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFavedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FavedStickersNotModified))return{hash:t.hash,stickers:$(t.stickers)}}async function j({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetFeaturedStickers({hash:e}));if(t&&!(t instanceof f.Api.messages.FeaturedStickersNotModified))return{hash:t.hash,sets:t.sets.map(E.c)}}async function N({sticker:e,unfave:t}){const n=new f.Api.messages.FaveSticker({id:Object(g.f)(e),unfave:t});await Object(p.g)(n)&&U({"@type":"updateFavoriteStickers"})}async function V({stickerSetId:e,accessHash:t}){const n=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:Object(g.l)(e,t)}));var s;if(n)return{set:Object(E.b)(n.set),stickers:$(n.documents),packs:(s=n.packs,s.reduce((e,{emoticon:t,documents:n})=>(e[t]=n.map(e=>Object(E.a)(b.a.documents[String(e)])).filter(Boolean),e),{}))}}async function F(){const e=await Object(p.g)(new f.Api.messages.GetStickerSet({stickerset:new f.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:Object(E.b)(e.set),stickers:$(e.documents)}}async function L({query:e,hash:t}){const n=await Object(p.g)(new f.Api.messages.SearchStickerSets({q:e,hash:t}));if(n&&!(n instanceof f.Api.messages.FoundStickerSetsNotModified))return{hash:n.hash,sets:n.sets.map(E.c)}}async function q({hash:e}){const t=await Object(p.g)(new f.Api.messages.GetSavedGifs({hash:e}));if(t&&!(t instanceof f.Api.messages.SavedGifsNotModified))return{hash:t.hash,gifs:J(t.gifs)}}async function H({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.InstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function K({stickerSetId:e,accessHash:t}){await Object(p.g)(new f.Api.messages.UninstallStickerSet({stickerset:Object(g.l)(e,t)}))&&U({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function z({query:e,offset:t=""}){if(!O){const e=await Object(p.g)(new f.Api.help.GetConfig);if(!e)return;const t=await Object(p.g)(new f.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof f.Api.User))return;O=new f.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await Object(p.g)(new f.Api.messages.GetInlineBotResults({bot:O,peer:new f.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map(e=>{if(e instanceof f.Api.BotInlineMediaResult)return e.document}).filter(Boolean);return{nextOffset:n.nextOffset,gifs:J(s)}}async function G({emoji:e,hash:t=0}){const n=await Object(p.g)(new f.Api.messages.GetStickers({emoticon:e,hash:t}));if(n&&!(n instanceof f.Api.messages.StickersNotModified))return{stickers:$(n.stickers),hash:n.hash}}async function W({language:e,fromVersion:t}){const n=await Object(p.g)(new f.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce((e,t)=>(e[t.keyword]=t.emoticons,e),{})}}function $(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(E.a)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}function J(e){return e.map(e=>{if(e instanceof f.Api.Document){const t=Object(R.m)(e);if(t)return b.a.documents[String(e.id)]=e,t}}).filter(Boolean)}async function Z({username:e}){try{return await Object(p.g)(new f.Api.channels.CheckUsername({channel:new f.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Y({chat:e,username:t}){await Object(p.g)(new f.Api.channels.UpdateUsername({channel:Object(g.g)(e.id,e.accessHash),username:t}))&&T({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Q({chat:e}){const t=await Object(p.g)(new f.Api.messages.ExportChatInvite({peer:Object(g.i)(e.id,e.accessHash)}));t&&t instanceof f.Api.ChatInviteExported&&T({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const X={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"},ee={};let te;async function ne(){const e=await Object(p.g)(new f.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function se(e){return te({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise((e,t)=>{ee.resolve=e,ee.reject=t})}async function ie(e){try{return await Object(p.h)({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return ue(e),!1}}async function ae(e){try{return await Object(p.h)({currentPassword:e}),!0}catch(e){return ue(e),!1}}async function re(e,t,n,s){try{return await Object(p.h)({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}async function oe(e,t){try{return await Object(p.h)({currentPassword:e,newPassword:e,email:t,emailCodeCallback:se,onEmailCodeError:ue}),!0}catch(e){return ue(e),!1}}function ce(e){ee.resolve(e)}function ue(e){let t;if(e instanceof f.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=X[e.message];t||(t="Unexpected Error",i.g&&console.error(e)),te({"@type":"updateTwoFaError",message:t})}var de=n(24),le=n(18),fe=n(14);const pe=["ar","fa"];function ge({firstName:e,lastName:t,about:n}){return Object(p.g)(new f.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function he(e){return Object(p.g)(new f.Api.account.CheckUsername({username:e}))}function me(e){return Object(p.g)(new f.Api.account.UpdateUsername({username:e}))}async function ye(e){const t=await Object(p.i)(e);return Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function be(e){const t=await Object(p.i)(e);await Object(p.g)(new f.Api.photos.UploadProfilePhoto({file:t}))}async function _e(e){const t=await Object(p.g)(new f.Api.account.GetWallPapers({hash:e}));if(!t||t instanceof f.Api.account.WallPapersNotModified)return;const n=t.wallpapers.filter(e=>e instanceof f.Api.WallPaper&&e.document instanceof f.Api.Document&&(!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return n.forEach(e=>{b.a.documents[String(e.document.id)]=e.document}),{hash:t.hash,wallpapers:n.map(de.b).filter(Boolean)}}async function we(e){const t=await Object(p.i)(e),n=await Object(p.g)(new f.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new f.Api.WallPaperSettings}));if(!(n&&n instanceof f.Api.WallPaper))return;const s=Object(de.b)(n);return s?(b.a.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function ve(){const e=await Object(p.g)(new f.Api.contacts.GetBlocked({limit:i.f}));if(e)return je(e),{users:e.users.map(h.a).filter(Boolean),chats:e.chats.map(e=>Object(m.d)(e,void 0,!0)).filter(Boolean),blockedIds:e.blocked.map(e=>Object(m.j)(e.peerId)),totalCount:e instanceof f.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function Ae(e){return Object(p.g)(new f.Api.contacts.Block({id:Object(g.o)(e)}))}function Ie(e,t){return Object(p.g)(new f.Api.contacts.Unblock({id:Object(g.i)(e,t)}))}async function Pe(){const e=await Object(p.g)(new f.Api.account.GetAuthorizations);if(e)return e.authorizations.map(de.a)}function Ce(e){return Object(p.g)(new f.Api.account.ResetAuthorization({hash:l()(e)}))}function Se(){return Object(p.g)(new f.Api.auth.ResetAuthorizations)}async function Me(){const e=await Object(p.g)(new f.Api.account.GetNotifyExceptions({compareSound:!0}),!0);(e instanceof f.Api.Updates||e instanceof f.Api.UpdatesCombined)&&je(e)}async function ke(){const[e,t,n,s]=await Promise.all([Object(p.g)(new f.Api.account.GetContactSignUpNotification),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyUsers})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyChats})),Object(p.g)(new f.Api.account.GetNotifySettings({peer:new f.Api.InputNotifyBroadcasts}))]);if(!t||!n||!s)return!1;const{silent:i,muteUntil:a,showPreviews:r}=t,{silent:o,muteUntil:c,showPreviews:u}=n,{silent:d,muteUntil:l,showPreviews:g}=s;return{hasContactJoinedNotifications:!e,hasPrivateChatsNotifications:!(i||"number"==typeof a&&Date.now()<1e3*a),hasPrivateChatsMessagePreview:r,hasGroupNotifications:!(o||"number"==typeof c&&Date.now()<1e3*c),hasGroupMessagePreview:u,hasBroadcastNotifications:!(d||"number"==typeof l&&Date.now()<1e3*l),hasBroadcastMessagePreview:g}}function Ee(e){return Object(p.g)(new f.Api.account.SetContactSignUpNotification({silent:e}))}function Re(e,{isSilent:t,shouldShowPreviews:n}){let s;s="contact"===e?new f.Api.InputNotifyUsers:"group"===e?new f.Api.InputNotifyChats:new f.Api.InputNotifyBroadcasts;const i={showPreviews:n,silent:t,muteUntil:t?2**31-1:void 0};return Object(p.g)(new f.Api.account.UpdateNotifySettings({peer:s,settings:new f.Api.InputPeerNotifySettings(i)}))}async function Ue(){const e=await Object(p.g)(new f.Api.langpack.GetLanguages({langPack:i.i}));if(e)return e.map(le.b)}async function Oe({sourceLangPacks:e,langCode:t}){const n=(await Promise.all(e.map(e=>Object(p.g)(new f.Api.langpack.GetLangPack({langPack:e,langCode:pe.includes(t)?t+"-raw":t}))))).filter(Boolean).map(e=>Object(fe.a)(e.strings.map(le.b),"key"));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function Te(e){const t=Object(g.k)(e),n=await Object(p.g)(new f.Api.account.GetPrivacy({key:t}));if(n)return je(n),Object(de.d)(n.rules)}function De(e){const t=Object(p.e)().session.getAuthKey().getKey();return Object(p.g)(new f.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Be(e){return Object(p.g)(new f.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function xe(e,t){const n=Object(g.k)(e),s=[];switch(t.allowedUsers&&s.push(new f.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.allowedChats&&s.push(new f.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map(({id:e})=>-e)})),t.blockedUsers&&s.push(new f.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map(({id:e,accessHash:t})=>Object(g.i)(e,t))})),t.blockedChats&&s.push(new f.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map(({id:e})=>-e)})),t.visibility){case"everybody":s.push(new f.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new f.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new f.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new f.Api.InputPrivacyValueDisallowAll)}const i=await Object(p.g)(new f.Api.account.SetPrivacy({key:n,rules:s}));if(i)return je(i),Object(de.d)(i.rules)}function je(e){e.users.forEach(e=>{e instanceof f.Api.User&&(b.a.users[e.id]=e)}),e.chats.forEach(e=>{(e instanceof f.Api.Chat||e instanceof f.Api.Channel)&&(b.a.chats[e.id]=e)})}var Ne=n(72);function Ve(e){if(e)return Object.values(e).map(e=>({id:e.id,title:e.title,amount:e.prices.reduce((e,t)=>e+Number(t.amount.value),0),prices:e.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}))}))}async function Fe({messageId:e,requestInfo:t,shouldSave:n}){const s=await Object(p.g)(new f.Api.payments.ValidateRequestedInfo({msgId:e,save:n||void 0,info:Object(g.p)(t)}));if(!s)return;const{id:i,shippingOptions:a}=s;return i?{id:i,shippingOptions:Ve(a)}:void 0}function Le({messageId:e,requestedInfoId:t,shippingOptionId:n,credentials:s}){return Object(p.g)(new f.Api.payments.SendPaymentForm({msgId:e,requestedInfoId:t,shippingOptionId:n,credentials:new f.Api.InputPaymentCredentials({save:s.save,data:new f.Api.DataJSON({data:JSON.stringify(s.data)})})}),!0)}async function qe({messageId:e}){const t=await Object(p.g)(new f.Api.payments.GetPaymentForm({msgId:e}));if(t)return function(e){const{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,nativeParams:a,savedInfo:r,invoice:o}=e,{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:y}=o,b=y.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),_=a?JSON.parse(a.data):{};return{canSaveCredentials:t,passwordMissing:n,providerId:s,nativeProvider:i,savedInfo:r,invoice:{test:c,nameRequested:u,phoneRequested:d,emailRequested:l,shippingAddressRequested:f,flexible:p,phoneToProvider:g,emailToProvider:h,currency:m,prices:b},nativeParams:{needCardholderName:_.need_cardholder_name,needCountry:_.need_country,needZip:_.need_zip,publishableKey:_.publishable_key}}}(t)}async function He(e){const t=await Object(p.g)(new f.Api.payments.GetPaymentReceipt({msgId:e}));if(t)return function(e){const{invoice:t,info:n,shipping:s,currency:i,totalAmount:a,credentialsTitle:r}=e,{shippingAddress:o,phone:c,name:u}=n||{},{prices:d}=t,l=d.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)}));let f,p;return s&&(f=s.prices.map(({label:e,amount:t})=>({label:e,amount:Number(t.value)})),p=s.title),{currency:i,prices:l,info:{shippingAddress:o,phone:c,name:u},totalAmount:Number(a.value),credentialsTitle:r,shippingPrices:f,shippingMethod:p}}(t)}let Ke;async function ze(e,t){Ke=e,Object(r.a)(Ze),Object(o.a)(Ze),Object(c.p)(Ze),Object(u.m)(Ze),function(e){w=e}(Ze),function(e){U=e}(Ze),function(e){T=e}(Ze),function(e){te=e}(Ze),await Object(p.f)(Ze,t)}const Ge=Object(a.c)((function(e){if(!Je||e!==$e)return;const t=Je;Je=void 0,t.forEach(Ke)}));let We,$e,Je;function Ze(e){Je?Je.push(e):Je=[e],We&&!i.b.has(e["@type"])||(We=Object(a.b)(Ge,i.c,!0),$e=Math.random()),We($e)}self.onerror=e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",e=>{console.error(e),Xe({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})});const Ye=new Map;function Qe(e){Xe({type:"update",update:e})}function Xe(e,t){t?postMessage(e,[t]):postMessage(e)}i.g&&console.log(">>> FINISH LOAD WORKER"),onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await ze(Qe,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:a}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Xe({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ye.set(e,t),a.push(t)}const t=await function(e,...t){return s[e](...t)}(n,...a),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Xe({type:"methodResponse",messageId:e,response:t},i)}catch(t){i.g&&console.error(t),e&&Xe({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ye.delete(e);break}case"cancelProgress":{const e=Ye.get(t.messageId);e&&(e.isCanceled=!0);break}}}}]); +//# sourceMappingURL=8ede9bdfe3390ee397af.worker.js.map \ No newline at end of file diff --git a/dist/7c2292f972e10d28cc51.worker.js.LICENSE.txt b/dist/8ede9bdfe3390ee397af.worker.js.LICENSE.txt similarity index 100% rename from dist/7c2292f972e10d28cc51.worker.js.LICENSE.txt rename to dist/8ede9bdfe3390ee397af.worker.js.LICENSE.txt diff --git a/dist/7c2292f972e10d28cc51.worker.js.map b/dist/8ede9bdfe3390ee397af.worker.js.map similarity index 99% rename from dist/7c2292f972e10d28cc51.worker.js.map rename to dist/8ede9bdfe3390ee397af.worker.js.map index 0fcc5702..b4b9c785 100644 --- a/dist/7c2292f972e10d28cc51.worker.js.map +++ b/dist/8ede9bdfe3390ee397af.worker.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/gramjs/index.js","webpack:///./src/util/cacheApi.ts","webpack:///./src/api/gramjs/methods/media.ts","webpack:///./src/api/gramjs/methods/client.ts","webpack:///./src/api/gramjs/gramjsBuilders/index.ts","webpack:///./src/api/gramjs/apiBuilders/peers.ts","webpack:///./src/api/gramjs/apiBuilders/chats.ts","webpack:///./src/config.ts","webpack:///./src/api/gramjs/localDb.ts","webpack:///./src/lib/gramjs/tl/api.js","webpack:///./src/api/gramjs/methods/chats.ts","webpack:///./src/lib/gramjs/Helpers.js","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/api/gramjs/apiBuilders/messages.ts","webpack:///./src/api/gramjs/methods/messages.ts","webpack:///./src/api/types/index.ts","webpack:///./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack:///./src/api/gramjs/apiBuilders/users.ts","webpack:///./src/util/iteratees.ts","webpack:///./node_modules/big-integer/BigInteger.js","webpack:///./src/api/gramjs/helpers.ts","webpack:///./src/api/gramjs/methods/auth.ts","webpack:///./src/api/gramjs/apiBuilders/helpers.ts","webpack:///./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack:///./src/api/gramjs/apiBuilders/common.ts","webpack:///./src/lib/gramjs/Utils.js","webpack:///./src/lib/gramjs/tl/index.js","webpack:///./src/api/gramjs/apiBuilders/symbols.ts","webpack:///./src/lib/gramjs/errors/Common.js","webpack:///./src/api/gramjs/apiBuilders/misc.ts","webpack:///./src/lib/gramjs/extensions/BinaryReader.js","webpack:///./src/api/gramjs/updater.ts","webpack:///./src/lib/gramjs/sessions/Memory.js","webpack:///./src/lib/gramjs/crypto/AuthKey.js","webpack:///./src/lib/gramjs/errors/index.js","webpack:///./src/util/schedulers.ts","webpack:///./src/lib/gramjs/Password.js","webpack:///./src/lib/gramjs/tl/core/GZIPPacked.js","webpack:///./src/util/waveform.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/gramjs/crypto/crypto.js","webpack:///./src/lib/gramjs/errors/RPCBaseErrors.js","webpack:///./src/lib/gramjs/tl/core/TLMessage.js","webpack:///./src/lib/gramjs/tl/core/MessageContainer.js","webpack:///./src/lib/gramjs/network/connection/Connection.js","webpack:///./src/lib/gramjs/sessions/StorageSession.js","webpack:///./node_modules/pako/dist/pako_inflate.js","webpack:///./src/lib/gramjs/extensions/index.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/lib/gramjs/tl/generationHelpers.js","webpack:///./node_modules/@cryptography/aes/dist/es/aes.js","webpack:///./src/lib/gramjs/extensions/Logger.js","webpack:///./src/lib/gramjs/errors/RPCErrorList.js","webpack:///./src/lib/gramjs/sessions/Abstract.js","webpack:///./src/lib/gramjs/tl/AllTLObjects.js","webpack:///./src/lib/gramjs/network/MTProtoSender.js","webpack:///./src/lib/gramjs/network/MTProtoPlainSender.js","webpack:///./src/lib/gramjs/network/MTProtoState.js","webpack:///./src/lib/gramjs/crypto/IGE.js","webpack:///./src/lib/gramjs/tl/core/index.js","webpack:///./src/lib/gramjs/tl/core/RPCResult.js","webpack:///./src/lib/gramjs/network/Authenticator.js","webpack:///./src/lib/gramjs/extensions/MessagePacker.js","webpack:///./src/lib/gramjs/extensions/BinaryWriter.js","webpack:///./src/lib/gramjs/network/index.js","webpack:///./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack:///./src/lib/gramjs/extensions/AsyncQueue.js","webpack:///./src/lib/gramjs/network/connection/TCPAbridged.js","webpack:///./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/api/gramjs/methods/bots.ts","webpack:///./node_modules/base64-js/index.js","webpack:///./node_modules/ieee754/index.js","webpack:///./node_modules/isarray/index.js","webpack:///(webpack)/buildin/module.js","webpack:///./src/lib/gramjs/crypto/converters.ts","webpack:///./src/lib/gramjs/crypto/words.ts","webpack:///./src/lib/gramjs/tl/apiTl.js","webpack:///./src/lib/gramjs/tl/schemaTl.js","webpack:///./src/lib/gramjs/client/TelegramClient.js","webpack:///./node_modules/os-browserify/browser.js","webpack:///./node_modules/process/browser.js","webpack:///./src/lib/gramjs/crypto/Factorizator.js","webpack:///./src/lib/gramjs/crypto/RSA.js","webpack:///./src/lib/gramjs/network/RequestState.js","webpack:///./src/lib/gramjs/network/connection/index.js","webpack:///./node_modules/async-mutex/lib/index.js","webpack:///./node_modules/async-mutex/lib/Mutex.js","webpack:///./node_modules/websocket/lib/browser.js","webpack:///./node_modules/websocket/lib/version.js","webpack:///./src/lib/gramjs/crypto/CTR.js","webpack:///./src/lib/gramjs/client/auth.ts","webpack:///./src/lib/gramjs/client/downloadFile.ts","webpack:///./src/lib/gramjs/client/uploadFile.ts","webpack:///./src/lib/gramjs/client/2fa.ts","webpack:///./src/lib/gramjs/Version.js","webpack:///./src/lib/gramjs/events/index.js","webpack:///./src/lib/gramjs/events/Raw.js","webpack:///./src/lib/gramjs/events/common.js","webpack:///./src/lib/gramjs/sessions/index.js","webpack:///./src/lib/gramjs/sessions/StringSession.js","webpack:///./src/lib/gramjs/sessions/CacheApiSession.js","webpack:///./src/lib/gramjs/sessions/LocalStorageSession.js","webpack:///./src/lib/gramjs/sessions/IdbSession.js","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/lib/gramjs/sessions/CallbackSession.js","webpack:///./src/api/gramjs/methods/users.ts","webpack:///./src/api/gramjs/methods/symbols.ts","webpack:///./src/api/gramjs/methods/management.ts","webpack:///./src/api/gramjs/methods/twoFaSettings.ts","webpack:///./src/api/gramjs/methods/settings.ts","webpack:///./src/api/gramjs/apiBuilders/payments.ts","webpack:///./src/api/gramjs/methods/payments.ts","webpack:///./src/api/gramjs/provider.ts","webpack:///./src/api/gramjs/worker/worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Api","require","TelegramClient","connection","tl","version","events","utils","errors","sessions","extensions","helpers","cacheApi","self","caches","Type","async","fetch","cacheName","type","request","Request","cache","open","response","match","Text","text","Blob","blob","substr","contentType","headers","Json","json","err","console","warn","save","data","cacheData","JSON","stringify","Response","put","clear","delete","downloadMedia","url","mediaFormat","start","end","client","isConnected","onProgress","mimeType","fullSize","mediaMatch","arrayBuffer","Promise","reject","Error","entityType","entityId","sizeType","replace","undefined","entity","getEntityTypeById","Number","Math","abs","localDb","chats","users","messages","documents","photos","stickerSets","includes","ApiMediaFormat","Stream","acceptsBuffer","progressCallback","workers","DOWNLOAD_WORKERS","GramJs","Message","message","media","MessageMediaPhoto","MessageMediaDocument","document","Document","attributes","some","a","DocumentAttributeSticker","getMessageMediaMimeType","size","Photo","downloadStickerSetThumb","Lottie","getMimeType","downloadProfilePhoto","download","parsed","DataUri","blobToDataUri","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","MEDIA_CACHE_MAX_BYTES","MEDIA_CACHE_DISABLED","startsWith","MEDIA_CACHE_NAME_AVATARS","MEDIA_CACHE_NAME","prepared","mediaData","URL","createObjectURL","prepareMedia","fallbackMimeType","length","subarray","reduce","result","byte","toString","GramJsLogger","setLevel","DEBUG_GRAMJS","gramJsUpdateEventBuilder","build","update","onUpdate","init","_onUpdate","sessionData","DEBUG","log","CallbackSession","onSessionUpdate","process","deviceModel","navigator","userAgent","appVersion","APP_VERSION","useWSS","additionalDcsDisabled","IS_TEST","addEventHandler","handleGramJsUpdate","updater","phoneNumber","onRequestPhoneNumber","phoneCode","onRequestCode","password","onRequestPassword","firstAndLastNames","onRequestRegistration","qrCode","onRequestQrCode","onError","onAuthError","onAuthReady","fetchCurrentUser","destroy","invokeRequest","auth","LogOut","disconnect","getClient","UpdateConnectionState","state","connected","UpdatesTooLong","GetFullUser","id","InputUserSelf","connectionState","handleTerminatedSession","shouldHandleUpdates","shouldThrow","className","invoke","updatesContainer","Updates","UpdatesCombined","updates","entities","forEach","_entities","injectUpdateEntities","error","isSlowMode","SendMessage","SendMedia","SendMultiMedia","dispatchErrorUpdate","args","downloadMediaWithClient","uploadFile","file","UPLOAD_WORKERS","updateTwoFaSettings","params","userFull","user","User","currentUser","buildApiUserFromFull","setMessageBuilderCurrentUserId","onCurrentUserUpdate","chatOrUserId","buildPeer","PeerUser","userId","PeerChannel","channelId","PeerChat","chatId","buildInputPeer","accessHash","InputPeerUser","BigInt","InputPeerChannel","InputPeerChat","buildInputPeerFromLocalDb","buildInputEntity","InputUser","InputChannel","buildInputStickerSet","InputStickerSetID","buildInputDocument","InputDocument","pick","buildInputMediaDocument","inputDocument","InputMediaDocument","buildInputPoll","pollParams","randomId","summary","quiz","poll","Poll","publicVoters","isPublic","question","answers","map","option","PollAnswer","Buffer","from","multipleChoice","InputMediaPoll","correctAnswers","solution","solutionEntities","buildMtpMessageEntity","buildFilterFromApiFolder","folder","emoticon","contacts","nonContacts","groups","channels","bots","excludeArchived","excludeMuted","excludeRead","pinnedChatIds","includedChatIds","excludedChatIds","pinnedPeers","filter","Boolean","includePeers","excludePeers","DialogFilter","title","broadcasts","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","fromId","offset","ApiMessageEntityTypes","Bold","MessageEntityBold","Italic","MessageEntityItalic","Underline","MessageEntityUnderline","Strike","MessageEntityStrike","Code","MessageEntityCode","Pre","MessageEntityPre","language","Blockquote","MessageEntityBlockquote","TextUrl","MessageEntityTextUrl","Url","MessageEntityUrl","Hashtag","MessageEntityHashtag","MentionName","InputMessageEntityMentionName","MessageEntityUnknown","calculateResultHash","ids","hash","isMessageWithMedia","MessageMediaWebPage","webpage","WebPage","photo","isServiceMessageWithMedia","action","buildChatPhotoForLocalDb","PhotoEmpty","ChatPhotoEmpty","dcId","photoId","ChatPhoto","buildInputContact","phone","firstName","lastName","InputPhoneContact","clientId","buildChatBannedRights","bannedRights","untilDate","ChatBannedRights","buildChatAdminRights","adminRights","ChatAdminRights","buildShippingInfo","info","shippingAddress","PaymentRequestedInfo","PostAddress","buildInputPrivacyKey","privacyKey","InputPrivacyKeyPhoneNumber","InputPrivacyKeyStatusTimestamp","InputPrivacyKeyProfilePhoto","InputPrivacyKeyForwards","InputPrivacyKeyChatInvite","isPeerUser","peer","isPeerChat","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","String","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","Channel","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","Chat","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","Date","now","getApiChatIdFromMtpPeer","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","omitVirtualClassFields","currentUserBannedRights","defaultBannedRights","ChatForbidden","ChannelForbidden","isRestricted","restrictionReason","restricted","buildApiChatRestrictionReason","isNotJoined","left","kicked","reason","platform","migratedTo","InputChannelEmpty","restrictionReasons","targetReason","find","buildApiChatFromPreview","preview","withForbidden","getUserName","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","UserEmpty","ChatEmpty","megagroup","getPeerKey","buildChatMember","member","ChannelParticipantBanned","ChannelParticipantLeft","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","ChannelParticipantAdmin","ChatParticipantAdmin","isAdmin","ChannelParticipantCreator","ChatParticipantCreator","isOwner","buildChatMembers","participants","ChatParticipants","ChannelParticipants","buildChatTypingStatus","SendMessageCancelAction","SendMessageTypingAction","SendMessageRecordVideoAction","SendMessageUploadVideoAction","SendMessageRecordAudioAction","SendMessageUploadAudioAction","SendMessageUploadPhotoAction","SendMessageUploadDocumentAction","SendMessageGeoLocationAction","SendMessageChooseContactAction","SendMessageGamePlayAction","SendMessageRecordRoundAction","SendMessageUploadRoundAction","UpdateUserTyping","timestamp","buildApiChatFolder","pickTruthy","buildApiChatFolderFromSuggested","description","API_UPDATE_THROTTLE","API_THROTTLE_RESET_UPDATES","Set","MEMBERS_LOAD_SLICE","window","innerHeight","PINNED_MESSAGES_LIMIT","BLOCKED_LIST_LIMIT","PROFILE_PHOTOS_LIMIT","LOCAL_MESSAGE_ID_BASE","MEMOJI_STICKER_ID","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","DELETED_COMMENTS_CHANNEL_ID","DEFAULT_LANG_PACK","localMessages","parseTl","serializeBytes","serializeDate","toSignedLittleBuffer","tlContent","schemeContent","CACHING_SUPPORTED","localStorage","extractParams","fileContent","f","constructors","functions","isFunction","push","argToBytes","x","alloc","writeInt32LE","writeDoubleLE","getBytes","getArgFromReader","reader","arg","isVector","useVectorId","readInt","temp","len","flagIndicator","readLong","readLargeInt","readDouble","tgReadString","tgReadBool","tgReadBytes","tgReadDate","skipConstructorId","tgReadObject","createClasses","classesType","classes","classParams","constructorId","subclassOfId","argsConfig","namespace","fullName","join","VirtualClass","constructor","keys","argName","this","isFlag","flags","flagIndex","idForBytes","CONSTRUCTOR_ID","writeUInt32LE","buffers","concat","values","flagCalculate","boxed","charAt","indexOf","toUpperCase","shift","readResult","definitions","fromCache","jsonCache","getItem","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","requests","loadFromTlSchemas","setItem","obj1","obj2","assign","mergeWithNamespaces","buildApiFromTlSchema","fetchChats","limit","offsetDate","archived","withPinned","GetDialogs","offsetPeer","InputPeerEmpty","excludePinned","resultPinned","GetPinnedDialogs","DialogsNotModified","updateLocalDb","lastMessagesByChatId","buildCollectionByKey","buildApiMessage","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","Dialog","chat","lastMessage","pinned","draft","formattedText","replyingToId","buildMessageDraft","buildApiUser","chatIds","totalChatCount","DialogsSlice","count","fetchFullChat","GetFullChannel","channel","fullChat","ChannelFull","about","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","inviteLink","ChatInviteExported","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","fullInfo","slowMode","seconds","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","GetFullChat","ChatFull","getFullChatInfo","searchChats","query","Search","q","localPeerIds","myResults","allChats","allUsers","isSelf","localChats","localUsers","u","globalChats","globalUsers","fetchChat","mtpUser","GetUsers","help","GetSupport","requestChatUpdate","GetPeerDialogs","peers","InputDialogPeer","saveDraft","replyToMsgId","SaveDraft","clearDraft","updateChatMutedState","account","UpdateNotifySettings","InputNotifyPeer","settings","InputPeerNotifySettings","createChannel","CreateChannel","broadcast","newChannel","InviteToChannel","joinChannel","JoinChannel","leaveChannel","LeaveChannel","deleteChannel","DeleteChannel","createGroupChat","CreateChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","EditPhoto","InputChatUploadedPhoto","EditChatPhoto","toggleChatPinned","shouldBePinned","ToggleDialogPin","isPinned","toggleChatArchived","folders","EditPeerFolders","folderPeers","InputFolderPeer","fetchChatFolders","GetDialogFilters","byId","orderedIds","fetchRecommendedChatFolders","results","GetSuggestedDialogFilters","editChatFolder","folderUpdate","UpdateDialogFilter","deleteChatFolder","isActionSuccessful","recommendedChatFolders","toggleDialogUnread","MarkDialogUnread","unread","getChatByUsername","ResolveUsername","togglePreHistoryHidden","isEnabled","TogglePreHistoryHidden","enabled","updateChatDefaultBannedRights","EditChatDefaultBannedRights","updateChatMemberBannedRights","participant","EditBanned","updateChatAdmin","EditAdmin","updateChatTitle","EditTitle","EditChatTitle","updateChatAbout","EditChatAbout","toggleSignatures","ToggleSignatures","memberFilter","ChannelParticipantsKicked","ChannelParticipantsAdmins","ChannelParticipantsRecent","GetParticipants","ChannelParticipantsNotModified","fetchGroupsForDiscussion","GetGroupsForDiscussion","setDiscussionGroup","SetDiscussionGroup","group","migrateChat","MigrateChat","openChatByInvite","CheckChatInvite","ChatInvite","ImportChatInvite","store","addMessageToLocalDb","crypto","little","signed","randBuffer","bytesNumber","reverse","bigInt","floor","subtract","pow","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","ceil","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","generateRandomLong","mod","crc32","buf","k","makeCRCTable","isBuffer","crc","index","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","all","slice","iv","sha256","bigIntMod","remainder","add","modExp","b","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","max","random","sleep","ms","resolve","setTimeout","getByteArray","integer","bits","byteLength","convertToLittle","correct","writeUInt32BE","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","currentUserId","localMessageCounter","_currentUserId","mtpMessage","resolveMessageApiChatId","MessageService","buildApiMessageWithChatId","buildApiMessageFromShort","out","buildApiMessageFromShortChat","buildApiMessageFromNotification","notification","currentDate","localId","content","buildMessageMediaContent","sticker","contact","buildMessageTextContent","inboxDate","isOutgoing","isChatWithSelf","post","fwdFrom","senderId","isChannelPost","MessageActionEmpty","targetUserId","targetChatId","MessageActionChatCreate","MessageActionChatEditTitle","MessageActionChatEditPhoto","MessageActionChatDeletePhoto","MessageActionChatAddUser","MessageActionChatDeleteUser","MessageActionChatJoinedByLink","MessageActionChannelCreate","MessageActionChatMigrateTo","MessageActionChannelMigrateFrom","MessageActionPinMessage","MessageActionHistoryClear","MessageActionPhoneCall","video","duration","mins","round","MessageActionContactSignUp","MessageActionPaymentSent","currencySign","amount","totalAmount","toFixed","MessageActionGroupCall","addPhotoToLocalDb","buildApiPhoto","buildAction","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","messageId","replyMarkup","ReplyKeyboardMarkup","ReplyInlineMarkup","markup","rows","buttons","button","KeyboardButton","KeyboardButtonUrl","KeyboardButtonCallback","KeyboardButtonRequestPoll","KeyboardButtonBuy","MessageMediaInvoice","receiptMsgId","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","ReplyKeyboardHide","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","DraftMessageEmpty","buildStickerFromDocument","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","attr","DocumentAttributeAudio","voice","fileName","getFilenameFromDocument","buildAudio","waveform","Array","buildVoice","buildApiDocument","buildDocumentFromMedia","MessageMediaContact","buildContact","MessageMediaPoll","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","buildInvoice","buildInvoiceFromMedia","DocumentEmpty","thumbs","videoAttr","DocumentAttributeVideo","gifAttr","DocumentAttributeAnimated","w","width","h","height","supportsStreaming","roundMessage","isRound","isGif","thumbnail","buildApiThumbnailFromStripped","pollResults","rawAnswers","answer","fromCharCode","buildPollResults","rawResults","totalVoters","recentVoters","recentVoterIds","chosen","voters","isChosen","isCorrect","votersCount","sizes","PhotoSize","buildApiPhotoSize","hasDocument","defaultBase","filenameAttribute","DocumentAttributeFilename","extension","split","buildLocalMessage","replyingTo","attachment","gif","scheduledAt","filename","blobUrl","previewBlobUrl","quick","dataUri","inputWaveform","interpolateArray","buildUploadingMedia","isChannel","buildNewPoll","isScheduled","buildForwardedMessage","toChat","isAudio","asIncomingInChatWithSelf","sendingState","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","fetchMessages","pagination","RequestClass","MAIN_THREAD_ID","GetHistory","GetReplies","msgId","MessagesNotModified","threadInfos","fetchMessage","GetMessages","InputMessageID","MessageEmpty","MESSAGE_DELETED","queue","sendMessage","isSilent","noWebPage","localMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","UploadMedia","fileReference","InputMediaPhoto","InputPhoto","fetchInputMedia","InputSingleMedia","multiMedia","scheduleDate","sendGroupedMedia","noWebpage","editMessage","messageUpdate","mtpEntities","EditMessage","rescheduleMessage","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","InputMediaUploadedPhoto","InputMediaUploadedDocument","pinMessage","isUnpin","isOneSide","UpdatePinnedMessage","unpin","pmOneside","unpinAllMessages","UnpinAllMessages","deleteMessages","messageIds","shouldDeleteForAll","DeleteMessages","revoke","deleteScheduledMessages","DeleteScheduledMessages","deleteHistory","DeleteHistory","just_clear","markMessageListRead","ReadHistory","ReadDiscussion","requestThreadInfoUpdate","markMessagesRead","ReadMessageContents","topMessageResult","repliesResult","GetDiscussionMessage","offsetId","addOffset","discussionChatId","topMessageId","ChannelMessages","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","InputMessagesFilterPhotoVideo","InputMessagesFilterDocument","InputMessagesFilterUrl","InputMessagesFilterMusic","InputMessagesFilterVoice","InputMessagesFilterChatPhotos","InputMessagesFilterEmpty","topMsgId","nextOffsetId","totalCount","MessagesSlice","searchMessagesGlobal","offsetRate","SearchGlobal","nextRate","fetchWebPagePreview","GetWebPagePreview","sendPollVote","options","SendVote","loadPollOptionResults","shouldResetVoters","GetPollVotes","votes","vote","nextOffset","forwardMessages","fromChat","randomIds","ForwardMessages","fromPeer","toPeer","findFirstMessageIdAfterDate","fetchScheduledHistory","GetScheduledHistory","sendScheduledMessages","SendScheduledMessages","fetchMessageLink","ExportMessageLink","grouped","thread","fetchPinnedMessages","InputMessagesFilterPinned","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","write","fromString","obj","checked","copy","val","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parseInt","utf8Write","blitBuffer","asciiWrite","str","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","apply","decodeCodePointsArray","SlowBuffer","INSPECT_MAX_BYTES","global","foo","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","y","list","pos","swap16","swap32","swap64","arguments","equals","inspect","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","mtpUserFull","commonChatsCount","pinnedMsgId","botInfo","bio","pinnedMessageId","botDescription","UserProfilePhoto","mutualContact","isContact","buildApiUserType","status","buildApiUserStatus","bot","deleted","mtpStatus","UserStatusEmpty","UserStatusOnline","expires","UserStatusOffline","wasOnline","UserStatusRecently","UserStatusLastWeek","collection","byKey","BASE","MAX_INT","MAX_INT_ARR","smallToArray","supportsNativeBigInt","Integer","v","radix","alphabet","caseSensitive","parseBase","parseValue","BigInteger","sign","isSmall","SmallInteger","NativeBigInt","isPrecise","arrayToSmall","compareAbs","createArray","truncate","sum","l_a","l_b","carry","base","addAny","addSmall","difference","a_l","b_l","borrow","subtractSmall","multiplyLong","product","a_i","multiplySmall","shiftLeft","multiplySmallAndArray","square","divModSmall","lambda","divisor","quotient","divModAny","negate","comparison","quotientDigit","divisorMostSignificantDigit","divMod1","guess","xlen","highx","highy","check","part","unshift","divMod2","qSign","mSign","isBasicPrime","isUnit","isEven","isDivisibleBy","millerRabinTest","nPrev","prev","next","modPow","plus","subtractAny","minus","small","l1","l2","multiplyKaratsuba","ac","bd","abcd","times","_multiplyBySmall","divmod","over","_0","_1","_2","isNegative","exp","isZero","modInv","isPositive","isOdd","compareTo","notEquals","neq","gt","lt","greaterOrEquals","geq","lesserOrEquals","leq","isPrime","strict","logN","toJSNumber","isProbablePrime","iterations","rng","randBetween","lastT","lastR","newT","newR","powersOfTwo","powers2Length","highestPower2","shift_isSmall","bitwise","fn","xSign","ySign","xRem","not","yRem","xDigit","yDigit","xDivMod","yDivMod","remQuo","or","xor","roughLOB","gcd","integerLogarithm","tmp","absBase","alphabetValues","digits","parseBaseFromArray","toBase","valueOf","neg","digit","toBaseString","parseStringValue","decimalPlace","parseNumberValue","toArray","minusOne","lcm","isInstance","usedRNG","low","range","top","fromArray","messageFullId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","buildAuthStateUpdate","isCodeViaApp","hint","token","btoa","FloodWaitError","hours","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","bytesToDataUri","shouldOmitPrefix","instance","SUBCLASS_OF_ID","classType","rest","pathBytesToSvg","path","num","buildPath","DEFAULT_THUMB_SIZE","thumb","PhotoStrippedSize","realSizes","strippedPhotoToJpg","buildApiThumbnailFromCached","photoSize","buildApiThumbnailFromPath","sizeAttribute","PhotoSizeProgressive","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","InputPeerSelf","UserFull","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","ipAddress","port","api","stickerAttribute","DocumentAttributeImageSize","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","PhotoCachedSize","pathThumb","PhotoPathSize","stickerSetId","stickerSetAccessHash","buildStickerSet","animated","installedDate","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","StickerSetMultiCovered","covers","cover","coverSticker","ReadCancelledError","super","TypeNotFoundError","invalidConstructorId","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","SecurityError","BadMessageError","errorMessage","ErrorMessages","16","17","18","19","20","32","33","34","35","48","64","CdnFileTamperedError","buildApiWallpaper","wallpaper","WallPaperNoFile","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyKey","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","PrivacyValueAllowAll","PrivacyValueAllowContacts","PrivacyValueDisallowContacts","PrivacyValueDisallowAll","PrivacyValueAllowUsers","PrivacyValueDisallowUsers","PrivacyValueAllowChatParticipants","PrivacyValueDisallowChatParticipants","coreObjects","tlobjects","stream","_last","readByte","readFloat","getBuffer","padding","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","sentMessageIds","originRequest","disconnected","broken","UpdateNewMessage","UpdateNewScheduledMessage","UpdateNewChannelMessage","UpdateShortChatMessage","UpdateShortMessage","UpdateServiceNotification","has","localDbChatId","newProfilePhoto","UpdateEditMessage","UpdateEditChannelMessage","UpdateDeleteMessages","UpdateDeleteScheduledMessages","UpdateDeleteChannelMessages","existingIds","missingIds","profilePhotoIds","UpdateMessageID","UpdateShortSentMessage","newContent","isAlreadySent","UpdateReadMessagesContents","UpdateChannelReadMessagesContents","UpdateMessagePoll","pollId","apiPoll","pollUpdate","UpdateMessagePollVote","UpdateChannelMessageViews","UpdateReadHistoryInbox","stillUnreadCount","UpdateReadHistoryOutbox","UpdateReadChannelInbox","UpdateReadChannelOutbox","UpdateDialogPinned","DialogPeer","UpdatePinnedDialogs","order","dp","UpdateFolderPeers","folderPeer","UpdateDialogFilterOrder","UpdateChatParticipants","replacedMembers","UpdateChatParticipantAdd","addedMember","UpdateChatParticipantDelete","deletedMemberId","UpdatePinnedMessages","UpdatePinnedChannelMessages","NotifyPeer","showPreviews","sound","shouldShowPreviews","UpdateChatUserTyping","typingStatus","UpdateChannelUserTyping","UpdateChannel","UpdateDialogUnreadMark","UpdateChatDefaultBannedRights","UpdateUserStatus","UpdateUserName","updatedUser","UpdateUserPhoto","UpdateUserPhone","UpdatePeerSettings","peerType","UpdatePeerBlocked","isBlocked","blocked","UpdatePrivacy","UpdateContactsReset","UpdateFavedStickers","Session","_serverAddress","_dcId","_port","_takeoutId","_updateStates","_authKey","setDC","serverAddress","BinaryReader","AuthKey","_key","_hash","auxHash","keyId","getKey","shaData","other","RPCError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","capture","throttle","shouldRunFirst","interval","isPending","_args","setInterval","clearInterval","throttleWithTickEnd","throttleWith","onTickEnd","schedulerFn","waiting","cb","then","pause","checkPrimeAndGood","primeBytes","g","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","computeHash","algo","salt1","salt2","salt","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","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","GZIPPacked","contentRelated","gzipped","toBytes","input","gzip","ungzip","fitCount","peak","newData","springFactor","leftFiller","rightFiller","idx","File","fileBits","FileReader","onload","onerror","readAsDataURL","lastModified","blobToFile","fetchBlob","AES","default","i2ab","ab2i","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","plainText","encrypt","encrypted","Hash","algorithm","subtle","createCipheriv","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","ServerError","TimedOutError","TLMessage","seqNo","MessageContainer","containerLength","before","tlMessage","PromisedWebSockets","AsyncQueue","Connection","ip","loggers","_ip","_log","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","debug","PacketCodecClass","connect","_initConn","_connect","_sendLoop","_recvLoop","pop","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","MemorySession","sessionInfo","_authKeys","_sessionString","_storageKey","_loadFromSessionString","_fetchFromCache","mainDcId","hashes","skipUpdateStorage","_updateStorage","getAuthKey","setAuthKey","authKey","getSessionData","asHex","mainDcIdStr","mainDcKey","setKey","_saveToCache","_delete","1","TYPED_OK","Uint16Array","Int32Array","_has","sources","source","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","chunk","fnUntyped","setTyped","on","Buf8","Buf16","Buf32","2","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","buf2binstring","string2buf","c2","m_pos","str_len","buf_len","binstring2buf","buf2string","c_len","utf16buf","utf8border","3","adler","s1","s2","4","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","5","table","makeTable","6","time","xflags","os","extra","extra_len","comment","hcrc","done","7","strm","_in","last","_out","beg","dmax","wsize","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","dist","from_source","output","next_in","avail_in","next_out","avail_out","lencode","distcode","lenbits","distbits","dolen","msg","dodist","sane","8","adler32","inflate_fast","inflate_table","zswap32","InflateState","wrap","havedict","total","head","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","inflateReset","inflateReset2","windowBits","inflateInit2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","flush","here_bits","here_op","here_val","last_bits","last_op","last_val","opts","hbuf","inf_leave","data_type","inflateEnd","inflateGetHeader","inflateSetDictionary","dictionary","dictLength","inflateInfo","9","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","mask","root","curr","drop","used","huff","base_index","MAXBITS","offs","extra_index","10","0","11","zlib_inflate","strings","ZStream","GZheader","Inflate","chunkSize","opt","raw","ended","inflator","_mode","next_out_utf8","tail","utf8str","allowBufError","onEnd","onData","inflateRaw","Logger","BinaryWriter","MessagePacker","Function","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","layer","methods","ignoreIds","objAll","objByName","objByType","commentIndex","followingTypes","dt","getTime","Si","T1","Uint32Array","T2","T3","T4","T5","T6","T7","T8","right","x2","x4","tEnc","tDec","xInv","computeTables","encKey","decKey","rcon","_message","a2","b2","rounds","decrypt","AES_IGE","blockSize","cipher","cipherText","prevX","prevY","yXOR","AES_IGE$1","incrementCounter","_level","level","isBrowser","browser","__nwjs","colors","messageFormat","canSend","levels","format","toISOString","color","UserMigrateError","newDc","PhoneMigrateError","SlowModeWaitError","FloodTestPhoneWaitError","FileMigrateError","NetworkMigrateError","EmailUnconfirmedError","codeLength","LAYER","MtProtoPlainSender","MTProtoState","Helpers","doAuthentication","RPCResult","RequestState","MsgsAck","upload","MsgsStateInfo","Pong","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","MTProtoSender","DEFAULT_OPTIONS","_connection","logger","_retries","retries","_delay","delay","_autoReconnect","autoReconnect","_connectTimeout","connectTimeout","_authKeyCallback","authKeyCallback","_updateCallback","updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","isMainSender","_onConnectionBreak","onConnectionBreak","_user_connected","_reconnecting","_disconnected","_send_loop_handle","_recv_loop_handle","_state","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","attempt","_disconnect","send","append","promise","plain","time_offset","timeOffset","rejectAll","ack","msgIds","batch","encryptMessageData","body","recv","reconnect","decryptMessageData","_processMessage","handler","_handleUpdate","_popStates","toPop","containerId","reqMsgId","innerMessage","pong","badSalt","badMsgId","newServerSalt","states","extend","badMsg","errorCode","updateTimeOffset","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","_getNewMsgId","IGE","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","afterId","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","encryptIge","decryptIge","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","correctMsgId","bad","old","AESIGE","ige","RpcError","innerCode","Factorizator","RSA","sender","nonce","resPQ","ReqPqMulti","ResPQ","pq","factorize","pqInnerData","PQInnerData","targetFingerprint","fingerprint","serverPublicKeyFingerprints","serverDhParams","ReqDHParams","publicKeyFingerprint","encryptedData","ServerDHParamsOk","ServerDHParamsFail","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","ServerDHInnerData","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","ClientDHInnerData","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","SetClientDHParams","nonceTypes","DhGenOk","DhGenRetry","DhGenFail","nonceNumber","calcNewNonceHash","_queue","_pendingStates","_ready","setReady","catch","finally","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","after","writeDataAsMessage","getValue","requestState","_stream","MTProtoPlainSender","ConnectionTCPFull","ConnectionTCPAbridged","ConnectionTCPObfuscated","Mutex","mutex","WebSocketClient","w3cwebsocket","closeError","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","addEventListener","onmessage","release","acquire","canGet","resolveGet","canPush","resolvePush","returned","AbridgedPacketCodec","props","obfuscateTag","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","keywords","ok","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","answerCallbackButton","GetBotCallbackAnswer","b64","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","webpackPolyfill","deprecate","paths","children","i2abLow","int","i2abBig","ab2iLow","ab","ab2iBig","isBigEndian","s2i","authFlow","checkAuthorization","downloadFile","sizeTypes","apiId","apiHash","_useIPV6","useIPV6","baseLogger","floodSleepLimit","_eventBuilders","_phoneCodeHash","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_floodWaitedRequests","_initWith","InvokeWithLayer","InitConnection","systemVersion","langCode","langPack","systemLangCode","_config","phoneCodeHashes","_borrowedSenderPromises","_additionalDcsDisabled","_initSession","_sender","GetConfig","_updateLoop","load","attempts","Ping","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","race","_lastRequest","GetState","DC","_cleanupBorrowedSender","_borrowExportedSender","senderPromise","_createExportedSender","dc","ExportAuthorization","req","ImportAuthorization","inputLocation","messageOrMedia","_downloadPhoto","_downloadDocument","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoSizeEmpty","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","_switchDC","authParams","apiCredentials","fileParams","callback","event","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","sequentialUpdates","endianness","hostname","location","loadavg","uptime","freemem","MAX_VALUE","totalmem","cpus","networkInterfaces","getNetworkInterfaces","arch","tmpdir","tmpDir","EOL","homedir","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","ys","condition","PUBLIC_KEYS","_serverKeys","keyInfo","rand","toEncrypt","Mutex_1","_pending","isLocked","_this","ticket","_dispatchNext","runExclusive","NativeWebSocket","_global","WebSocket","MozWebSocket","websocket_version","W3CWebSocket","uri","protocols","prop","me","signInUser","botAuthToken","ImportBotAuthorization","signInBot","phoneCodeHash","signInUserWithQrCode","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","SignIn","AuthorizationSignUpRequired","signInWithPassword","SignUp","AcceptTermsOfService","isScanningComplete","inputPromise","ExportLoginToken","exceptIds","LoginToken","updatePromise","UpdateLoginToken","result2","LoginTokenSuccess","authorization","Authorization","LoginTokenMigrateTo","migratedResult","ImportLoginToken","sendResult","SendCode","CodeSettings","SentCodeTypeSms","SentCodeTypeApp","resendResult","ResendCode","passwordSrpResult","GetPassword","passwordSrpCheck","computePasswordSrpCheck","CheckPassword","Foreman","maxWorkers","requestWorker","activeWorkers","deferred","_resolve","createDeferred","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","GetFile","precise","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","SaveBigFilePart","filePart","fileTotalParts","SaveFilePart","InputFileBig","InputFile","md5Checksum","isCheckPassword","currentPassword","newPassword","email","emailCodeCallback","onEmailCodeError","pwd","newAlgo","PasswordKdfAlgoUnknown","hasPassword","InputCheckPasswordEmpty","UpdatePasswordSettings","newSettings","PasswordInputSettings","newPasswordHash","newSecureSettings","ConfirmPasswordEmail","NewMessage","Raw","StopPropagation","EventBuilder","types","func","blacklistChats","resolved","Memory","StringSession","CacheApiSession","LocalStorageSession","IdbSession","decode","serverAddressLen","dcBuffer","addressBuffer","addressLengthBuffer","portBuffer","encode","StorageSession","cached","removeItem","idb","del","promisifyRequest","oncomplete","onsuccess","onabort","createStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","defaultGetStoreFunc","defaultGetStore","customStore","setMany","entries","entry","getMany","eachCursor","openCursor","continue","items","cursor","_sessionData","_callback","skipOnUpdate","fetchFullUser","userWithFullInfo","fetchNearestCountry","dcInfo","GetNearestDc","country","fetchTopUsers","topPeers","GetTopPeers","correspondents","TopPeers","fetchContactList","GetContacts","ContactsNotModified","savedCount","fetchUsers","updateContact","ImportContacts","deleteUser","DeleteContacts","fetchProfilePhotos","GetUserPhotos","inputGifBot","fetchStickerSets","allStickers","GetAllStickers","AllStickersNotModified","sets","fetchRecentStickers","GetRecentStickers","RecentStickersNotModified","stickers","processStickerResult","fetchFavoriteStickers","GetFavedStickers","FavedStickersNotModified","fetchFeaturedStickers","GetFeaturedStickers","FeaturedStickersNotModified","faveSticker","unfave","FaveSticker","fetchStickers","GetStickerSet","packs","acc","documentId","fetchAnimatedEmojis","InputStickerSetAnimatedEmoji","searchStickers","SearchStickerSets","FoundStickerSetsNotModified","fetchSavedGifs","GetSavedGifs","SavedGifsNotModified","gifs","processGifResult","installStickerSet","InstallStickerSet","uninstallStickerSet","UninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","GetInlineBotResults","foundGif","BotInlineMediaResult","fetchStickersForEmoji","GetStickers","StickersNotModified","fetchEmojiKeywords","fromVersion","GetEmojiKeywordsDifference","emojiKeyword","keyword","emoticons","checkChatUsername","CheckUsername","setChatUsername","UpdateUsername","updatePrivateLink","ExportChatInvite","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","onRequestEmailCode","checkPassword","clearPassword","updatePassword","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","UpdateProfile","checkUsername","updateUsername","updateProfilePhoto","UploadProfilePhoto","uploadProfilePhoto","fetchWallpapers","GetWallPapers","WallPapersNotModified","filteredWallpapers","wallpapers","WallPaper","pattern","uploadWallpaper","UploadWallPaper","WallPaperSettings","fetchBlockedContacts","GetBlocked","blockedIds","BlockedSlice","blockContact","Block","unblockContact","Unblock","fetchAuthorizations","GetAuthorizations","authorizations","terminateAuthorization","ResetAuthorization","terminateAllAuthorizations","ResetAuthorizations","fetchNotificationExceptions","GetNotifyExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","GetContactSignUpNotification","GetNotifySettings","InputNotifyUsers","InputNotifyChats","InputNotifyBroadcasts","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","SetContactSignUpNotification","updateNotificationSettings","fetchLanguages","langpack","GetLanguages","fetchLangPack","sourceLangPacks","collections","GetLangPack","fetchPrivacySettings","GetPrivacy","registerDevice","secret","RegisterDevice","tokenType","appSandbox","otherUids","unregisterDevice","UnregisterDevice","setPrivacySettings","privacyRules","allowedUsers","InputPrivacyValueAllowUsers","allowedChats","InputPrivacyValueAllowChatParticipants","blockedUsers","InputPrivacyValueDisallowUsers","blockedChats","InputPrivacyValueDisallowChatParticipants","InputPrivacyValueAllowAll","InputPrivacyValueAllowContacts","InputPrivacyValueDisallowContacts","InputPrivacyValueDisallowAll","SetPrivacy","buildShippingOptions","shippingOptions","prices","cur","label","validateRequestedInfo","requestInfo","shouldSave","payments","ValidateRequestedInfo","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","SendPaymentForm","InputPaymentCredentials","DataJSON","getPaymentForm","GetPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","GetPaymentReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initClient","flushUpdatesOnTickEnd","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","sendToOrigin","callbackState","Map","postMessage","callbackArgs","lastArg","fnName","callApi"],"mappings":";aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,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D,EAAK63B,WACpCysD,IACgBA,EDvCPrgD,YAAa,GC0C1B","file":"7c2292f972e10d28cc51.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 111);\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","// 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(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\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 const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet';\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number;\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) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n) {\n // eslint-disable-next-line max-len\n const mediaMatch = url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let 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.Document | GramJs.StickerSet | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (['msg', 'sticker', 'gif', 'wallpaper', 'photo'].includes(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 } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n 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.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\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 ApiMediaFormat, ApiOnProgress, ApiSessionData, 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';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\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, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n client = new TelegramClient(\n new sessions.CallbackSession(sessionData, onSessionUpdate),\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || DEFAULT_USER_AGENT,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\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\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\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 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 }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates = typeof result & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in result && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(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: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\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 buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\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: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\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 && media.webpage.photo instanceof GramJs.Photo\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function 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","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isInputPeerChannel, isInputPeerChat, isInputPeerUser, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\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 ...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: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\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 if (peerEntity instanceof GramJs.User) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason === undefined) {\n return {\n isRestricted: false,\n };\n }\n\n return {\n isRestricted: peerEntity.restricted,\n restrictionReason,\n };\n } else if (peerEntity instanceof GramJs.Chat) {\n return {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n };\n } else if (peerEntity instanceof GramJs.Channel) {\n const isRestricted = peerEntity.restricted\n && peerEntity.restrictionReason\n && peerEntity.restrictionReason.some((reason) => reason.platform === 'all');\n\n return {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n isRestricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n }\n return {};\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\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: peerEntity.migratedTo.accessHash.toString(),\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: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\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 photo.photoId.toString();\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 : member.userId;\n\n return {\n userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : 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) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now(),\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(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).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","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 500;\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;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\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;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { 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}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n} as LocalDb;\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","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\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}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\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 updateLocalDb(result);\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n\n const lastMessagesByChatId = buildCollectionByKey(\n [...result.messages, ...(resultPinned ? resultPinned.messages : [])]\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...preparePeers(result),\n ...(resultPinned && preparePeers(resultPinned)),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = [\n ...(resultPinned ? resultPinned.dialogs : []),\n ...result.dialogs,\n ];\n\n const orderedPinnedIds: number[] = [];\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);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = [...result.users, ...(resultPinned ? resultPinned.users : [])]\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = [...result.chats, ...result.users]\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate(chat: ApiChat) {\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 lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity),\n 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: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\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 } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n } = 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\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: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? call.id.toString() : undefined,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted,\n}: {\n chat: ApiChat; isMuted: boolean;\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 : undefined }),\n }));\n\n void requestChatUpdate(chat);\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; 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: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\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: number; 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 number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights }) {\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),\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 number,\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: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n if (result instanceof GramJs.ChatInvite) {\n await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n\n return undefined;\n } else {\n return buildApiChatFromPreview(result.chat);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\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","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 {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 * 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\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\n};\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\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 ApiKeyboardButtons,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped, buildApiPhotoSize } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { getCurrencySign } from '../../../components/middle/helpers/getCurrencySign';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || (currentDate / 1000),\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action && buildAction(mtpMessage.action, fromId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const { inlineButtons, keyboardButtons } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty || !draft.message) {\n return undefined;\n }\n\n return {\n formattedText: buildMessageTextContent(draft.message, draft.entities),\n replyingToId: draft.replyToMsgId,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n 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 if (media.ttlSeconds) {\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 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 return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\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,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\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\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\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 const currencySign = getCurrencySign(currency);\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n description: `${currencySign}${(Number(totalAmount) / 100).toFixed(2)} ${test ? 'TEST INVOICE' : ''}`,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\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 return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'siteName',\n 'title',\n 'description',\n ]),\n photo: photo && photo instanceof GramJs.Photo\n ? {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes: photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize),\n }\n : undefined,\n // TODO support video and embed\n ...(document && { hasDocument: true }),\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let text = '';\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserId = 'users' in action\n // Api returns array of userIds, but no action currently has multiple users in it\n ? action.users && action.users[0]\n : ('userId' in action && action.userId) || undefined;\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = `%action_origin% created the group «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n text = isChannelPost\n ? `Channel renamed to «${action.title}»`\n : `%action_origin% changed group name to «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n text = isChannelPost\n ? 'Channel photo updated'\n : '%action_origin% updated group photo';\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n text = isChannelPost\n ? 'Channel photo was deleted'\n : 'Chat photo was deleted';\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% joined the group'\n : '%action_origin% added %target_user% to the group';\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% left the group'\n : '%action_origin% removed %target_user% from the group';\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = '%action_origin% joined the chat from invitation link';\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Channel created';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n text = 'Migrated to %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n text = 'Migrated from %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = '%action_origin% pinned %message%';\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'Chat history was cleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n text = `${isOutgoing ? 'Outgoing' : 'Incoming'} ${action.video ? 'Video' : 'Phone'} Call`;\n\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text += ` (${mins} min${mins > 1 ? 's' : ''})`;\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = '%action_origin% joined Telegram';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n const currencySign = getCurrencySign(action.currency);\n const amount = (Number(action.totalAmount) / 100).toFixed(2);\n text = `You successfully transferred ${currencySign}${amount} to shop for %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 = `Voice chat ended (${mins} min${mins > 1 ? 's' : ''})`;\n } else {\n text = 'Voice chat started';\n }\n } else {\n text = '%ACTION_NOT_IMPLEMENTED%';\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 targetUserId,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons\n} | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'Receipt';\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 { [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000),\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\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: Math.round(Date.now() / 1000),\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\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_IMAGE_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_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\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","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const 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 );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\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[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n}) {\n const isScheduled = message.date * 1000 > Date.now();\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 (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\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 }));\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 markMessageListRead({\n chat, threadId, maxId,\n}: {\n chat: ApiChat; threadId: number; maxId?: 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);\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;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\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\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': '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 }), 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, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\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 hash: calculateResultHash(messages.map((message) => message.id)),\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\nexport function fetchMessageLink({ chat, message }: { chat: ApiChat; message: ApiMessage }) {\n return invokeRequest(new GramJs.channels.ExportMessageLink({\n id: message.id,\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n ...(message.isInAlbum && { grouped: true }),\n ...(message.threadInfo && message.threadInfo.topMessageId !== message.id && { thread: true }),\n }));\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiUser, ApiUserStatus, ApiUserType } from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo,\n } = mtpUserFull;\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n ...(botInfo && { botDescription: botInfo.description }),\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\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: buildApiUserType(mtpUser),\n ...(firstName && { firstName }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n };\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","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","var bigInt = (function (undefined) {\r\n \"use strict\";\r\n\r\n var BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_INT = 9007199254740992,\r\n MAX_INT_ARR = smallToArray(MAX_INT),\r\n DEFAULT_ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\";\r\n\r\n var supportsNativeBigInt = typeof BigInt === \"function\";\r\n\r\n function Integer(v, radix, alphabet, caseSensitive) {\r\n if (typeof v === \"undefined\") return Integer[0];\r\n if (typeof radix !== \"undefined\") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);\r\n return parseValue(v);\r\n }\r\n\r\n function BigInteger(value, sign) {\r\n this.value = value;\r\n this.sign = sign;\r\n this.isSmall = false;\r\n }\r\n BigInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function SmallInteger(value) {\r\n this.value = value;\r\n this.sign = value < 0;\r\n this.isSmall = true;\r\n }\r\n SmallInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function NativeBigInt(value) {\r\n this.value = value;\r\n }\r\n NativeBigInt.prototype = Object.create(Integer.prototype);\r\n\r\n function isPrecise(n) {\r\n return -MAX_INT < n && n < MAX_INT;\r\n }\r\n\r\n function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes\r\n if (n < 1e7)\r\n return [n];\r\n if (n < 1e14)\r\n return [n % 1e7, Math.floor(n / 1e7)];\r\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\r\n }\r\n\r\n function arrayToSmall(arr) { // If BASE changes this function may need to change\r\n trim(arr);\r\n var length = arr.length;\r\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\r\n switch (length) {\r\n case 0: return 0;\r\n case 1: return arr[0];\r\n case 2: return arr[0] + arr[1] * BASE;\r\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\r\n }\r\n }\r\n return arr;\r\n }\r\n\r\n function trim(v) {\r\n var i = v.length;\r\n while (v[--i] === 0);\r\n v.length = i + 1;\r\n }\r\n\r\n function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\r\n var x = new Array(length);\r\n var i = -1;\r\n while (++i < length) {\r\n x[i] = 0;\r\n }\r\n return x;\r\n }\r\n\r\n function truncate(n) {\r\n if (n > 0) return Math.floor(n);\r\n return Math.ceil(n);\r\n }\r\n\r\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\r\n var l_a = a.length,\r\n l_b = b.length,\r\n r = new Array(l_a),\r\n carry = 0,\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l_b; i++) {\r\n sum = a[i] + b[i] + carry;\r\n carry = sum >= base ? 1 : 0;\r\n r[i] = sum - carry * base;\r\n }\r\n while (i < l_a) {\r\n sum = a[i] + carry;\r\n carry = sum === base ? 1 : 0;\r\n r[i++] = sum - carry * base;\r\n }\r\n if (carry > 0) r.push(carry);\r\n return r;\r\n }\r\n\r\n function addAny(a, b) {\r\n if (a.length >= b.length) return add(a, b);\r\n return add(b, a);\r\n }\r\n\r\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l; i++) {\r\n sum = a[i] - base + carry;\r\n carry = Math.floor(sum / base);\r\n r[i] = sum - carry * base;\r\n carry += 1;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall) {\r\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\r\n }\r\n return new BigInteger(addAny(a, b), this.sign);\r\n };\r\n BigInteger.prototype.plus = BigInteger.prototype.add;\r\n\r\n SmallInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n if (isPrecise(a + b)) return new SmallInteger(a + b);\r\n b = smallToArray(Math.abs(b));\r\n }\r\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\r\n };\r\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\r\n\r\n NativeBigInt.prototype.add = function (v) {\r\n return new NativeBigInt(this.value + parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\r\n\r\n function subtract(a, b) { // assumes a and b are arrays with a >= b\r\n var a_l = a.length,\r\n b_l = b.length,\r\n r = new Array(a_l),\r\n borrow = 0,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < b_l; i++) {\r\n difference = a[i] - borrow - b[i];\r\n if (difference < 0) {\r\n difference += base;\r\n borrow = 1;\r\n } else borrow = 0;\r\n r[i] = difference;\r\n }\r\n for (i = b_l; i < a_l; i++) {\r\n difference = a[i] - borrow;\r\n if (difference < 0) difference += base;\r\n else {\r\n r[i++] = difference;\r\n break;\r\n }\r\n r[i] = difference;\r\n }\r\n for (; i < a_l; i++) {\r\n r[i] = a[i];\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function subtractAny(a, b, sign) {\r\n var value;\r\n if (compareAbs(a, b) >= 0) {\r\n value = subtract(a, b);\r\n } else {\r\n value = subtract(b, a);\r\n sign = !sign;\r\n }\r\n value = arrayToSmall(value);\r\n if (typeof value === \"number\") {\r\n if (sign) value = -value;\r\n return new SmallInteger(value);\r\n }\r\n return new BigInteger(value, sign);\r\n }\r\n\r\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n carry = -b,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < l; i++) {\r\n difference = a[i] + carry;\r\n carry = Math.floor(difference / base);\r\n difference %= base;\r\n r[i] = difference < 0 ? difference + base : difference;\r\n }\r\n r = arrayToSmall(r);\r\n if (typeof r === \"number\") {\r\n if (sign) r = -r;\r\n return new SmallInteger(r);\r\n } return new BigInteger(r, sign);\r\n }\r\n\r\n BigInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall)\r\n return subtractSmall(a, Math.abs(b), this.sign);\r\n return subtractAny(a, b, this.sign);\r\n };\r\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\r\n\r\n SmallInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n return new SmallInteger(a - b);\r\n }\r\n return subtractSmall(b, Math.abs(a), a >= 0);\r\n };\r\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\r\n\r\n NativeBigInt.prototype.subtract = function (v) {\r\n return new NativeBigInt(this.value - parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\r\n\r\n BigInteger.prototype.negate = function () {\r\n return new BigInteger(this.value, !this.sign);\r\n };\r\n SmallInteger.prototype.negate = function () {\r\n var sign = this.sign;\r\n var small = new SmallInteger(-this.value);\r\n small.sign = !sign;\r\n return small;\r\n };\r\n NativeBigInt.prototype.negate = function () {\r\n return new NativeBigInt(-this.value);\r\n }\r\n\r\n BigInteger.prototype.abs = function () {\r\n return new BigInteger(this.value, false);\r\n };\r\n SmallInteger.prototype.abs = function () {\r\n return new SmallInteger(Math.abs(this.value));\r\n };\r\n NativeBigInt.prototype.abs = function () {\r\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\r\n }\r\n\r\n\r\n function multiplyLong(a, b) {\r\n var a_l = a.length,\r\n b_l = b.length,\r\n l = a_l + b_l,\r\n r = createArray(l),\r\n base = BASE,\r\n product, carry, i, a_i, b_j;\r\n for (i = 0; i < a_l; ++i) {\r\n a_i = a[i];\r\n for (var j = 0; j < b_l; ++j) {\r\n b_j = b[j];\r\n product = a_i * b_j + r[i + j];\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n r[i + j + 1] += carry;\r\n }\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n carry = 0,\r\n product, i;\r\n for (i = 0; i < l; i++) {\r\n product = a[i] * b + carry;\r\n carry = Math.floor(product / base);\r\n r[i] = product - carry * base;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n function shiftLeft(x, n) {\r\n var r = [];\r\n while (n-- > 0) r.push(0);\r\n return r.concat(x);\r\n }\r\n\r\n function multiplyKaratsuba(x, y) {\r\n var n = Math.max(x.length, y.length);\r\n\r\n if (n <= 30) return multiplyLong(x, y);\r\n n = Math.ceil(n / 2);\r\n\r\n var b = x.slice(n),\r\n a = x.slice(0, n),\r\n d = y.slice(n),\r\n c = y.slice(0, n);\r\n\r\n var ac = multiplyKaratsuba(a, c),\r\n bd = multiplyKaratsuba(b, d),\r\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\r\n\r\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\r\n trim(product);\r\n return product;\r\n }\r\n\r\n // The following function is derived from a surface fit of a graph plotting the performance difference\r\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\r\n function useKaratsuba(l1, l2) {\r\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\r\n }\r\n\r\n BigInteger.prototype.multiply = function (v) {\r\n var n = parseValue(v),\r\n a = this.value, b = n.value,\r\n sign = this.sign !== n.sign,\r\n abs;\r\n if (n.isSmall) {\r\n if (b === 0) return Integer[0];\r\n if (b === 1) return this;\r\n if (b === -1) return this.negate();\r\n abs = Math.abs(b);\r\n if (abs < BASE) {\r\n return new BigInteger(multiplySmall(a, abs), sign);\r\n }\r\n b = smallToArray(abs);\r\n }\r\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\r\n return new BigInteger(multiplyKaratsuba(a, b), sign);\r\n return new BigInteger(multiplyLong(a, b), sign);\r\n };\r\n\r\n BigInteger.prototype.times = BigInteger.prototype.multiply;\r\n\r\n function multiplySmallAndArray(a, b, sign) { // a >= 0\r\n if (a < BASE) {\r\n return new BigInteger(multiplySmall(b, a), sign);\r\n }\r\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\r\n }\r\n SmallInteger.prototype._multiplyBySmall = function (a) {\r\n if (isPrecise(a.value * this.value)) {\r\n return new SmallInteger(a.value * this.value);\r\n }\r\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\r\n };\r\n BigInteger.prototype._multiplyBySmall = function (a) {\r\n if (a.value === 0) return Integer[0];\r\n if (a.value === 1) return this;\r\n if (a.value === -1) return this.negate();\r\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\r\n };\r\n SmallInteger.prototype.multiply = function (v) {\r\n return parseValue(v)._multiplyBySmall(this);\r\n };\r\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\r\n\r\n NativeBigInt.prototype.multiply = function (v) {\r\n return new NativeBigInt(this.value * parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\r\n\r\n function square(a) {\r\n //console.assert(2 * BASE * BASE < MAX_INT);\r\n var l = a.length,\r\n r = createArray(l + l),\r\n base = BASE,\r\n product, carry, i, a_i, a_j;\r\n for (i = 0; i < l; i++) {\r\n a_i = a[i];\r\n carry = 0 - a_i * a_i;\r\n for (var j = i; j < l; j++) {\r\n a_j = a[j];\r\n product = 2 * (a_i * a_j) + r[i + j] + carry;\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n }\r\n r[i + l] = carry;\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.square = function () {\r\n return new BigInteger(square(this.value), false);\r\n };\r\n\r\n SmallInteger.prototype.square = function () {\r\n var value = this.value * this.value;\r\n if (isPrecise(value)) return new SmallInteger(value);\r\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\r\n };\r\n\r\n NativeBigInt.prototype.square = function (v) {\r\n return new NativeBigInt(this.value * this.value);\r\n }\r\n\r\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n base = BASE,\r\n result = createArray(b.length),\r\n divisorMostSignificantDigit = b[b_l - 1],\r\n // normalization\r\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\r\n remainder = multiplySmall(a, lambda),\r\n divisor = multiplySmall(b, lambda),\r\n quotientDigit, shift, carry, borrow, i, l, q;\r\n if (remainder.length <= a_l) remainder.push(0);\r\n divisor.push(0);\r\n divisorMostSignificantDigit = divisor[b_l - 1];\r\n for (shift = a_l - b_l; shift >= 0; shift--) {\r\n quotientDigit = base - 1;\r\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\r\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\r\n }\r\n // quotientDigit <= base - 1\r\n carry = 0;\r\n borrow = 0;\r\n l = divisor.length;\r\n for (i = 0; i < l; i++) {\r\n carry += quotientDigit * divisor[i];\r\n q = Math.floor(carry / base);\r\n borrow += remainder[shift + i] - (carry - q * base);\r\n carry = q;\r\n if (borrow < 0) {\r\n remainder[shift + i] = borrow + base;\r\n borrow = -1;\r\n } else {\r\n remainder[shift + i] = borrow;\r\n borrow = 0;\r\n }\r\n }\r\n while (borrow !== 0) {\r\n quotientDigit -= 1;\r\n carry = 0;\r\n for (i = 0; i < l; i++) {\r\n carry += remainder[shift + i] - base + divisor[i];\r\n if (carry < 0) {\r\n remainder[shift + i] = carry + base;\r\n carry = 0;\r\n } else {\r\n remainder[shift + i] = carry;\r\n carry = 1;\r\n }\r\n }\r\n borrow += carry;\r\n }\r\n result[shift] = quotientDigit;\r\n }\r\n // denormalization\r\n remainder = divModSmall(remainder, lambda)[0];\r\n return [arrayToSmall(result), arrayToSmall(remainder)];\r\n }\r\n\r\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\r\n // Performs faster than divMod1 on larger input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n result = [],\r\n part = [],\r\n base = BASE,\r\n guess, xlen, highx, highy, check;\r\n while (a_l) {\r\n part.unshift(a[--a_l]);\r\n trim(part);\r\n if (compareAbs(part, b) < 0) {\r\n result.push(0);\r\n continue;\r\n }\r\n xlen = part.length;\r\n highx = part[xlen - 1] * base + part[xlen - 2];\r\n highy = b[b_l - 1] * base + b[b_l - 2];\r\n if (xlen > b_l) {\r\n highx = (highx + 1) * base;\r\n }\r\n guess = Math.ceil(highx / highy);\r\n do {\r\n check = multiplySmall(b, guess);\r\n if (compareAbs(check, part) <= 0) break;\r\n guess--;\r\n } while (guess);\r\n result.push(guess);\r\n part = subtract(part, check);\r\n }\r\n result.reverse();\r\n return [arrayToSmall(result), arrayToSmall(part)];\r\n }\r\n\r\n function divModSmall(value, lambda) {\r\n var length = value.length,\r\n quotient = createArray(length),\r\n base = BASE,\r\n i, q, remainder, divisor;\r\n remainder = 0;\r\n for (i = length - 1; i >= 0; --i) {\r\n divisor = remainder * base + value[i];\r\n q = truncate(divisor / lambda);\r\n remainder = divisor - q * lambda;\r\n quotient[i] = q | 0;\r\n }\r\n return [quotient, remainder | 0];\r\n }\r\n\r\n function divModAny(self, v) {\r\n var value, n = parseValue(v);\r\n if (supportsNativeBigInt) {\r\n return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];\r\n }\r\n var a = self.value, b = n.value;\r\n var quotient;\r\n if (b === 0) throw new Error(\"Cannot divide by zero\");\r\n if (self.isSmall) {\r\n if (n.isSmall) {\r\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\r\n }\r\n return [Integer[0], self];\r\n }\r\n if (n.isSmall) {\r\n if (b === 1) return [self, Integer[0]];\r\n if (b == -1) return [self.negate(), Integer[0]];\r\n var abs = Math.abs(b);\r\n if (abs < BASE) {\r\n value = divModSmall(a, abs);\r\n quotient = arrayToSmall(value[0]);\r\n var remainder = value[1];\r\n if (self.sign) remainder = -remainder;\r\n if (typeof quotient === \"number\") {\r\n if (self.sign !== n.sign) quotient = -quotient;\r\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\r\n }\r\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\r\n }\r\n b = smallToArray(abs);\r\n }\r\n var comparison = compareAbs(a, b);\r\n if (comparison === -1) return [Integer[0], self];\r\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\r\n\r\n // divMod1 is faster on smaller input sizes\r\n if (a.length + b.length <= 200)\r\n value = divMod1(a, b);\r\n else value = divMod2(a, b);\r\n\r\n quotient = value[0];\r\n var qSign = self.sign !== n.sign,\r\n mod = value[1],\r\n mSign = self.sign;\r\n if (typeof quotient === \"number\") {\r\n if (qSign) quotient = -quotient;\r\n quotient = new SmallInteger(quotient);\r\n } else quotient = new BigInteger(quotient, qSign);\r\n if (typeof mod === \"number\") {\r\n if (mSign) mod = -mod;\r\n mod = new SmallInteger(mod);\r\n } else mod = new BigInteger(mod, mSign);\r\n return [quotient, mod];\r\n }\r\n\r\n BigInteger.prototype.divmod = function (v) {\r\n var result = divModAny(this, v);\r\n return {\r\n quotient: result[0],\r\n remainder: result[1]\r\n };\r\n };\r\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\r\n\r\n\r\n BigInteger.prototype.divide = function (v) {\r\n return divModAny(this, v)[0];\r\n };\r\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {\r\n return new NativeBigInt(this.value / parseValue(v).value);\r\n };\r\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\r\n\r\n BigInteger.prototype.mod = function (v) {\r\n return divModAny(this, v)[1];\r\n };\r\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {\r\n return new NativeBigInt(this.value % parseValue(v).value);\r\n };\r\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\r\n\r\n BigInteger.prototype.pow = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value,\r\n value, x, y;\r\n if (b === 0) return Integer[1];\r\n if (a === 0) return Integer[0];\r\n if (a === 1) return Integer[1];\r\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.sign) {\r\n return Integer[0];\r\n }\r\n if (!n.isSmall) throw new Error(\"The exponent \" + n.toString() + \" is too large.\");\r\n if (this.isSmall) {\r\n if (isPrecise(value = Math.pow(a, b)))\r\n return new SmallInteger(truncate(value));\r\n }\r\n x = this;\r\n y = Integer[1];\r\n while (true) {\r\n if (b & 1 === 1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === 0) break;\r\n b /= 2;\r\n x = x.square();\r\n }\r\n return y;\r\n };\r\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\r\n\r\n NativeBigInt.prototype.pow = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value, b = n.value;\r\n var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);\r\n if (b === _0) return Integer[1];\r\n if (a === _0) return Integer[0];\r\n if (a === _1) return Integer[1];\r\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.isNegative()) return new NativeBigInt(_0);\r\n var x = this;\r\n var y = Integer[1];\r\n while (true) {\r\n if ((b & _1) === _1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === _0) break;\r\n b /= _2;\r\n x = x.square();\r\n }\r\n return y;\r\n }\r\n\r\n BigInteger.prototype.modPow = function (exp, mod) {\r\n exp = parseValue(exp);\r\n mod = parseValue(mod);\r\n if (mod.isZero()) throw new Error(\"Cannot take modPow with modulus 0\");\r\n var r = Integer[1],\r\n base = this.mod(mod);\r\n if (exp.isNegative()) {\r\n exp = exp.multiply(Integer[-1]);\r\n base = base.modInv(mod);\r\n }\r\n while (exp.isPositive()) {\r\n if (base.isZero()) return Integer[0];\r\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\r\n exp = exp.divide(2);\r\n base = base.square().mod(mod);\r\n }\r\n return r;\r\n };\r\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\r\n\r\n function compareAbs(a, b) {\r\n if (a.length !== b.length) {\r\n return a.length > b.length ? 1 : -1;\r\n }\r\n for (var i = a.length - 1; i >= 0; i--) {\r\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\r\n }\r\n return 0;\r\n }\r\n\r\n BigInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) return 1;\r\n return compareAbs(a, b);\r\n };\r\n SmallInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = Math.abs(this.value),\r\n b = n.value;\r\n if (n.isSmall) {\r\n b = Math.abs(b);\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n return -1;\r\n };\r\n NativeBigInt.prototype.compareAbs = function (v) {\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n a = a >= 0 ? a : -a;\r\n b = b >= 0 ? b : -b;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n\r\n BigInteger.prototype.compare = function (v) {\r\n // See discussion about comparison with Infinity:\r\n // https://github.com/peterolson/BigInteger.js/issues/61\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (this.sign !== n.sign) {\r\n return n.sign ? 1 : -1;\r\n }\r\n if (n.isSmall) {\r\n return this.sign ? -1 : 1;\r\n }\r\n return compareAbs(a, b) * (this.sign ? -1 : 1);\r\n };\r\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\r\n\r\n SmallInteger.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) {\r\n return a == b ? 0 : a > b ? 1 : -1;\r\n }\r\n if (a < 0 !== n.sign) {\r\n return a < 0 ? -1 : 1;\r\n }\r\n return a < 0 ? 1 : -1;\r\n };\r\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\r\n\r\n NativeBigInt.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\r\n\r\n BigInteger.prototype.equals = function (v) {\r\n return this.compare(v) === 0;\r\n };\r\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\r\n\r\n BigInteger.prototype.notEquals = function (v) {\r\n return this.compare(v) !== 0;\r\n };\r\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\r\n\r\n BigInteger.prototype.greater = function (v) {\r\n return this.compare(v) > 0;\r\n };\r\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\r\n\r\n BigInteger.prototype.lesser = function (v) {\r\n return this.compare(v) < 0;\r\n };\r\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\r\n\r\n BigInteger.prototype.greaterOrEquals = function (v) {\r\n return this.compare(v) >= 0;\r\n };\r\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\r\n\r\n BigInteger.prototype.lesserOrEquals = function (v) {\r\n return this.compare(v) <= 0;\r\n };\r\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\r\n\r\n BigInteger.prototype.isEven = function () {\r\n return (this.value[0] & 1) === 0;\r\n };\r\n SmallInteger.prototype.isEven = function () {\r\n return (this.value & 1) === 0;\r\n };\r\n NativeBigInt.prototype.isEven = function () {\r\n return (this.value & BigInt(1)) === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isOdd = function () {\r\n return (this.value[0] & 1) === 1;\r\n };\r\n SmallInteger.prototype.isOdd = function () {\r\n return (this.value & 1) === 1;\r\n };\r\n NativeBigInt.prototype.isOdd = function () {\r\n return (this.value & BigInt(1)) === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isPositive = function () {\r\n return !this.sign;\r\n };\r\n SmallInteger.prototype.isPositive = function () {\r\n return this.value > 0;\r\n };\r\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\r\n\r\n BigInteger.prototype.isNegative = function () {\r\n return this.sign;\r\n };\r\n SmallInteger.prototype.isNegative = function () {\r\n return this.value < 0;\r\n };\r\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\r\n\r\n BigInteger.prototype.isUnit = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isUnit = function () {\r\n return Math.abs(this.value) === 1;\r\n };\r\n NativeBigInt.prototype.isUnit = function () {\r\n return this.abs().value === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isZero = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isZero = function () {\r\n return this.value === 0;\r\n };\r\n NativeBigInt.prototype.isZero = function () {\r\n return this.value === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isDivisibleBy = function (v) {\r\n var n = parseValue(v);\r\n if (n.isZero()) return false;\r\n if (n.isUnit()) return true;\r\n if (n.compareAbs(2) === 0) return this.isEven();\r\n return this.mod(n).isZero();\r\n };\r\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\r\n\r\n function isBasicPrime(v) {\r\n var n = v.abs();\r\n if (n.isUnit()) return false;\r\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\r\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\r\n if (n.lesser(49)) return true;\r\n // we don't know if it's prime: let the other functions figure it out\r\n }\r\n\r\n function millerRabinTest(n, a) {\r\n var nPrev = n.prev(),\r\n b = nPrev,\r\n r = 0,\r\n d, t, i, x;\r\n while (b.isEven()) b = b.divide(2), r++;\r\n next: for (i = 0; i < a.length; i++) {\r\n if (n.lesser(a[i])) continue;\r\n x = bigInt(a[i]).modPow(b, n);\r\n if (x.isUnit() || x.equals(nPrev)) continue;\r\n for (d = r - 1; d != 0; d--) {\r\n x = x.square().mod(n);\r\n if (x.isUnit()) return false;\r\n if (x.equals(nPrev)) continue next;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\r\n BigInteger.prototype.isPrime = function (strict) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var bits = n.bitLength();\r\n if (bits <= 64)\r\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\r\n var logN = Math.log(2) * bits.toJSNumber();\r\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt(i + 2));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\r\n\r\n BigInteger.prototype.isProbablePrime = function (iterations, rng) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var t = iterations === undefined ? 5 : iterations;\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt.randBetween(2, n.minus(2), rng));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\r\n\r\n BigInteger.prototype.modInv = function (n) {\r\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\r\n while (!newR.isZero()) {\r\n q = r.divide(newR);\r\n lastT = t;\r\n lastR = r;\r\n t = newT;\r\n r = newR;\r\n newT = lastT.subtract(q.multiply(newT));\r\n newR = lastR.subtract(q.multiply(newR));\r\n }\r\n if (!r.isUnit()) throw new Error(this.toString() + \" and \" + n.toString() + \" are not co-prime\");\r\n if (t.compare(0) === -1) {\r\n t = t.add(n);\r\n }\r\n if (this.isNegative()) {\r\n return t.negate();\r\n }\r\n return t;\r\n };\r\n\r\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\r\n\r\n BigInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return subtractSmall(value, 1, this.sign);\r\n }\r\n return new BigInteger(addSmall(value, 1), this.sign);\r\n };\r\n SmallInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\r\n return new BigInteger(MAX_INT_ARR, false);\r\n };\r\n NativeBigInt.prototype.next = function () {\r\n return new NativeBigInt(this.value + BigInt(1));\r\n }\r\n\r\n BigInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return new BigInteger(addSmall(value, 1), true);\r\n }\r\n return subtractSmall(value, 1, this.sign);\r\n };\r\n SmallInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\r\n return new BigInteger(MAX_INT_ARR, true);\r\n };\r\n NativeBigInt.prototype.prev = function () {\r\n return new NativeBigInt(this.value - BigInt(1));\r\n }\r\n\r\n var powersOfTwo = [1];\r\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\r\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\r\n\r\n function shift_isSmall(n) {\r\n return Math.abs(n) <= BASE;\r\n }\r\n\r\n BigInteger.prototype.shiftLeft = function (v) {\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftRight(-n);\r\n var result = this;\r\n if (result.isZero()) return result;\r\n while (n >= powers2Length) {\r\n result = result.multiply(highestPower2);\r\n n -= powers2Length - 1;\r\n }\r\n return result.multiply(powersOfTwo[n]);\r\n };\r\n NativeBigInt.prototype.shiftLeft = function(v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value << v.value)\r\n }\r\n SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\r\n\r\n BigInteger.prototype.shiftRight = function (v) {\r\n var remQuo;\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftLeft(-n);\r\n var result = this;\r\n while (n >= powers2Length) {\r\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\r\n remQuo = divModAny(result, highestPower2);\r\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n n -= powers2Length - 1;\r\n }\r\n remQuo = divModAny(result, powersOfTwo[n]);\r\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n };\r\n NativeBigInt.prototype.shiftRight = function (v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value >> v.value)\r\n }\r\n SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\r\n\r\n function bitwise(x, y, fn) {\r\n y = parseValue(y);\r\n var xSign = x.isNegative(), ySign = y.isNegative();\r\n var xRem = xSign ? x.not() : x,\r\n yRem = ySign ? y.not() : y;\r\n var xDigit = 0, yDigit = 0;\r\n var xDivMod = null, yDivMod = null;\r\n var result = [];\r\n while (!xRem.isZero() || !yRem.isZero()) {\r\n xDivMod = divModAny(xRem, highestPower2);\r\n xDigit = xDivMod[1].toJSNumber();\r\n if (xSign) {\r\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\r\n }\r\n\r\n yDivMod = divModAny(yRem, highestPower2);\r\n yDigit = yDivMod[1].toJSNumber();\r\n if (ySign) {\r\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\r\n }\r\n\r\n xRem = xDivMod[0];\r\n yRem = yDivMod[0];\r\n result.push(fn(xDigit, yDigit));\r\n }\r\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\r\n for (var i = result.length - 1; i >= 0; i -= 1) {\r\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\r\n }\r\n return sum;\r\n }\r\n\r\n BigInteger.prototype.not = function () {\r\n return this.negate().prev();\r\n };\r\n NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;\r\n\r\n BigInteger.prototype.and = function (n) {\r\n return bitwise(this, n, function (a, b) { return a & b; });\r\n };\r\n NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;\r\n\r\n BigInteger.prototype.or = function (n) {\r\n return bitwise(this, n, function (a, b) { return a | b; });\r\n };\r\n NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;\r\n\r\n BigInteger.prototype.xor = function (n) {\r\n return bitwise(this, n, function (a, b) { return a ^ b; });\r\n };\r\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;\r\n\r\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\r\n function roughLOB(n) { // get lowestOneBit (rough)\r\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\r\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\r\n var v = n.value,\r\n x = typeof v === \"number\" ? v | LOBMASK_I :\r\n typeof v === \"bigint\" ? v | BigInt(LOBMASK_I) :\r\n v[0] + v[1] * BASE | LOBMASK_BI;\r\n return x & -x;\r\n }\r\n\r\n function integerLogarithm(value, base) {\r\n if (base.compareTo(value) <= 0) {\r\n var tmp = integerLogarithm(value, base.square(base));\r\n var p = tmp.p;\r\n var e = tmp.e;\r\n var t = p.multiply(base);\r\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\r\n }\r\n return { p: bigInt(1), e: 0 };\r\n }\r\n\r\n BigInteger.prototype.bitLength = function () {\r\n var n = this;\r\n if (n.compareTo(bigInt(0)) < 0) {\r\n n = n.negate().subtract(bigInt(1));\r\n }\r\n if (n.compareTo(bigInt(0)) === 0) {\r\n return bigInt(0);\r\n }\r\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\r\n }\r\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\r\n\r\n function max(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.greater(b) ? a : b;\r\n }\r\n function min(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.lesser(b) ? a : b;\r\n }\r\n function gcd(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n if (a.equals(b)) return a;\r\n if (a.isZero()) return b;\r\n if (b.isZero()) return a;\r\n var c = Integer[1], d, t;\r\n while (a.isEven() && b.isEven()) {\r\n d = min(roughLOB(a), roughLOB(b));\r\n a = a.divide(d);\r\n b = b.divide(d);\r\n c = c.multiply(d);\r\n }\r\n while (a.isEven()) {\r\n a = a.divide(roughLOB(a));\r\n }\r\n do {\r\n while (b.isEven()) {\r\n b = b.divide(roughLOB(b));\r\n }\r\n if (a.greater(b)) {\r\n t = b; b = a; a = t;\r\n }\r\n b = b.subtract(a);\r\n } while (!b.isZero());\r\n return c.isUnit() ? a : a.multiply(c);\r\n }\r\n function lcm(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n return a.divide(gcd(a, b)).multiply(b);\r\n }\r\n function randBetween(a, b, rng) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n var usedRNG = rng || Math.random;\r\n var low = min(a, b), high = max(a, b);\r\n var range = high.subtract(low).add(1);\r\n if (range.isSmall) return low.add(Math.floor(usedRNG() * range));\r\n var digits = toBase(range, BASE).value;\r\n var result = [], restricted = true;\r\n for (var i = 0; i < digits.length; i++) {\r\n var top = restricted ? digits[i] : BASE;\r\n var digit = truncate(usedRNG() * top);\r\n result.push(digit);\r\n if (digit < top) restricted = false;\r\n }\r\n return low.add(Integer.fromArray(result, BASE, false));\r\n }\r\n\r\n var parseBase = function (text, base, alphabet, caseSensitive) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n text = String(text);\r\n if (!caseSensitive) {\r\n text = text.toLowerCase();\r\n alphabet = alphabet.toLowerCase();\r\n }\r\n var length = text.length;\r\n var i;\r\n var absBase = Math.abs(base);\r\n var alphabetValues = {};\r\n for (i = 0; i < alphabet.length; i++) {\r\n alphabetValues[alphabet[i]] = i;\r\n }\r\n for (i = 0; i < length; i++) {\r\n var c = text[i];\r\n if (c === \"-\") continue;\r\n if (c in alphabetValues) {\r\n if (alphabetValues[c] >= absBase) {\r\n if (c === \"1\" && absBase === 1) continue;\r\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\r\n }\r\n }\r\n }\r\n base = parseValue(base);\r\n var digits = [];\r\n var isNegative = text[0] === \"-\";\r\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\r\n var c = text[i];\r\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\r\n else if (c === \"<\") {\r\n var start = i;\r\n do { i++; } while (text[i] !== \">\" && i < text.length);\r\n digits.push(parseValue(text.slice(start + 1, i)));\r\n }\r\n else throw new Error(c + \" is not a valid character\");\r\n }\r\n return parseBaseFromArray(digits, base, isNegative);\r\n };\r\n\r\n function parseBaseFromArray(digits, base, isNegative) {\r\n var val = Integer[0], pow = Integer[1], i;\r\n for (i = digits.length - 1; i >= 0; i--) {\r\n val = val.add(digits[i].times(pow));\r\n pow = pow.times(base);\r\n }\r\n return isNegative ? val.negate() : val;\r\n }\r\n\r\n function stringify(digit, alphabet) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n if (digit < alphabet.length) {\r\n return alphabet[digit];\r\n }\r\n return \"<\" + digit + \">\";\r\n }\r\n\r\n function toBase(n, base) {\r\n base = bigInt(base);\r\n if (base.isZero()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n throw new Error(\"Cannot convert nonzero numbers to base 0.\");\r\n }\r\n if (base.equals(-1)) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n if (n.isNegative())\r\n return {\r\n value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))\r\n .map(Array.prototype.valueOf, [1, 0])\r\n ),\r\n isNegative: false\r\n };\r\n\r\n var arr = Array.apply(null, Array(n.toJSNumber() - 1))\r\n .map(Array.prototype.valueOf, [0, 1]);\r\n arr.unshift([1]);\r\n return {\r\n value: [].concat.apply([], arr),\r\n isNegative: false\r\n };\r\n }\r\n\r\n var neg = false;\r\n if (n.isNegative() && base.isPositive()) {\r\n neg = true;\r\n n = n.abs();\r\n }\r\n if (base.isUnit()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n\r\n return {\r\n value: Array.apply(null, Array(n.toJSNumber()))\r\n .map(Number.prototype.valueOf, 1),\r\n isNegative: neg\r\n };\r\n }\r\n var out = [];\r\n var left = n, divmod;\r\n while (left.isNegative() || left.compareAbs(base) >= 0) {\r\n divmod = left.divmod(base);\r\n left = divmod.quotient;\r\n var digit = divmod.remainder;\r\n if (digit.isNegative()) {\r\n digit = base.minus(digit).abs();\r\n left = left.next();\r\n }\r\n out.push(digit.toJSNumber());\r\n }\r\n out.push(left.toJSNumber());\r\n return { value: out.reverse(), isNegative: neg };\r\n }\r\n\r\n function toBaseString(n, base, alphabet) {\r\n var arr = toBase(n, base);\r\n return (arr.isNegative ? \"-\" : \"\") + arr.value.map(function (x) {\r\n return stringify(x, alphabet);\r\n }).join('');\r\n }\r\n\r\n BigInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n SmallInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n NativeBigInt.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n BigInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix !== 10) return toBaseString(this, radix, alphabet);\r\n var v = this.value, l = v.length, str = String(v[--l]), zeros = \"0000000\", digit;\r\n while (--l >= 0) {\r\n digit = String(v[l]);\r\n str += zeros.slice(digit.length) + digit;\r\n }\r\n var sign = this.sign ? \"-\" : \"\";\r\n return sign + str;\r\n };\r\n\r\n SmallInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix != 10) return toBaseString(this, radix, alphabet);\r\n return String(this.value);\r\n };\r\n\r\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\r\n\r\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\r\n\r\n BigInteger.prototype.valueOf = function () {\r\n return parseInt(this.toString(), 10);\r\n };\r\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\r\n\r\n SmallInteger.prototype.valueOf = function () {\r\n return this.value;\r\n };\r\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\r\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {\r\n return parseInt(this.toString(), 10);\r\n }\r\n\r\n function parseStringValue(v) {\r\n if (isPrecise(+v)) {\r\n var x = +v;\r\n if (x === truncate(x))\r\n return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);\r\n throw new Error(\"Invalid integer: \" + v);\r\n }\r\n var sign = v[0] === \"-\";\r\n if (sign) v = v.slice(1);\r\n var split = v.split(/e/i);\r\n if (split.length > 2) throw new Error(\"Invalid integer: \" + split.join(\"e\"));\r\n if (split.length === 2) {\r\n var exp = split[1];\r\n if (exp[0] === \"+\") exp = exp.slice(1);\r\n exp = +exp;\r\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error(\"Invalid integer: \" + exp + \" is not a valid exponent.\");\r\n var text = split[0];\r\n var decimalPlace = text.indexOf(\".\");\r\n if (decimalPlace >= 0) {\r\n exp -= text.length - decimalPlace - 1;\r\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\r\n }\r\n if (exp < 0) throw new Error(\"Cannot include negative exponent part for integers\");\r\n text += (new Array(exp + 1)).join(\"0\");\r\n v = text;\r\n }\r\n var isValid = /^([0-9][0-9]*)$/.test(v);\r\n if (!isValid) throw new Error(\"Invalid integer: \" + v);\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(sign ? \"-\" + v : v));\r\n }\r\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\r\n while (max > 0) {\r\n r.push(+v.slice(min, max));\r\n min -= l;\r\n if (min < 0) min = 0;\r\n max -= l;\r\n }\r\n trim(r);\r\n return new BigInteger(r, sign);\r\n }\r\n\r\n function parseNumberValue(v) {\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(v));\r\n }\r\n if (isPrecise(v)) {\r\n if (v !== truncate(v)) throw new Error(v + \" is not an integer.\");\r\n return new SmallInteger(v);\r\n }\r\n return parseStringValue(v.toString());\r\n }\r\n\r\n function parseValue(v) {\r\n if (typeof v === \"number\") {\r\n return parseNumberValue(v);\r\n }\r\n if (typeof v === \"string\") {\r\n return parseStringValue(v);\r\n }\r\n if (typeof v === \"bigint\") {\r\n return new NativeBigInt(v);\r\n }\r\n return v;\r\n }\r\n // Pre-define numbers in range [-999,999]\r\n for (var i = 0; i < 1000; i++) {\r\n Integer[i] = parseValue(i);\r\n if (i > 0) Integer[-i] = parseValue(-i);\r\n }\r\n // Backwards compatibility\r\n Integer.one = Integer[1];\r\n Integer.zero = Integer[0];\r\n Integer.minusOne = Integer[-1];\r\n Integer.max = max;\r\n Integer.min = min;\r\n Integer.gcd = gcd;\r\n Integer.lcm = lcm;\r\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };\r\n Integer.randBetween = randBetween;\r\n\r\n Integer.fromArray = function (digits, base, isNegative) {\r\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\r\n };\r\n\r\n return Integer;\r\n})();\r\n\r\n// Node.js check\r\nif (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (typeof define === \"function\" && define.amd) {\r\n define( function () {\r\n return bigInt;\r\n });\r\n}\r\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\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 (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","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: 'Invalid Password',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\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","export 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(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\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 && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","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 <= 1572864000) { // 1500MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n\n/* CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`;\n } else if (entity.firstName) {\n return entity.firstName;\n } else if (entity.lastName) {\n return entity.lastName;\n } else {\n return '';\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\nfunction getDC(dcId) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: 'pluto.web.telegram.org',\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: 'venus.web.telegram.org',\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: 'aurora.web.telegram.org',\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: 'vesta.web.telegram.org',\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: 'flora.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","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","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n if (!stickerAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute.stickerset as GramJs.InputStickerSetID;\n const emoji = stickerAttribute.alt;\n const isAnimated = document.mimeType === 'application/x-tgsticker';\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo.id ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n hash,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs && thumbs.length),\n count,\n hash,\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","/**\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","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { pick } from '../../../util/iteratees';\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: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | 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;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\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","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","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\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();\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n 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 || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | 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 if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now();\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\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 }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(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 = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\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 ((\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[randomId.toString()];\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();\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: update.channelId,\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: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\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: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\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: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\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: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\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: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\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 const {\n silent, muteUntil, showPreviews, sound,\n } = update.notifySettings;\n\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isMuted,\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\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: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\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 const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent || (typeof muteUntil === 'number' && Date.now() < 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.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","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 {\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","/**\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","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\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 { 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","/* 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 { 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 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","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 * 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","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');\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 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) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\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();\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);\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() {\n this._connected = false;\n await this._recvArray.push(undefined);\n await this.socket.close();\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\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 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","/* pako 1.0.10 nodeca/pako */(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n},{\"./common\":1}],3:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n},{}],7:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],8:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":1,\"./adler32\":3,\"./crc32\":5,\"./inffast\":7,\"./inftrees\":9}],9:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":1}],10:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],11:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],\"/lib/inflate.js\":[function(require,module,exports){\n'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n},{\"./utils/common\":1,\"./utils/strings\":2,\"./zlib/constants\":4,\"./zlib/gzheader\":6,\"./zlib/inflate\":8,\"./zlib/messages\":10,\"./zlib/zstream\":11}]},{},[])(\"/lib/inflate.js\")\n});\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","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","var S = new Uint8Array(256);\nvar Si = new Uint8Array(256);\nvar T1 = new Uint32Array(256);\nvar T2 = new Uint32Array(256);\nvar T3 = new Uint32Array(256);\nvar T4 = new Uint32Array(256);\nvar T5 = new Uint32Array(256);\nvar T6 = new Uint32Array(256);\nvar T7 = new Uint32Array(256);\nvar T8 = new Uint32Array(256);\nfunction computeTables() {\n var d = new Uint8Array(256);\n var t = new Uint8Array(256);\n var x2;\n var x4;\n var x8;\n var s;\n var tEnc;\n var tDec;\n var x = 0;\n var xInv = 0;\n // Compute double and third tables\n for (var i = 0; i < 256; i++) {\n d[i] = i << 1 ^ (i >> 7) * 283;\n t[d[i] ^ i] = i;\n }\n for (; !S[x]; x ^= x2 || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n S[x] = s;\n Si[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n T1[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T2[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T3[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T4[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T5[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T6[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T7[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T8[s] = tDec = tDec << 24 ^ tDec >>> 8;\n xInv = t[xInv] || 1;\n }\n}\n\n/**\n * Gets a uint32 from string in big-endian order order\n */\nfunction s2i(str, pos) {\n return (str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3));\n}\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Helper function for transforming string key to Uint32Array\n */\nfunction getWords(key) {\n if (key instanceof Uint32Array) {\n return key;\n }\n if (typeof key === 'string') {\n if (key.length % 4 !== 0)\n for (var i = key.length % 4; i <= 4; i++)\n key += '\\0x00';\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4)\n buf[i / 4] = s2i(key, i);\n return buf;\n }\n if (key instanceof Uint8Array) {\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4) {\n buf[i / 4] = (key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]);\n }\n return buf;\n }\n throw new Error('Unable to create 32-bit words');\n}\nfunction xor(left, right, to) {\n if (to === void 0) { to = left; }\n for (var i = 0; i < left.length; i++)\n to[i] = left[i] ^ right[i];\n}\n\ncomputeTables();\n/**\n * Low-level AES Cipher\n */\nvar AES = /** @class */ (function () {\n function AES(_key) {\n var key = getWords(_key);\n if (key.length !== 4 && key.length !== 6 && key.length !== 8) {\n throw new Error('Invalid key size');\n }\n this.encKey = new Uint32Array(4 * key.length + 28);\n this.decKey = new Uint32Array(4 * key.length + 28);\n this.encKey.set(key);\n var rcon = 1;\n var i = key.length;\n var tmp;\n // schedule encryption keys\n for (; i < 4 * key.length + 28; i++) {\n tmp = this.encKey[i - 1];\n // apply sbox\n if (i % key.length === 0 || (key.length === 8 && i % key.length === 4)) {\n tmp = S[tmp >>> 24] << 24 ^ S[(tmp >> 16) & 255] << 16 ^ S[(tmp >> 8) & 255] << 8 ^ S[tmp & 255];\n // shift rows and add rcon\n if (i % key.length === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ (rcon << 24);\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n this.encKey[i] = this.encKey[i - key.length] ^ tmp;\n }\n // schedule decryption keys\n for (var j = 0; i; j++, i--) {\n tmp = this.encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n this.decKey[j] = tmp;\n }\n else {\n this.decKey[j] = (T5[S[tmp >>> 24]]\n ^ T6[S[(tmp >> 16) & 255]]\n ^ T7[S[(tmp >> 8) & 255]]\n ^ T8[S[tmp & 255]]);\n }\n }\n }\n AES.prototype.encrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.encKey[0];\n var b = message[1] ^ this.encKey[1];\n var c = message[2] ^ this.encKey[2];\n var d = message[3] ^ this.encKey[3];\n var rounds = this.encKey.length / 4 - 2;\n var k = 4;\n var a2;\n var b2;\n var c2;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T1[a >>> 24] ^ T2[(b >> 16) & 255] ^ T3[(c >> 8) & 255] ^ T4[d & 255] ^ this.encKey[k];\n b2 = T1[b >>> 24] ^ T2[(c >> 16) & 255] ^ T3[(d >> 8) & 255] ^ T4[a & 255] ^ this.encKey[k + 1];\n c2 = T1[c >>> 24] ^ T2[(d >> 16) & 255] ^ T3[(a >> 8) & 255] ^ T4[b & 255] ^ this.encKey[k + 2];\n d = T1[d >>> 24] ^ T2[(a >> 16) & 255] ^ T3[(b >> 8) & 255] ^ T4[c & 255] ^ this.encKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n // console.log(a, b, c, d);\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[i] = (S[a >>> 24] << 24\n ^ S[(b >> 16) & 255] << 16\n ^ S[(c >> 8) & 255] << 8\n ^ S[d & 255]\n ^ this.encKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n AES.prototype.decrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.decKey[0];\n var b = message[3] ^ this.decKey[1];\n var c = message[2] ^ this.decKey[2];\n var d = message[1] ^ this.decKey[3];\n var rounds = this.decKey.length / 4 - 2;\n var a2;\n var b2;\n var c2;\n var k = 4;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T5[a >>> 24] ^ T6[(b >> 16) & 255] ^ T7[(c >> 8) & 255] ^ T8[d & 255] ^ this.decKey[k];\n b2 = T5[b >>> 24] ^ T6[(c >> 16) & 255] ^ T7[(d >> 8) & 255] ^ T8[a & 255] ^ this.decKey[k + 1];\n c2 = T5[c >>> 24] ^ T6[(d >> 16) & 255] ^ T7[(a >> 8) & 255] ^ T8[b & 255] ^ this.decKey[k + 2];\n d = T5[d >>> 24] ^ T6[(a >> 16) & 255] ^ T7[(b >> 8) & 255] ^ T8[c & 255] ^ this.decKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[3 & -i] = (Si[a >>> 24] << 24\n ^ Si[(b >> 16) & 255] << 16\n ^ Si[(c >> 8) & 255] << 8\n ^ Si[d & 255]\n ^ this.decKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n return AES;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE = /** @class */ (function () {\n function AES_IGE(key, iv, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.key = getWords(key);\n this.iv = getWords(iv);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var prevX = this.iv.subarray(this.blockSize, this.iv.length);\n var prevY = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = text.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.encrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n cipherText[j] = y[k];\n }\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n var cipherText = getWords(message);\n var text = buf || new Uint32Array(cipherText.length);\n var prevY = this.iv.subarray(this.blockSize, this.iv.length);\n var prevX = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = cipherText.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.decrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n text[j] = y[k];\n }\n return text;\n };\n return AES_IGE;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE$1 = /** @class */ (function () {\n function AES_IGE(key, counter, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.offset = 0;\n this.key = getWords(key);\n this.counter = getWords(counter);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n if (this.counter.length !== 4) {\n throw new Error('AES-CTR mode counter must be 16 bytes length');\n }\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var offset = this.offset;\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = this.cipher.encrypt(this.counter);\n for (var j = i, k = offset; j < text.length && k < this.blockSize; j++, k++)\n cipherText[j] = x[k] ^ text[j];\n if (text.length - i >= this.blockSize)\n this.incrementCounter();\n if (offset) {\n i -= offset;\n offset = 0;\n }\n }\n this.offset = (this.offset + (text.length % 4)) % 4;\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n return this.encrypt(message, buf);\n };\n AES_IGE.prototype.incrementCounter = function () {\n // increment counter\n for (var carry = this.counter.length - 1; carry >= 0; carry--) {\n if (++this.counter[carry] < 0xFFFFFFFF)\n break; // If overflowing, it'll be 0 and we'll have to continue propagating the carry\n }\n };\n return AES_IGE;\n}());\n\nexport default AES;\nexport { AES_IGE$1 as CTR, AES_IGE as IGE };\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 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 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 {\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}\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 [/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 EmailUnconfirmedError,\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","const api = require('./api');\n\nconst LAYER = 128;\nconst tlobjects = {};\n\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 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');\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n\n/**\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 the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this._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 await Helpers.sleep(this._delay);\n }\n }\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 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 // CONTEST\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n /*\n if (!Helpers.isArrayLike(request)) {\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n } else {\n throw new Error('not supported')\n } */\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.time_offset = res.timeOffset;\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._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\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 this._log.info('Broken authorization key; resetting');\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (this._onConnectionBreak && !this._isMainSender) {\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId);\n }\n\n // We don't really need to do this if we're going to sign in again\n /* await this.authKey.setKey(null)\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(null)\n } */\n // We can disconnect at sign in\n /* await this.disconnect()\n */\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n 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 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 delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\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 this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\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 to = this._state.updateTimeOffset(message.msgId);\n this._log.info(`System clock is wrong, set time offset to ${to}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 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 delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n this._log.info('Started reconnecting');\n this._reconnect();\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 await this.connect(this._connection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\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 BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, data).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { 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","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 { 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","const BigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst RSA = require('../crypto/RSA');\nconst Helpers = require('../Helpers');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { SecurityError } = require('../errors/Common');\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 */\nasync function doAuthentication(sender, log) {\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\n const resPQ = await sender.send(new requests.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof constructors.ResPQ)) {\n throw new Error(`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 log.debug('Starting authKey generation step 2');\n // Step 2 sending: DH Exchange\n let {\n p,\n q,\n } = Factorizator.factorize(pq);\n\n // TODO Bring back after `Factorizator` fix.\n p = Helpers.getByteArray(p);\n q = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n\n const pqInnerData = new constructors.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p,\n q,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n });\n\n // sha_digest + data + random_bytes\n let cipherText;\n let targetFingerprint;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n cipherText = await RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes());\n if (cipherText !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (cipherText === undefined) {\n throw new SecurityError('Step 2 could not find a valid key for fingerprints');\n }\n\n const serverDhParams = await sender.send(\n new requests.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p,\n q,\n publicKeyFingerprint: targetFingerprint,\n encryptedData: cipherText,\n }),\n );\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk\n || serverDhParams instanceof constructors.ServerDHParamsFail)) {\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 constructors.ServerDHParamsFail) {\n const sh = await Helpers.sha1(Helpers.toSignedLittleBuffer(newNonce, 32)\n .slice(4, 20));\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 constructors.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 {\n key,\n iv,\n } = await Helpers.generateKeyDataFromNonce(resPQ.serverNonce, newNonce);\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 constructors.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('Step 3 Invalid server nonce in encrypted answer');\n }\n const dhPrime = Helpers.readBigIntFromBuffer(serverDhInner.dhPrime, false, false);\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(Helpers.generateRandomBytes(256), false, false);\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 constructors.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: 0, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([await Helpers.sha1(clientDhInner), clientDhInner]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new requests.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [constructors.DhGenOk, constructors.DhGenRetry, constructors.DhGenFail];\n if (!(dhGen instanceof nonceTypes[0] || dhGen instanceof nonceTypes[1] || dhGen instanceof nonceTypes[2])) {\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(`Step 3 invalid ${name} server nonce from server`);\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypes.indexOf(dhGen.constructor);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\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 constructors.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return {\n authKey,\n timeOffset,\n };\n}\n\n\nmodule.exports = doAuthentication;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('../extensions/BinaryWriter');\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 this._queue.push(state);\n this.setReady(true);\n\n if (state) {\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","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","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst doAuthentication = require('./Authenticator');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n doAuthentication,\n MTProtoSender,\n UpdateConnectionState,\n};\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() {\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 }\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) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`;\n } else {\n return `ws://${ip}:${port}/apiws`;\n }\n }\n\n connect(port, ip) {\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);\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 reject(error);\n };\n this.client.onclose = () => {\n this.resolveRead(false);\n this.closed = true;\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 const release = await mutex.acquire();\n try {\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 } finally {\n release();\n }\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\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 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","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\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?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\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?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\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 isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\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.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result;\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\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","/*\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","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#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = 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#f4e096c3 flags:# multiple_allowed:flags.1?true can_forward:flags.2?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param: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#bba51639 call:InputGroupCall time_ms:long scale:int = InputFileLocation;\npeerUser#9db1bc6d user_id:int = Peer;\npeerChat#bad0e5bb chat_id:int = Peer;\npeerChannel#bddde532 channel_id:int = 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#200250ba id:int = User;\nuser#938458c1 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:int 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#9ba2d800 id:int = Chat;\nchat#3bda1bde flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true id:int 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#7328bdb id:int title:string = Chat;\nchannel#d31a961e flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true id:int access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int version: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#289da732 flags:# broadcast:flags.5?true megagroup:flags.8?true id:int access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#8a1e2983 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:int 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 = ChatFull;\nchannelFull#548c3f93 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:int 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?int 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?int 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 = ChatFull;\nchatParticipant#c8d7493e user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantCreator#da13538a user_id:int = ChatParticipant;\nchatParticipantAdmin#e2d6e436 user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3f460fed chat_id:int 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#bce383d2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#cbf24940 phone_number:string first_name:string last_name:string vcard:string user_id:int = 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#a6638b9a title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#488a7337 users:Vector = MessageAction;\nmessageActionChatDeleteUser#b2ae9b0c user_id:int = MessageAction;\nmessageActionChatJoinedByLink#f89cf5e8 inviter_id:int = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#51bdb021 channel_id:int = MessageAction;\nmessageActionChannelMigrateFrom#b055eaee title:string chat_id:int = 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#76b9f11a call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#df969c2d id:int bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#8af40b25 flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#139a9a77 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int 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#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#86cadb6c chat_id:int from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int 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#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int 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#12b9417b user_id:int 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#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int 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#3f2038db flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int 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#e73547e1 flags:# query_id:long user_id:int 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#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int 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#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int 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#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int 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#42f88f2c poll_id:long user_id:int options:Vector = 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#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#6b171718 flags:# channel_id:int 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#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChat#1330a196 chat_id:int = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#a45eb99b chat_id:int call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#f3b3781f flags:# chat_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#7fecb1ec flags:# channel_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#7f9488a user_id:int date:int stopped:Bool qts:int = 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#faeff833 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#1157b858 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int 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#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int 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;\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#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 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#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 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 = 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#6e24fc9d flags:# revoked:flags.0?true permanent:flags.5?true link:string admin_id:int date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = 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#352dca58 offset:int length:int user_id:int = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = 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#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#50a1dfd6 flags:# left:flags.0?true peer:Peer kicked_by:int 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#2e0709a5 hash:int 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#d5348d85 flags:# multiple_allowed:flags.1?true can_forward:flags.3?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\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#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int 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#58fffcd0 pos:int user_id:int 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#8d0b2415 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:int invoice:Invoice provider_id:int 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#10b555d0 flags:# date:int bot_id:int provider_id:int 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#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int 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#a26f881b prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = 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#cac943f2 hash:long bot_id:int 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#5108d648 hash:int 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#badcc1a3 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#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?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#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int 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#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int 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#18f3d0f7 user_id:int messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#6014f412 user_id:int deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#31962a4c user_id:int 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#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?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#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int 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#c95c6654 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 id:long access_hash:long participants_count:int params:flags.0?DataJSON title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#b96b25ee 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 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 params:flags.6?DataJSON = 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#1e3e6680 user_id:int date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#dfd2330f admin_id:int 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;\n---functions---\n// Only needed functions from \\`api.tl\\` are manually copied here to reduce package size\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int 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#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf 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.getWallPapers#aabb1763 hash:int = 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;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = 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#d4982db5 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:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec 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:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = 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#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = 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#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\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#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\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#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = 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#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = 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;\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;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\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#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = 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.exportMessageLink#e63fadeb flags:# grouped:flags.0?true thread:flags.1?true channel:InputChannel id:int = ExportedMessageLink;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 128\n`;","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n`;","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst DEFAULT_IPV4_IP = 'venus.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\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 };\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 === undefined || apiHash === undefined) {\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._borrowedSenderPromises = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n }\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 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 const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log,\n );\n\n await this._sender.connect(connection);\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n this._updateLoop();\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (this.isConnected()) {\n await Helpers.sleep(3 * 1000);\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.Ping({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n })), 1500);\n }, 3, 100);\n } catch (err) {\n await this.disconnect();\n this.connect();\n\n return;\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n }\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._borrowedSenderPromises)\n .map((promise) => {\n return promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._borrowedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n await this.disconnect();\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 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 _cleanupBorrowedSender(dcId) {\n delete this._borrowedSenderPromises[dcId];\n }\n\n _borrowExportedSender(dcId) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n let senderPromise = this._borrowedSenderPromises[dcId];\n if (!senderPromise) {\n senderPromise = this._createExportedSender(dcId);\n this._borrowedSenderPromises[dcId] = senderPromise;\n\n senderPromise.then((sender) => {\n if (!sender) {\n delete this._borrowedSenderPromises[dcId];\n }\n });\n }\n return senderPromise;\n }\n\n async _createExportedSender(dcId) {\n const dc = utils.getDC(dcId);\n const sender = new MTProtoSender(this.session.getAuthKey(dcId),\n {\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._cleanupBorrowedSender.bind(this),\n });\n for (let i = 0; i < 5; i++) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ));\n if (this.session.dcId !== dcId) {\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 }\n sender.dcId = dcId;\n return sender;\n } catch (e) {\n await sender.disconnect();\n }\n }\n return undefined;\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\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadWebDocument(media, args) {\n throw new Error('not implemented');\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n try {\n const promise = this._sender.send(request);\n const result = await promise;\n // this.session.processEntities(result)\n // this._entityCache.add(result)\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 {\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\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\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n 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","exports.endianness = function () { return 'LE' };\n\nexports.hostname = function () {\n if (typeof location !== 'undefined') {\n return location.hostname\n }\n else return '';\n};\n\nexports.loadavg = function () { return [] };\n\nexports.uptime = function () { return 0 };\n\nexports.freemem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.totalmem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.cpus = function () { return [] };\n\nexports.type = function () { return 'Browser' };\n\nexports.release = function () {\n if (typeof navigator !== 'undefined') {\n return navigator.appVersion;\n }\n return '';\n};\n\nexports.networkInterfaces\n= exports.getNetworkInterfaces\n= function () { return {} };\n\nexports.arch = function () { return 'javascript' };\n\nexports.platform = function () { return 'browser' };\n\nexports.tmpdir = exports.tmpDir = function () {\n return '/tmp';\n};\n\nexports.EOL = '\\n';\n\nexports.homedir = function () {\n\treturn '/'\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\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","/* eslint-disable max-len */\nconst BigInt = require('big-integer');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n generateRandomBytes,\n modExp,\n} = require('../Helpers');\n\nconst PUBLIC_KEYS = [{\n fingerprint: [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],\n n: BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),\n e: 65537,\n}, {\n fingerprint: [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],\n n: BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),\n e: 65537,\n}, {\n fingerprint: [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],\n n: BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),\n e: 65537,\n}, {\n fingerprint: [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],\n n: BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),\n e: 65537,\n}];\n\nconst _serverKeys = {};\n\nPUBLIC_KEYS.forEach(({\n fingerprint,\n ...keyInfo\n}) => {\n _serverKeys[readBigIntFromBuffer(fingerprint.slice(-8), true, true)] = 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 None if no key matching this fingerprint is found.\n */\nasync function encrypt(fingerprint, data) {\n const key = _serverKeys[fingerprint];\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\nmodule.exports = {\n encrypt,\n};\n","class RequestState {\n constructor(request, after = undefined) {\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.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\nmodule.exports = RequestState;\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","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex_1 = require(\"./Mutex\");\nexports.Mutex = Mutex_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._queue = [];\n this._pending = false;\n }\n Mutex.prototype.isLocked = function () {\n return this._pending;\n };\n Mutex.prototype.acquire = function () {\n var _this = this;\n var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); });\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this\n .acquire()\n .then(function (release) {\n var result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw (e);\n }\n return Promise\n .resolve(result)\n .then(function (x) { return (release(), x); }, function (e) {\n release();\n throw e;\n });\n });\n };\n Mutex.prototype._dispatchNext = function () {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","var _global = (function () {\n\tif (!this && typeof global !== 'undefined') {\n\t\treturn global;\n\t}\n\treturn this;\n})();\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar websocket_version = require('./version');\n\n\n/**\n * Expose a W3C WebSocket class with just one or two arguments.\n */\nfunction W3CWebSocket(uri, protocols) {\n\tvar native_instance;\n\n\tif (protocols) {\n\t\tnative_instance = new NativeWebSocket(uri, protocols);\n\t}\n\telse {\n\t\tnative_instance = new NativeWebSocket(uri);\n\t}\n\n\t/**\n\t * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket\n\t * class). Since it is an Object it will be returned as it is when creating an\n\t * instance of W3CWebSocket via 'new W3CWebSocket()'.\n\t *\n\t * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2\n\t */\n\treturn native_instance;\n}\nif (NativeWebSocket) {\n\t['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {\n\t\tObject.defineProperty(W3CWebSocket, prop, {\n\t\t\tget: function() { return NativeWebSocket[prop]; }\n\t\t});\n\t});\n}\n\n/**\n * Module exports.\n */\nmodule.exports = {\n 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,\n 'version' : websocket_version\n};\n","module.exports = require('../package.json').version;\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","// 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}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n const me = 'phoneNumber' in authParams\n ? await signInUser(client, apiCredentials, authParams)\n : await signInBot(client, apiCredentials, authParams);\n\n // TODO @logger\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep } from '../Helpers';\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 REQUEST_TIMEOUT = 15000;\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 let sender: any;\n if (dcId) {\n try {\n sender = await client._borrowExportedSender(dcId);\n } catch (e) {\n // This should never raise\n client._log.error(e);\n if (e.message === 'DC_ID_INVALID') {\n // Can't export a sender for the ID we are currently in\n sender = client._sender;\n } else {\n throw e;\n }\n }\n } else {\n sender = client._sender;\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 // 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 await foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async () => {\n try {\n const result = await Promise.race([\n await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset,\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(REQUEST_TIMEOUT).then(() => Promise.reject(new Error('REQUEST_TIMEOUT'))),\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 return result.bytes;\n } catch (err) {\n hasEnded = true;\n throw err;\n } finally {\n foreman.releaseWorker();\n }\n })());\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\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\n\nfunction createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve: resolve!,\n };\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';\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 UPLOAD_TIMEOUT = 15 * 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 // We always upload from the DC we are in.\n const sender = await client._borrowExportedSender(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 () => {\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: j,\n fileTotalParts: partCount,\n bytes,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: j,\n bytes,\n }),\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 })());\n }\n try {\n await Promise.race([\n await Promise.all(sendingParts),\n sleep(UPLOAD_TIMEOUT * workers).then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n } catch (err) {\n if (err.message === 'TIMEOUT') {\n // eslint-disable-next-line no-console\n console.warn('Upload timeout. Retrying...');\n i -= workers;\n continue;\n }\n\n throw err;\n }\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","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","module.exports = '0.0.2';\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","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 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 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","/* 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 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 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","function 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 request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","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","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\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: number;\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 fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { 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 } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\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 }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs && stickerSet.thumbs.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: 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({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n 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: result.hash,\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport { buildApiWallpaper, buildApiSession, buildPrivacyRules } from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\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 hash: result.hash,\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: number) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildPeer(chatOrUserId),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, 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 const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }), true);\n\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updateLocalDb(result);\n }\n}\n\nexport async function fetchNotificationSettings() {\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 || (typeof privateMuteUntil === 'number' && Date.now() < privateMuteUntil * 1000)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number' && Date.now() < groupMuteUntil * 1000)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number' && Date.now() < broadcastMuteUntil * 1000)\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 : undefined,\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 }: { sourceLangPacks: string[]; langCode: string }) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function 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: IInputPrivacyRules,\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 }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\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\nfunction updateLocalDb(\n result: GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined,\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\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 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 providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\n\nexport async function validateRequestedInfo({\n messageId,\n requestInfo,\n shouldSave,\n}: {\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 msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n messageId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n messageId: number;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n messageId,\n}: {\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n msgId: messageId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({ msgId }));\n if (!result) {\n return undefined;\n }\n return buildReceipt(result);\n}\n","import {\n ApiOnProgress, ApiSessionData, ApiUpdate, OnApiUpdate,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, sessionData);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n }\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"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/gramjs/index.js","webpack:///./src/util/cacheApi.ts","webpack:///./src/api/gramjs/methods/media.ts","webpack:///./src/api/gramjs/methods/client.ts","webpack:///./src/api/gramjs/gramjsBuilders/index.ts","webpack:///./src/api/gramjs/apiBuilders/peers.ts","webpack:///./src/api/gramjs/apiBuilders/chats.ts","webpack:///./src/config.ts","webpack:///./src/api/gramjs/localDb.ts","webpack:///./src/lib/gramjs/tl/api.js","webpack:///./src/api/gramjs/methods/chats.ts","webpack:///./src/lib/gramjs/Helpers.js","webpack:///./src/components/middle/helpers/getCurrencySign.ts","webpack:///./src/api/gramjs/apiBuilders/messages.ts","webpack:///./src/api/gramjs/methods/messages.ts","webpack:///./src/api/types/index.ts","webpack:///./node_modules/node-libs-browser/node_modules/buffer/index.js","webpack:///./src/api/gramjs/apiBuilders/users.ts","webpack:///./src/util/iteratees.ts","webpack:///./node_modules/big-integer/BigInteger.js","webpack:///./src/api/gramjs/helpers.ts","webpack:///./src/api/gramjs/methods/auth.ts","webpack:///./src/api/gramjs/apiBuilders/helpers.ts","webpack:///./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack:///./src/api/gramjs/apiBuilders/common.ts","webpack:///./src/lib/gramjs/Utils.js","webpack:///./src/lib/gramjs/tl/index.js","webpack:///./src/api/gramjs/apiBuilders/symbols.ts","webpack:///./src/lib/gramjs/errors/Common.js","webpack:///./src/api/gramjs/apiBuilders/misc.ts","webpack:///./src/lib/gramjs/extensions/BinaryReader.js","webpack:///./src/api/gramjs/updater.ts","webpack:///./src/lib/gramjs/sessions/Memory.js","webpack:///./src/lib/gramjs/crypto/AuthKey.js","webpack:///./src/lib/gramjs/errors/index.js","webpack:///./src/util/schedulers.ts","webpack:///./src/lib/gramjs/Password.js","webpack:///./src/lib/gramjs/tl/core/GZIPPacked.js","webpack:///./src/util/waveform.ts","webpack:///./src/util/files.ts","webpack:///./src/lib/gramjs/crypto/crypto.js","webpack:///./src/lib/gramjs/errors/RPCBaseErrors.js","webpack:///./src/lib/gramjs/tl/core/TLMessage.js","webpack:///./src/lib/gramjs/tl/core/MessageContainer.js","webpack:///./src/lib/gramjs/network/connection/Connection.js","webpack:///./src/lib/gramjs/sessions/StorageSession.js","webpack:///./node_modules/pako/dist/pako_inflate.js","webpack:///./src/lib/gramjs/extensions/index.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/lib/gramjs/tl/generationHelpers.js","webpack:///./node_modules/@cryptography/aes/dist/es/aes.js","webpack:///./src/lib/gramjs/extensions/Logger.js","webpack:///./src/lib/gramjs/errors/RPCErrorList.js","webpack:///./src/lib/gramjs/sessions/Abstract.js","webpack:///./src/lib/gramjs/tl/AllTLObjects.js","webpack:///./src/lib/gramjs/network/MTProtoSender.js","webpack:///./src/lib/gramjs/network/MTProtoPlainSender.js","webpack:///./src/lib/gramjs/network/MTProtoState.js","webpack:///./src/lib/gramjs/crypto/IGE.js","webpack:///./src/lib/gramjs/tl/core/index.js","webpack:///./src/lib/gramjs/tl/core/RPCResult.js","webpack:///./src/lib/gramjs/network/Authenticator.js","webpack:///./src/lib/gramjs/extensions/MessagePacker.js","webpack:///./src/lib/gramjs/extensions/BinaryWriter.js","webpack:///./src/lib/gramjs/network/index.js","webpack:///./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack:///./src/lib/gramjs/extensions/AsyncQueue.js","webpack:///./src/lib/gramjs/network/connection/TCPAbridged.js","webpack:///./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/api/gramjs/methods/bots.ts","webpack:///./node_modules/base64-js/index.js","webpack:///./node_modules/ieee754/index.js","webpack:///./node_modules/isarray/index.js","webpack:///(webpack)/buildin/module.js","webpack:///./src/lib/gramjs/crypto/converters.ts","webpack:///./src/lib/gramjs/crypto/words.ts","webpack:///./src/lib/gramjs/tl/apiTl.js","webpack:///./src/lib/gramjs/tl/schemaTl.js","webpack:///./src/lib/gramjs/client/TelegramClient.js","webpack:///./node_modules/os-browserify/browser.js","webpack:///./node_modules/process/browser.js","webpack:///./src/lib/gramjs/crypto/Factorizator.js","webpack:///./src/lib/gramjs/crypto/RSA.js","webpack:///./src/lib/gramjs/network/RequestState.js","webpack:///./src/lib/gramjs/network/connection/index.js","webpack:///./node_modules/async-mutex/lib/index.js","webpack:///./node_modules/async-mutex/lib/Mutex.js","webpack:///./node_modules/websocket/lib/browser.js","webpack:///./node_modules/websocket/lib/version.js","webpack:///./src/lib/gramjs/crypto/CTR.js","webpack:///./src/lib/gramjs/client/auth.ts","webpack:///./src/lib/gramjs/client/downloadFile.ts","webpack:///./src/lib/gramjs/client/uploadFile.ts","webpack:///./src/lib/gramjs/client/2fa.ts","webpack:///./src/lib/gramjs/Version.js","webpack:///./src/lib/gramjs/events/index.js","webpack:///./src/lib/gramjs/events/Raw.js","webpack:///./src/lib/gramjs/events/common.js","webpack:///./src/lib/gramjs/sessions/index.js","webpack:///./src/lib/gramjs/sessions/StringSession.js","webpack:///./src/lib/gramjs/sessions/CacheApiSession.js","webpack:///./src/lib/gramjs/sessions/LocalStorageSession.js","webpack:///./src/lib/gramjs/sessions/IdbSession.js","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/lib/gramjs/sessions/CallbackSession.js","webpack:///./src/api/gramjs/methods/users.ts","webpack:///./src/api/gramjs/methods/symbols.ts","webpack:///./src/api/gramjs/methods/management.ts","webpack:///./src/api/gramjs/methods/twoFaSettings.ts","webpack:///./src/api/gramjs/methods/settings.ts","webpack:///./src/api/gramjs/apiBuilders/payments.ts","webpack:///./src/api/gramjs/methods/payments.ts","webpack:///./src/api/gramjs/provider.ts","webpack:///./src/api/gramjs/worker/worker.ts"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","Api","require","TelegramClient","connection","tl","version","events","utils","errors","sessions","extensions","helpers","cacheApi","self","caches","Type","async","fetch","cacheName","type","request","Request","cache","open","response","match","Text","text","Blob","blob","substr","contentType","headers","Json","json","err","console","warn","save","data","cacheData","JSON","stringify","Response","put","clear","delete","downloadMedia","url","mediaFormat","start","end","client","isConnected","onProgress","mimeType","fullSize","mediaMatch","arrayBuffer","Promise","reject","Error","entityType","entityId","sizeType","replace","undefined","entity","getEntityTypeById","Number","Math","abs","localDb","chats","users","messages","documents","photos","stickerSets","includes","ApiMediaFormat","Stream","acceptsBuffer","progressCallback","workers","DOWNLOAD_WORKERS","GramJs","Message","message","media","MessageMediaPhoto","MessageMediaDocument","document","Document","attributes","some","a","DocumentAttributeSticker","getMessageMediaMimeType","size","Photo","downloadStickerSetThumb","Lottie","getMimeType","downloadProfilePhoto","download","parsed","DataUri","blobToDataUri","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","MEDIA_CACHE_MAX_BYTES","MEDIA_CACHE_DISABLED","startsWith","MEDIA_CACHE_NAME_AVATARS","MEDIA_CACHE_NAME","prepared","mediaData","URL","createObjectURL","prepareMedia","fallbackMimeType","length","subarray","reduce","result","byte","toString","GramJsLogger","setLevel","DEBUG_GRAMJS","gramJsUpdateEventBuilder","build","update","onUpdate","init","_onUpdate","sessionData","DEBUG","log","CallbackSession","onSessionUpdate","process","deviceModel","navigator","userAgent","appVersion","APP_VERSION","useWSS","additionalDcsDisabled","IS_TEST","addEventHandler","handleGramJsUpdate","updater","phoneNumber","onRequestPhoneNumber","phoneCode","onRequestCode","password","onRequestPassword","firstAndLastNames","onRequestRegistration","qrCode","onRequestQrCode","onError","onAuthError","onAuthReady","fetchCurrentUser","destroy","invokeRequest","auth","LogOut","disconnect","getClient","UpdateConnectionState","state","connected","UpdatesTooLong","GetFullUser","id","InputUserSelf","connectionState","handleTerminatedSession","shouldHandleUpdates","shouldThrow","className","invoke","updatesContainer","Updates","UpdatesCombined","updates","entities","forEach","_entities","injectUpdateEntities","error","isSlowMode","SendMessage","SendMedia","SendMultiMedia","dispatchErrorUpdate","args","downloadMediaWithClient","uploadFile","file","UPLOAD_WORKERS","updateTwoFaSettings","params","userFull","user","User","currentUser","buildApiUserFromFull","setMessageBuilderCurrentUserId","onCurrentUserUpdate","chatOrUserId","buildPeer","PeerUser","userId","PeerChannel","channelId","PeerChat","chatId","buildInputPeer","accessHash","InputPeerUser","BigInt","InputPeerChannel","InputPeerChat","buildInputPeerFromLocalDb","buildInputEntity","InputUser","InputChannel","buildInputStickerSet","InputStickerSetID","buildInputDocument","InputDocument","pick","buildInputMediaDocument","inputDocument","InputMediaDocument","buildInputPoll","pollParams","randomId","summary","quiz","poll","Poll","publicVoters","isPublic","question","answers","map","option","PollAnswer","Buffer","from","multipleChoice","InputMediaPoll","correctAnswers","solution","solutionEntities","buildMtpMessageEntity","buildFilterFromApiFolder","folder","emoticon","contacts","nonContacts","groups","channels","bots","excludeArchived","excludeMuted","excludeRead","pinnedChatIds","includedChatIds","excludedChatIds","pinnedPeers","filter","Boolean","includePeers","excludePeers","DialogFilter","title","broadcasts","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","fromId","offset","ApiMessageEntityTypes","Bold","MessageEntityBold","Italic","MessageEntityItalic","Underline","MessageEntityUnderline","Strike","MessageEntityStrike","Code","MessageEntityCode","Pre","MessageEntityPre","language","Blockquote","MessageEntityBlockquote","TextUrl","MessageEntityTextUrl","Url","MessageEntityUrl","Hashtag","MessageEntityHashtag","MentionName","InputMessageEntityMentionName","MessageEntityUnknown","calculateResultHash","ids","hash","isMessageWithMedia","MessageMediaWebPage","webpage","WebPage","photo","isServiceMessageWithMedia","action","buildChatPhotoForLocalDb","PhotoEmpty","ChatPhotoEmpty","dcId","photoId","ChatPhoto","buildInputContact","phone","firstName","lastName","InputPhoneContact","clientId","buildChatBannedRights","bannedRights","untilDate","ChatBannedRights","buildChatAdminRights","adminRights","ChatAdminRights","buildShippingInfo","info","shippingAddress","PaymentRequestedInfo","PostAddress","buildInputPrivacyKey","privacyKey","InputPrivacyKeyPhoneNumber","InputPrivacyKeyStatusTimestamp","InputPrivacyKeyProfilePhoto","InputPrivacyKeyForwards","InputPrivacyKeyChatInvite","isPeerUser","peer","isPeerChat","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","String","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","Channel","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","Chat","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","Date","now","getApiChatIdFromMtpPeer","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","omitVirtualClassFields","currentUserBannedRights","defaultBannedRights","ChatForbidden","ChannelForbidden","isRestricted","restrictionReason","restricted","buildApiChatRestrictionReason","isNotJoined","left","kicked","reason","platform","migratedTo","InputChannelEmpty","restrictionReasons","targetReason","find","buildApiChatFromPreview","preview","withForbidden","getUserName","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","UserEmpty","ChatEmpty","megagroup","getPeerKey","buildChatMember","member","ChannelParticipantBanned","ChannelParticipantLeft","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","ChannelParticipantAdmin","ChatParticipantAdmin","isAdmin","ChannelParticipantCreator","ChatParticipantCreator","isOwner","buildChatMembers","participants","ChatParticipants","ChannelParticipants","buildChatTypingStatus","SendMessageCancelAction","SendMessageTypingAction","SendMessageRecordVideoAction","SendMessageUploadVideoAction","SendMessageRecordAudioAction","SendMessageUploadAudioAction","SendMessageUploadPhotoAction","SendMessageUploadDocumentAction","SendMessageGeoLocationAction","SendMessageChooseContactAction","SendMessageGamePlayAction","SendMessageRecordRoundAction","SendMessageUploadRoundAction","UpdateUserTyping","timestamp","buildApiChatFolder","pickTruthy","buildApiChatFolderFromSuggested","description","API_UPDATE_THROTTLE","API_THROTTLE_RESET_UPDATES","Set","MEMBERS_LOAD_SLICE","window","innerHeight","PINNED_MESSAGES_LIMIT","BLOCKED_LIST_LIMIT","PROFILE_PHOTOS_LIMIT","LOCAL_MESSAGE_ID_BASE","MEMOJI_STICKER_ID","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","DELETED_COMMENTS_CHANNEL_ID","DEFAULT_LANG_PACK","localMessages","parseTl","serializeBytes","serializeDate","toSignedLittleBuffer","tlContent","schemeContent","CACHING_SUPPORTED","localStorage","extractParams","fileContent","f","constructors","functions","isFunction","push","argToBytes","x","alloc","writeInt32LE","writeDoubleLE","getBytes","getArgFromReader","reader","arg","isVector","useVectorId","readInt","temp","len","flagIndicator","readLong","readLargeInt","readDouble","tgReadString","tgReadBool","tgReadBytes","tgReadDate","skipConstructorId","tgReadObject","createClasses","classesType","classes","classParams","constructorId","subclassOfId","argsConfig","namespace","fullName","join","VirtualClass","constructor","keys","argName","this","isFlag","flags","flagIndex","idForBytes","CONSTRUCTOR_ID","writeUInt32LE","buffers","concat","values","flagCalculate","boxed","charAt","indexOf","toUpperCase","shift","readResult","definitions","fromCache","jsonCache","getItem","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","requests","loadFromTlSchemas","setItem","obj1","obj2","assign","mergeWithNamespaces","buildApiFromTlSchema","fetchChats","limit","offsetDate","archived","withPinned","GetDialogs","offsetPeer","InputPeerEmpty","excludePinned","resultPinned","GetPinnedDialogs","DialogsNotModified","updateLocalDb","lastMessagesByChatId","buildCollectionByKey","buildApiMessage","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","Dialog","chat","lastMessage","pinned","draft","formattedText","replyingToId","buildMessageDraft","buildApiUser","chatIds","totalChatCount","DialogsSlice","count","fetchFullChat","GetFullChannel","channel","fullChat","ChannelFull","about","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","inviteLink","ChatInviteExported","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","fullInfo","slowMode","seconds","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","GetFullChat","ChatFull","getFullChatInfo","searchChats","query","Search","q","localPeerIds","myResults","allChats","allUsers","isSelf","localChats","localUsers","u","globalChats","globalUsers","fetchChat","mtpUser","GetUsers","help","GetSupport","requestChatUpdate","GetPeerDialogs","peers","InputDialogPeer","saveDraft","replyToMsgId","SaveDraft","clearDraft","updateChatMutedState","account","UpdateNotifySettings","InputNotifyPeer","settings","InputPeerNotifySettings","createChannel","CreateChannel","broadcast","newChannel","InviteToChannel","joinChannel","JoinChannel","leaveChannel","LeaveChannel","deleteChannel","DeleteChannel","createGroupChat","CreateChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","EditPhoto","InputChatUploadedPhoto","EditChatPhoto","toggleChatPinned","shouldBePinned","ToggleDialogPin","isPinned","toggleChatArchived","folders","EditPeerFolders","folderPeers","InputFolderPeer","fetchChatFolders","GetDialogFilters","byId","orderedIds","fetchRecommendedChatFolders","results","GetSuggestedDialogFilters","editChatFolder","folderUpdate","UpdateDialogFilter","deleteChatFolder","isActionSuccessful","recommendedChatFolders","toggleDialogUnread","MarkDialogUnread","unread","getChatByUsername","ResolveUsername","togglePreHistoryHidden","isEnabled","TogglePreHistoryHidden","enabled","updateChatDefaultBannedRights","EditChatDefaultBannedRights","updateChatMemberBannedRights","participant","EditBanned","updateChatAdmin","EditAdmin","updateChatTitle","EditTitle","EditChatTitle","updateChatAbout","EditChatAbout","toggleSignatures","ToggleSignatures","memberFilter","ChannelParticipantsKicked","ChannelParticipantsAdmins","ChannelParticipantsRecent","GetParticipants","ChannelParticipantsNotModified","fetchGroupsForDiscussion","GetGroupsForDiscussion","setDiscussionGroup","SetDiscussionGroup","group","migrateChat","MigrateChat","openChatByInvite","CheckChatInvite","ChatInvite","ImportChatInvite","store","addMessageToLocalDb","crypto","little","signed","randBuffer","bytesNumber","reverse","bigInt","floor","subtract","pow","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","ceil","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","generateRandomLong","mod","crc32","buf","k","makeCRCTable","isBuffer","crc","index","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","all","slice","iv","sha256","bigIntMod","remainder","add","modExp","b","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","max","random","sleep","ms","resolve","setTimeout","getByteArray","integer","bits","byteLength","convertToLittle","correct","writeUInt32BE","CURRENCIES","USD","EUR","GBP","JPY","RUB","UAH","INR","AED","getCurrencySign","currency","currentUserId","localMessageCounter","_currentUserId","mtpMessage","resolveMessageApiChatId","MessageService","buildApiMessageWithChatId","buildApiMessageFromShort","out","buildApiMessageFromShortChat","buildApiMessageFromNotification","notification","currentDate","localId","content","buildMessageMediaContent","sticker","contact","buildMessageTextContent","inboxDate","isOutgoing","isChatWithSelf","post","fwdFrom","senderId","isChannelPost","MessageActionEmpty","targetUserId","targetChatId","MessageActionChatCreate","MessageActionChatEditTitle","MessageActionChatEditPhoto","MessageActionChatDeletePhoto","MessageActionChatAddUser","MessageActionChatDeleteUser","MessageActionChatJoinedByLink","MessageActionChannelCreate","MessageActionChatMigrateTo","MessageActionChannelMigrateFrom","MessageActionPinMessage","MessageActionHistoryClear","MessageActionPhoneCall","video","duration","mins","round","MessageActionContactSignUp","MessageActionPaymentSent","currencySign","amount","totalAmount","toFixed","MessageActionGroupCall","addPhotoToLocalDb","buildApiPhoto","buildAction","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","messageId","replyMarkup","ReplyKeyboardMarkup","ReplyInlineMarkup","markup","rows","buttons","button","KeyboardButton","KeyboardButtonUrl","KeyboardButtonCallback","KeyboardButtonRequestPoll","KeyboardButtonBuy","MessageMediaInvoice","receiptMsgId","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","ReplyKeyboardHide","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","DraftMessageEmpty","buildStickerFromDocument","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","attr","DocumentAttributeAudio","voice","fileName","getFilenameFromDocument","buildAudio","waveform","Array","buildVoice","buildApiDocument","buildDocumentFromMedia","MessageMediaContact","buildContact","MessageMediaPoll","buildPoll","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","buildInvoice","buildInvoiceFromMedia","DocumentEmpty","thumbs","videoAttr","DocumentAttributeVideo","gifAttr","DocumentAttributeAnimated","w","width","h","height","supportsStreaming","roundMessage","isRound","isGif","thumbnail","buildApiThumbnailFromStripped","pollResults","rawAnswers","answer","fromCharCode","buildPollResults","rawResults","totalVoters","recentVoters","recentVoterIds","chosen","voters","isChosen","isCorrect","votersCount","sizes","PhotoSize","buildApiPhotoSize","hasDocument","defaultBase","filenameAttribute","DocumentAttributeFilename","extension","split","buildLocalMessage","replyingTo","attachment","gif","scheduledAt","filename","blobUrl","previewBlobUrl","quick","dataUri","inputWaveform","interpolateArray","buildUploadingMedia","isChannel","buildNewPoll","isScheduled","buildForwardedMessage","toChat","isAudio","asIncomingInChatWithSelf","sendingState","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","fetchMessages","pagination","RequestClass","MAIN_THREAD_ID","GetHistory","GetReplies","msgId","MessagesNotModified","threadInfos","fetchMessage","GetMessages","InputMessageID","MessageEmpty","MESSAGE_DELETED","queue","sendMessage","isSilent","noWebPage","localMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","UploadMedia","fileReference","InputMediaPhoto","InputPhoto","fetchInputMedia","InputSingleMedia","multiMedia","scheduleDate","sendGroupedMedia","noWebpage","editMessage","messageUpdate","mtpEntities","EditMessage","rescheduleMessage","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","InputMediaUploadedPhoto","InputMediaUploadedDocument","pinMessage","isUnpin","isOneSide","UpdatePinnedMessage","unpin","pmOneside","unpinAllMessages","UnpinAllMessages","deleteMessages","messageIds","shouldDeleteForAll","DeleteMessages","revoke","deleteScheduledMessages","DeleteScheduledMessages","deleteHistory","DeleteHistory","just_clear","markMessageListRead","ReadHistory","ReadDiscussion","requestThreadInfoUpdate","markMessagesRead","ReadMessageContents","topMessageResult","repliesResult","GetDiscussionMessage","offsetId","addOffset","discussionChatId","topMessageId","ChannelMessages","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","InputMessagesFilterPhotoVideo","InputMessagesFilterDocument","InputMessagesFilterUrl","InputMessagesFilterMusic","InputMessagesFilterVoice","InputMessagesFilterChatPhotos","InputMessagesFilterEmpty","topMsgId","nextOffsetId","totalCount","MessagesSlice","searchMessagesGlobal","offsetRate","SearchGlobal","nextRate","fetchWebPagePreview","GetWebPagePreview","sendPollVote","options","SendVote","loadPollOptionResults","shouldResetVoters","GetPollVotes","votes","vote","nextOffset","forwardMessages","fromChat","randomIds","ForwardMessages","fromPeer","toPeer","findFirstMessageIdAfterDate","fetchScheduledHistory","GetScheduledHistory","sendScheduledMessages","SendScheduledMessages","fetchMessageLink","ExportMessageLink","grouped","thread","fetchPinnedMessages","InputMessagesFilterPinned","base64","ieee754","isArray","kMaxLength","TYPED_ARRAY_SUPPORT","createBuffer","that","RangeError","Uint8Array","__proto__","encodingOrOffset","allocUnsafe","TypeError","ArrayBuffer","array","byteOffset","fromArrayLike","fromArrayBuffer","string","encoding","isEncoding","actual","write","fromString","obj","checked","copy","val","fromObject","assertSize","isView","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","isNaN","arrayIndexOf","lastIndexOf","arr","indexSize","arrLength","valLength","read","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parseInt","utf8Write","blitBuffer","asciiWrite","str","charCodeAt","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","res","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","apply","decodeCodePointsArray","SlowBuffer","INSPECT_MAX_BYTES","global","foo","e","typedArraySupport","poolSize","_augment","species","configurable","fill","allocUnsafeSlow","_isBuffer","compare","y","list","pos","swap16","swap32","swap64","arguments","equals","inspect","target","thisStart","thisEnd","thisCopy","targetCopy","isFinite","toJSON","_arr","ret","toHex","bytes","checkOffset","ext","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeIntLE","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleBE","targetStart","set","code","INVALID_BASE64_RE","Infinity","leadSurrogate","toByteArray","trim","stringtrim","base64clean","src","dst","mtpUserFull","commonChatsCount","pinnedMsgId","botInfo","bio","pinnedMessageId","botDescription","UserProfilePhoto","mutualContact","isContact","buildApiUserType","status","buildApiUserStatus","bot","deleted","mtpStatus","UserStatusEmpty","UserStatusOnline","expires","UserStatusOffline","wasOnline","UserStatusRecently","UserStatusLastWeek","collection","byKey","BASE","MAX_INT","MAX_INT_ARR","smallToArray","supportsNativeBigInt","Integer","v","radix","alphabet","caseSensitive","parseBase","parseValue","BigInteger","sign","isSmall","SmallInteger","NativeBigInt","isPrecise","arrayToSmall","compareAbs","createArray","truncate","sum","l_a","l_b","carry","base","addAny","addSmall","difference","a_l","b_l","borrow","subtractSmall","multiplyLong","product","a_i","multiplySmall","shiftLeft","multiplySmallAndArray","square","divModSmall","lambda","divisor","quotient","divModAny","negate","comparison","quotientDigit","divisorMostSignificantDigit","divMod1","guess","xlen","highx","highy","check","part","unshift","divMod2","qSign","mSign","isBasicPrime","isUnit","isEven","isDivisibleBy","millerRabinTest","nPrev","prev","next","modPow","plus","subtractAny","minus","small","l1","l2","multiplyKaratsuba","ac","bd","abcd","times","_multiplyBySmall","divmod","over","_0","_1","_2","isNegative","exp","isZero","modInv","isPositive","isOdd","compareTo","notEquals","neq","gt","lt","greaterOrEquals","geq","lesserOrEquals","leq","isPrime","strict","logN","toJSNumber","isProbablePrime","iterations","rng","randBetween","lastT","lastR","newT","newR","powersOfTwo","powers2Length","highestPower2","shift_isSmall","bitwise","fn","xSign","ySign","xRem","not","yRem","xDigit","yDigit","xDivMod","yDivMod","remQuo","or","xor","roughLOB","gcd","integerLogarithm","tmp","absBase","alphabetValues","digits","parseBaseFromArray","toBase","valueOf","neg","digit","toBaseString","parseStringValue","decimalPlace","parseNumberValue","toArray","minusOne","lcm","isInstance","usedRNG","low","range","top","fromArray","messageFullId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","buildAuthStateUpdate","isCodeViaApp","hint","token","btoa","FloodWaitError","hours","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","bytesToDataUri","shouldOmitPrefix","instance","SUBCLASS_OF_ID","classType","rest","pathBytesToSvg","path","num","buildPath","DEFAULT_THUMB_SIZE","thumb","PhotoStrippedSize","realSizes","strippedPhotoToJpg","buildApiThumbnailFromCached","photoSize","buildApiThumbnailFromPath","sizeAttribute","PhotoSizeProgressive","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","InputPeerSelf","UserFull","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","ipAddress","port","api","stickerAttribute","DocumentAttributeImageSize","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","PhotoCachedSize","pathThumb","PhotoPathSize","stickerSetId","stickerSetAccessHash","buildStickerSet","animated","installedDate","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","StickerSetMultiCovered","covers","cover","coverSticker","ReadCancelledError","super","TypeNotFoundError","invalidConstructorId","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","SecurityError","BadMessageError","errorMessage","ErrorMessages","16","17","18","19","20","32","33","34","35","48","64","CdnFileTamperedError","buildApiWallpaper","wallpaper","WallPaperNoFile","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyKey","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","PrivacyValueAllowAll","PrivacyValueAllowContacts","PrivacyValueDisallowContacts","PrivacyValueDisallowAll","PrivacyValueAllowUsers","PrivacyValueDisallowUsers","PrivacyValueAllowChatParticipants","PrivacyValueDisallowChatParticipants","coreObjects","tlobjects","stream","_last","readByte","readFloat","getBuffer","padding","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","sentMessageIds","originRequest","disconnected","broken","UpdateNewMessage","UpdateNewScheduledMessage","UpdateNewChannelMessage","UpdateShortChatMessage","UpdateShortMessage","UpdateServiceNotification","has","localDbChatId","newProfilePhoto","UpdateEditMessage","UpdateEditChannelMessage","UpdateDeleteMessages","UpdateDeleteScheduledMessages","UpdateDeleteChannelMessages","existingIds","missingIds","profilePhotoIds","UpdateMessageID","UpdateShortSentMessage","newContent","isAlreadySent","UpdateReadMessagesContents","UpdateChannelReadMessagesContents","UpdateMessagePoll","pollId","apiPoll","pollUpdate","UpdateMessagePollVote","UpdateChannelMessageViews","UpdateReadHistoryInbox","stillUnreadCount","UpdateReadHistoryOutbox","UpdateReadChannelInbox","UpdateReadChannelOutbox","UpdateDialogPinned","DialogPeer","UpdatePinnedDialogs","order","dp","UpdateFolderPeers","folderPeer","UpdateDialogFilterOrder","UpdateChatParticipants","replacedMembers","UpdateChatParticipantAdd","addedMember","UpdateChatParticipantDelete","deletedMemberId","UpdatePinnedMessages","UpdatePinnedChannelMessages","NotifyPeer","showPreviews","sound","shouldShowPreviews","UpdateChatUserTyping","typingStatus","UpdateChannelUserTyping","UpdateChannel","UpdateDialogUnreadMark","UpdateChatDefaultBannedRights","UpdateUserStatus","UpdateUserName","updatedUser","UpdateUserPhoto","UpdateUserPhone","UpdatePeerSettings","peerType","UpdatePeerBlocked","isBlocked","blocked","UpdatePrivacy","UpdateContactsReset","UpdateFavedStickers","Session","_serverAddress","_dcId","_port","_takeoutId","_updateStates","_authKey","setDC","serverAddress","BinaryReader","AuthKey","_key","_hash","auxHash","keyId","getKey","shaData","other","RPCError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","capture","throttle","shouldRunFirst","interval","isPending","_args","setInterval","clearInterval","throttleWithTickEnd","throttleWith","onTickEnd","schedulerFn","waiting","cb","then","pause","checkPrimeAndGood","primeBytes","g","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","computeHash","algo","salt1","salt2","salt","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","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","GZIPPacked","contentRelated","gzipped","toBytes","input","gzip","ungzip","fitCount","peak","newData","springFactor","leftFiller","rightFiller","idx","File","fileBits","FileReader","onload","onerror","readAsDataURL","lastModified","blobToFile","fetchBlob","AES","default","i2ab","ab2i","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","plainText","encrypt","encrypted","Hash","algorithm","subtle","createCipheriv","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","ServerError","TimedOutError","TLMessage","seqNo","MessageContainer","containerLength","before","tlMessage","PromisedWebSockets","AsyncQueue","Connection","ip","loggers","_ip","_log","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","debug","PacketCodecClass","connect","_initConn","_connect","_sendLoop","_recvLoop","pop","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","MemorySession","sessionInfo","_authKeys","_sessionString","_storageKey","_loadFromSessionString","_fetchFromCache","mainDcId","hashes","skipUpdateStorage","_updateStorage","getAuthKey","setAuthKey","authKey","getSessionData","asHex","mainDcIdStr","mainDcKey","setKey","_saveToCache","_delete","1","TYPED_OK","Uint16Array","Int32Array","_has","sources","source","shrinkBuf","fnTyped","arraySet","dest","src_offs","dest_offs","flattenChunks","chunks","chunk","fnUntyped","setTyped","on","Buf8","Buf16","Buf32","2","STR_APPLY_OK","STR_APPLY_UIA_OK","__","_utf8len","buf2binstring","string2buf","c2","m_pos","str_len","buf_len","binstring2buf","buf2string","c_len","utf16buf","utf8border","3","adler","s1","s2","4","Z_NO_FLUSH","Z_PARTIAL_FLUSH","Z_SYNC_FLUSH","Z_FULL_FLUSH","Z_FINISH","Z_BLOCK","Z_TREES","Z_OK","Z_STREAM_END","Z_NEED_DICT","Z_ERRNO","Z_STREAM_ERROR","Z_DATA_ERROR","Z_BUF_ERROR","Z_NO_COMPRESSION","Z_BEST_SPEED","Z_BEST_COMPRESSION","Z_DEFAULT_COMPRESSION","Z_FILTERED","Z_HUFFMAN_ONLY","Z_RLE","Z_FIXED","Z_DEFAULT_STRATEGY","Z_BINARY","Z_TEXT","Z_UNKNOWN","Z_DEFLATED","5","table","makeTable","6","time","xflags","os","extra","extra_len","comment","hcrc","done","7","strm","_in","last","_out","beg","dmax","wsize","whave","wnext","s_window","hold","lcode","dcode","lmask","dmask","here","op","dist","from_source","output","next_in","avail_in","next_out","avail_out","lencode","distcode","lenbits","distbits","dolen","msg","dodist","sane","8","adler32","inflate_fast","inflate_table","zswap32","InflateState","wrap","havedict","total","head","wbits","ncode","nlen","ndist","have","lens","work","lendyn","distdyn","back","was","inflateResetKeep","total_in","total_out","inflateReset","inflateReset2","windowBits","inflateInit2","lenfix","distfix","virgin","fixedtables","sym","updatewindow","inflateInit","flush","here_bits","here_op","here_val","last_bits","last_op","last_val","opts","hbuf","inf_leave","data_type","inflateEnd","inflateGetHeader","inflateSetDictionary","dictionary","dictLength","inflateInfo","9","lbase","lext","dbase","dext","lens_index","codes","table_index","incr","mask","root","curr","drop","used","huff","base_index","MAXBITS","offs","extra_index","10","0","11","zlib_inflate","strings","ZStream","GZheader","Inflate","chunkSize","opt","raw","ended","inflator","_mode","next_out_utf8","tail","utf8str","allowBufError","onEnd","onData","inflateRaw","Logger","BinaryWriter","MessagePacker","Function","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","layer","methods","ignoreIds","objAll","objByName","objByType","commentIndex","followingTypes","dt","getTime","Si","T1","Uint32Array","T2","T3","T4","T5","T6","T7","T8","right","x2","x4","tEnc","tDec","xInv","computeTables","encKey","decKey","rcon","_message","a2","b2","rounds","decrypt","AES_IGE","blockSize","cipher","cipherText","prevX","prevY","yXOR","AES_IGE$1","incrementCounter","_level","level","isBrowser","browser","__nwjs","colors","messageFormat","canSend","levels","format","toISOString","color","UserMigrateError","newDc","PhoneMigrateError","SlowModeWaitError","FloodTestPhoneWaitError","FileMigrateError","NetworkMigrateError","EmailUnconfirmedError","codeLength","LAYER","MtProtoPlainSender","MTProtoState","Helpers","doAuthentication","RPCResult","RequestState","MsgsAck","upload","MsgsStateInfo","Pong","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","MTProtoSender","DEFAULT_OPTIONS","_connection","logger","_retries","retries","_delay","delay","_autoReconnect","autoReconnect","_connectTimeout","connectTimeout","_authKeyCallback","authKeyCallback","_updateCallback","updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","isMainSender","_onConnectionBreak","onConnectionBreak","_user_connected","_reconnecting","_disconnected","_send_loop_handle","_recv_loop_handle","_state","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","attempt","_disconnect","send","append","promise","plain","time_offset","timeOffset","rejectAll","ack","msgIds","batch","encryptMessageData","body","recv","reconnect","decryptMessageData","_processMessage","handler","_handleUpdate","_popStates","toPop","containerId","reqMsgId","innerMessage","pong","badSalt","badMsgId","newServerSalt","states","extend","badMsg","errorCode","updateTimeOffset","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","_getNewMsgId","IGE","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","afterId","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","encryptIge","decryptIge","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","correctMsgId","bad","old","AESIGE","ige","RpcError","innerCode","Factorizator","RSA","sender","nonce","resPQ","ReqPqMulti","ResPQ","pq","factorize","pqInnerData","PQInnerData","targetFingerprint","fingerprint","serverPublicKeyFingerprints","serverDhParams","ReqDHParams","publicKeyFingerprint","encryptedData","ServerDHParamsOk","ServerDHParamsFail","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","ServerDHInnerData","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","ClientDHInnerData","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","SetClientDHParams","nonceTypes","DhGenOk","DhGenRetry","DhGenFail","nonceNumber","calcNewNonceHash","_queue","_pendingStates","_ready","setReady","catch","finally","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","after","writeDataAsMessage","getValue","requestState","_stream","MTProtoPlainSender","ConnectionTCPFull","ConnectionTCPAbridged","ConnectionTCPObfuscated","Mutex","mutex","WebSocketClient","w3cwebsocket","closeError","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","addEventListener","onmessage","release","acquire","canGet","resolveGet","canPush","resolvePush","returned","AbridgedPacketCodec","props","obfuscateTag","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","keywords","ok","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","answerCallbackButton","GetBotCallbackAnswer","b64","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","parts","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","LN2","webpackPolyfill","deprecate","paths","children","i2abLow","int","i2abBig","ab2iLow","ab","ab2iBig","isBigEndian","s2i","authFlow","checkAuthorization","downloadFile","sizeTypes","apiId","apiHash","_useIPV6","useIPV6","baseLogger","floodSleepLimit","_eventBuilders","_phoneCodeHash","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_floodWaitedRequests","_initWith","InvokeWithLayer","InitConnection","systemVersion","langCode","langPack","systemLangCode","_config","phoneCodeHashes","_borrowedSenderPromises","_additionalDcsDisabled","_initSession","_sender","GetConfig","_updateLoop","load","attempts","Ping","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","race","_lastRequest","GetState","DC","_cleanupBorrowedSender","_borrowExportedSender","senderPromise","_createExportedSender","dc","ExportAuthorization","req","ImportAuthorization","inputLocation","messageOrMedia","_downloadPhoto","_downloadDocument","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoSizeEmpty","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","_switchDC","authParams","apiCredentials","fileParams","callback","event","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","sequentialUpdates","endianness","hostname","location","loadavg","uptime","freemem","MAX_VALUE","totalmem","cpus","networkInterfaces","getNetworkInterfaces","arch","tmpdir","tmpDir","EOL","homedir","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","clearTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","ys","condition","PUBLIC_KEYS","_serverKeys","keyInfo","rand","toEncrypt","Mutex_1","_pending","isLocked","_this","ticket","_dispatchNext","runExclusive","NativeWebSocket","_global","WebSocket","MozWebSocket","websocket_version","W3CWebSocket","uri","protocols","prop","me","signInUser","botAuthToken","ImportBotAuthorization","signInBot","phoneCodeHash","signInUserWithQrCode","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","SignIn","AuthorizationSignUpRequired","signInWithPassword","SignUp","AcceptTermsOfService","isScanningComplete","inputPromise","ExportLoginToken","exceptIds","LoginToken","updatePromise","UpdateLoginToken","result2","LoginTokenSuccess","authorization","Authorization","LoginTokenMigrateTo","migratedResult","ImportLoginToken","sendResult","SendCode","CodeSettings","SentCodeTypeSms","SentCodeTypeApp","resendResult","ResendCode","passwordSrpResult","GetPassword","passwordSrpCheck","computePasswordSrpCheck","CheckPassword","Foreman","maxWorkers","requestWorker","activeWorkers","deferred","_resolve","createDeferred","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","GetFile","precise","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","SaveBigFilePart","filePart","fileTotalParts","SaveFilePart","InputFileBig","InputFile","md5Checksum","isCheckPassword","currentPassword","newPassword","email","emailCodeCallback","onEmailCodeError","pwd","newAlgo","PasswordKdfAlgoUnknown","hasPassword","InputCheckPasswordEmpty","UpdatePasswordSettings","newSettings","PasswordInputSettings","newPasswordHash","newSecureSettings","ConfirmPasswordEmail","NewMessage","Raw","StopPropagation","EventBuilder","types","func","blacklistChats","resolved","Memory","StringSession","CacheApiSession","LocalStorageSession","IdbSession","decode","serverAddressLen","dcBuffer","addressBuffer","addressLengthBuffer","portBuffer","encode","StorageSession","cached","removeItem","idb","del","promisifyRequest","oncomplete","onsuccess","onabort","createStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","defaultGetStoreFunc","defaultGetStore","customStore","setMany","entries","entry","getMany","eachCursor","openCursor","continue","items","cursor","_sessionData","_callback","skipOnUpdate","fetchFullUser","userWithFullInfo","fetchNearestCountry","dcInfo","GetNearestDc","country","fetchTopUsers","topPeers","GetTopPeers","correspondents","TopPeers","fetchContactList","GetContacts","ContactsNotModified","savedCount","fetchUsers","updateContact","ImportContacts","deleteUser","DeleteContacts","fetchProfilePhotos","GetUserPhotos","inputGifBot","fetchStickerSets","allStickers","GetAllStickers","AllStickersNotModified","sets","fetchRecentStickers","GetRecentStickers","RecentStickersNotModified","stickers","processStickerResult","fetchFavoriteStickers","GetFavedStickers","FavedStickersNotModified","fetchFeaturedStickers","GetFeaturedStickers","FeaturedStickersNotModified","faveSticker","unfave","FaveSticker","fetchStickers","GetStickerSet","packs","acc","documentId","fetchAnimatedEmojis","InputStickerSetAnimatedEmoji","searchStickers","SearchStickerSets","FoundStickerSetsNotModified","fetchSavedGifs","GetSavedGifs","SavedGifsNotModified","gifs","processGifResult","installStickerSet","InstallStickerSet","uninstallStickerSet","UninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","GetInlineBotResults","foundGif","BotInlineMediaResult","fetchStickersForEmoji","GetStickers","StickersNotModified","fetchEmojiKeywords","fromVersion","GetEmojiKeywordsDifference","emojiKeyword","keyword","emoticons","checkChatUsername","CheckUsername","setChatUsername","UpdateUsername","updatePrivateLink","ExportChatInvite","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","onRequestEmailCode","checkPassword","clearPassword","updatePassword","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","UpdateProfile","checkUsername","updateUsername","updateProfilePhoto","UploadProfilePhoto","uploadProfilePhoto","fetchWallpapers","GetWallPapers","WallPapersNotModified","filteredWallpapers","wallpapers","WallPaper","pattern","uploadWallpaper","UploadWallPaper","WallPaperSettings","fetchBlockedContacts","GetBlocked","blockedIds","BlockedSlice","blockContact","Block","unblockContact","Unblock","fetchAuthorizations","GetAuthorizations","authorizations","terminateAuthorization","ResetAuthorization","terminateAllAuthorizations","ResetAuthorizations","fetchNotificationExceptions","GetNotifyExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","GetContactSignUpNotification","GetNotifySettings","InputNotifyUsers","InputNotifyChats","InputNotifyBroadcasts","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","SetContactSignUpNotification","updateNotificationSettings","fetchLanguages","langpack","GetLanguages","fetchLangPack","sourceLangPacks","collections","GetLangPack","fetchPrivacySettings","GetPrivacy","registerDevice","secret","RegisterDevice","tokenType","appSandbox","otherUids","unregisterDevice","UnregisterDevice","setPrivacySettings","privacyRules","allowedUsers","InputPrivacyValueAllowUsers","allowedChats","InputPrivacyValueAllowChatParticipants","blockedUsers","InputPrivacyValueDisallowUsers","blockedChats","InputPrivacyValueDisallowChatParticipants","InputPrivacyValueAllowAll","InputPrivacyValueAllowContacts","InputPrivacyValueDisallowContacts","InputPrivacyValueDisallowAll","SetPrivacy","buildShippingOptions","shippingOptions","prices","cur","label","validateRequestedInfo","requestInfo","shouldSave","payments","ValidateRequestedInfo","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","SendPaymentForm","InputPaymentCredentials","DataJSON","getPaymentForm","GetPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","GetPaymentReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initClient","flushUpdatesOnTickEnd","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","sendToOrigin","callbackState","Map","postMessage","callbackArgs","lastArg","fnName","callApi"],"mappings":";aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO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0D,EAAK63B,WACpCysD,IACgBA,EDvCPrgD,YAAa,GC0C1B","file":"8ede9bdfe3390ee397af.worker.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 111);\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","// 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(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\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 const request = new Request(key);\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet';\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number;\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) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n) {\n // eslint-disable-next-line max-len\n const mediaMatch = url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let 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.Document | GramJs.StickerSet | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (['msg', 'sticker', 'gif', 'wallpaper', 'photo'].includes(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 } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n 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.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\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 ApiMediaFormat, ApiOnProgress, ApiSessionData, 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';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\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, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n client = new TelegramClient(\n new sessions.CallbackSession(sessionData, onSessionUpdate),\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || DEFAULT_USER_AGENT,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\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\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\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 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 }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates = typeof result & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in result && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(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: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\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 buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\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: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\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 && media.webpage.photo instanceof GramJs.Photo\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function 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","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isInputPeerChannel, isInputPeerChat, isInputPeerUser, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\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 ...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: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\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 if (peerEntity instanceof GramJs.User) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason === undefined) {\n return {\n isRestricted: false,\n };\n }\n\n return {\n isRestricted: peerEntity.restricted,\n restrictionReason,\n };\n } else if (peerEntity instanceof GramJs.Chat) {\n return {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n };\n } else if (peerEntity instanceof GramJs.Channel) {\n const isRestricted = peerEntity.restricted\n && peerEntity.restrictionReason\n && peerEntity.restrictionReason.some((reason) => reason.platform === 'all');\n\n return {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n isRestricted,\n restrictionReason: buildApiChatRestrictionReason(peerEntity.restrictionReason),\n };\n }\n return {};\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\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: peerEntity.migratedTo.accessHash.toString(),\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: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\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 photo.photoId.toString();\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 : member.userId;\n\n return {\n userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : 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) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now(),\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(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).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","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 500;\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;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\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;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { 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}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n} as LocalDb;\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","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\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}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\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 updateLocalDb(result);\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n\n const lastMessagesByChatId = buildCollectionByKey(\n [...result.messages, ...(resultPinned ? resultPinned.messages : [])]\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...preparePeers(result),\n ...(resultPinned && preparePeers(resultPinned)),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = [\n ...(resultPinned ? resultPinned.dialogs : []),\n ...result.dialogs,\n ];\n\n const orderedPinnedIds: number[] = [];\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);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = [...result.users, ...(resultPinned ? resultPinned.users : [])]\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = [...result.chats, ...result.users]\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate(chat: ApiChat) {\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 lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity),\n 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: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\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 } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n } = 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\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: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? call.id.toString() : undefined,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted,\n}: {\n chat: ApiChat; isMuted: boolean;\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 : undefined }),\n }));\n\n void requestChatUpdate(chat);\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; 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: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\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: number; 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 number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights }) {\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),\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 number,\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: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n if (result instanceof GramJs.ChatInvite) {\n await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n\n return undefined;\n } else {\n return buildApiChatFromPreview(result.chat);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\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","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 {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 * 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\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\n};\n","const CURRENCIES: Record = {\n USD: '$',\n EUR: '€',\n GBP: '£',\n JPY: '¥',\n RUB: '₽',\n UAH: '₴',\n INR: '₹',\n AED: 'د.إ',\n};\n\nexport function getCurrencySign(currency: string | undefined): string {\n if (!currency) {\n return '';\n }\n return CURRENCIES[currency] || '';\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 ApiKeyboardButtons,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped, buildApiPhotoSize } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { getCurrencySign } from '../../../components/middle/helpers/getCurrencySign';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || (currentDate / 1000),\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action && buildAction(mtpMessage.action, fromId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const { inlineButtons, keyboardButtons } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty || !draft.message) {\n return undefined;\n }\n\n return {\n formattedText: buildMessageTextContent(draft.message, draft.entities),\n replyingToId: draft.replyToMsgId,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n 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 if (media.ttlSeconds) {\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 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 return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\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,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\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\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\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 const currencySign = getCurrencySign(currency);\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n description: `${currencySign}${(Number(totalAmount) / 100).toFixed(2)} ${test ? 'TEST INVOICE' : ''}`,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\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 return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'siteName',\n 'title',\n 'description',\n ]),\n photo: photo && photo instanceof GramJs.Photo\n ? {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes: photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize)\n .map(buildApiPhotoSize),\n }\n : undefined,\n // TODO support video and embed\n ...(document && { hasDocument: true }),\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let text = '';\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserId = 'users' in action\n // Api returns array of userIds, but no action currently has multiple users in it\n ? action.users && action.users[0]\n : ('userId' in action && action.userId) || undefined;\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = `%action_origin% created the group «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n text = isChannelPost\n ? `Channel renamed to «${action.title}»`\n : `%action_origin% changed group name to «${action.title}»`;\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n text = isChannelPost\n ? 'Channel photo updated'\n : '%action_origin% updated group photo';\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n text = isChannelPost\n ? 'Channel photo was deleted'\n : 'Chat photo was deleted';\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% joined the group'\n : '%action_origin% added %target_user% to the group';\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n text = !senderId || senderId === targetUserId\n ? '%target_user% left the group'\n : '%action_origin% removed %target_user% from the group';\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = '%action_origin% joined the chat from invitation link';\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Channel created';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n text = 'Migrated to %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n text = 'Migrated from %target_chat%';\n targetChatId = getApiChatIdFromMtpPeer(action);\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = '%action_origin% pinned %message%';\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'Chat history was cleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n text = `${isOutgoing ? 'Outgoing' : 'Incoming'} ${action.video ? 'Video' : 'Phone'} Call`;\n\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text += ` (${mins} min${mins > 1 ? 's' : ''})`;\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = '%action_origin% joined Telegram';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n const currencySign = getCurrencySign(action.currency);\n const amount = (Number(action.totalAmount) / 100).toFixed(2);\n text = `You successfully transferred ${currencySign}${amount} to shop for %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 = `Voice chat ended (${mins} min${mins > 1 ? 's' : ''})`;\n } else {\n text = 'Voice chat started';\n }\n } else {\n text = '%ACTION_NOT_IMPLEMENTED%';\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 targetUserId,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons\n} | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'Receipt';\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 { [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000),\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\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: Math.round(Date.now() / 1000),\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\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_IMAGE_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_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\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","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const 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 );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\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[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n}) {\n const isScheduled = message.date * 1000 > Date.now();\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 (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\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 }));\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 markMessageListRead({\n chat, threadId, maxId,\n}: {\n chat: ApiChat; threadId: number; maxId?: 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);\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;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\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\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': '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 }), 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, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\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 hash: calculateResultHash(messages.map((message) => message.id)),\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\nexport function fetchMessageLink({ chat, message }: { chat: ApiChat; message: ApiMessage }) {\n return invokeRequest(new GramJs.channels.ExportMessageLink({\n id: message.id,\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n ...(message.isInAlbum && { grouped: true }),\n ...(message.threadInfo && message.threadInfo.topMessageId !== message.id && { thread: true }),\n }));\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiUser, ApiUserStatus, ApiUserType } from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo,\n } = mtpUserFull;\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n ...(botInfo && { botDescription: botInfo.description }),\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\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: buildApiUserType(mtpUser),\n ...(firstName && { firstName }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n };\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","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","var bigInt = (function (undefined) {\r\n \"use strict\";\r\n\r\n var BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_INT = 9007199254740992,\r\n MAX_INT_ARR = smallToArray(MAX_INT),\r\n DEFAULT_ALPHABET = \"0123456789abcdefghijklmnopqrstuvwxyz\";\r\n\r\n var supportsNativeBigInt = typeof BigInt === \"function\";\r\n\r\n function Integer(v, radix, alphabet, caseSensitive) {\r\n if (typeof v === \"undefined\") return Integer[0];\r\n if (typeof radix !== \"undefined\") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);\r\n return parseValue(v);\r\n }\r\n\r\n function BigInteger(value, sign) {\r\n this.value = value;\r\n this.sign = sign;\r\n this.isSmall = false;\r\n }\r\n BigInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function SmallInteger(value) {\r\n this.value = value;\r\n this.sign = value < 0;\r\n this.isSmall = true;\r\n }\r\n SmallInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function NativeBigInt(value) {\r\n this.value = value;\r\n }\r\n NativeBigInt.prototype = Object.create(Integer.prototype);\r\n\r\n function isPrecise(n) {\r\n return -MAX_INT < n && n < MAX_INT;\r\n }\r\n\r\n function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes\r\n if (n < 1e7)\r\n return [n];\r\n if (n < 1e14)\r\n return [n % 1e7, Math.floor(n / 1e7)];\r\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\r\n }\r\n\r\n function arrayToSmall(arr) { // If BASE changes this function may need to change\r\n trim(arr);\r\n var length = arr.length;\r\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\r\n switch (length) {\r\n case 0: return 0;\r\n case 1: return arr[0];\r\n case 2: return arr[0] + arr[1] * BASE;\r\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\r\n }\r\n }\r\n return arr;\r\n }\r\n\r\n function trim(v) {\r\n var i = v.length;\r\n while (v[--i] === 0);\r\n v.length = i + 1;\r\n }\r\n\r\n function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger\r\n var x = new Array(length);\r\n var i = -1;\r\n while (++i < length) {\r\n x[i] = 0;\r\n }\r\n return x;\r\n }\r\n\r\n function truncate(n) {\r\n if (n > 0) return Math.floor(n);\r\n return Math.ceil(n);\r\n }\r\n\r\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\r\n var l_a = a.length,\r\n l_b = b.length,\r\n r = new Array(l_a),\r\n carry = 0,\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l_b; i++) {\r\n sum = a[i] + b[i] + carry;\r\n carry = sum >= base ? 1 : 0;\r\n r[i] = sum - carry * base;\r\n }\r\n while (i < l_a) {\r\n sum = a[i] + carry;\r\n carry = sum === base ? 1 : 0;\r\n r[i++] = sum - carry * base;\r\n }\r\n if (carry > 0) r.push(carry);\r\n return r;\r\n }\r\n\r\n function addAny(a, b) {\r\n if (a.length >= b.length) return add(a, b);\r\n return add(b, a);\r\n }\r\n\r\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l; i++) {\r\n sum = a[i] - base + carry;\r\n carry = Math.floor(sum / base);\r\n r[i] = sum - carry * base;\r\n carry += 1;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall) {\r\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\r\n }\r\n return new BigInteger(addAny(a, b), this.sign);\r\n };\r\n BigInteger.prototype.plus = BigInteger.prototype.add;\r\n\r\n SmallInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n if (isPrecise(a + b)) return new SmallInteger(a + b);\r\n b = smallToArray(Math.abs(b));\r\n }\r\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\r\n };\r\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\r\n\r\n NativeBigInt.prototype.add = function (v) {\r\n return new NativeBigInt(this.value + parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\r\n\r\n function subtract(a, b) { // assumes a and b are arrays with a >= b\r\n var a_l = a.length,\r\n b_l = b.length,\r\n r = new Array(a_l),\r\n borrow = 0,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < b_l; i++) {\r\n difference = a[i] - borrow - b[i];\r\n if (difference < 0) {\r\n difference += base;\r\n borrow = 1;\r\n } else borrow = 0;\r\n r[i] = difference;\r\n }\r\n for (i = b_l; i < a_l; i++) {\r\n difference = a[i] - borrow;\r\n if (difference < 0) difference += base;\r\n else {\r\n r[i++] = difference;\r\n break;\r\n }\r\n r[i] = difference;\r\n }\r\n for (; i < a_l; i++) {\r\n r[i] = a[i];\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function subtractAny(a, b, sign) {\r\n var value;\r\n if (compareAbs(a, b) >= 0) {\r\n value = subtract(a, b);\r\n } else {\r\n value = subtract(b, a);\r\n sign = !sign;\r\n }\r\n value = arrayToSmall(value);\r\n if (typeof value === \"number\") {\r\n if (sign) value = -value;\r\n return new SmallInteger(value);\r\n }\r\n return new BigInteger(value, sign);\r\n }\r\n\r\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n carry = -b,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < l; i++) {\r\n difference = a[i] + carry;\r\n carry = Math.floor(difference / base);\r\n difference %= base;\r\n r[i] = difference < 0 ? difference + base : difference;\r\n }\r\n r = arrayToSmall(r);\r\n if (typeof r === \"number\") {\r\n if (sign) r = -r;\r\n return new SmallInteger(r);\r\n } return new BigInteger(r, sign);\r\n }\r\n\r\n BigInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall)\r\n return subtractSmall(a, Math.abs(b), this.sign);\r\n return subtractAny(a, b, this.sign);\r\n };\r\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\r\n\r\n SmallInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n return new SmallInteger(a - b);\r\n }\r\n return subtractSmall(b, Math.abs(a), a >= 0);\r\n };\r\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\r\n\r\n NativeBigInt.prototype.subtract = function (v) {\r\n return new NativeBigInt(this.value - parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\r\n\r\n BigInteger.prototype.negate = function () {\r\n return new BigInteger(this.value, !this.sign);\r\n };\r\n SmallInteger.prototype.negate = function () {\r\n var sign = this.sign;\r\n var small = new SmallInteger(-this.value);\r\n small.sign = !sign;\r\n return small;\r\n };\r\n NativeBigInt.prototype.negate = function () {\r\n return new NativeBigInt(-this.value);\r\n }\r\n\r\n BigInteger.prototype.abs = function () {\r\n return new BigInteger(this.value, false);\r\n };\r\n SmallInteger.prototype.abs = function () {\r\n return new SmallInteger(Math.abs(this.value));\r\n };\r\n NativeBigInt.prototype.abs = function () {\r\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\r\n }\r\n\r\n\r\n function multiplyLong(a, b) {\r\n var a_l = a.length,\r\n b_l = b.length,\r\n l = a_l + b_l,\r\n r = createArray(l),\r\n base = BASE,\r\n product, carry, i, a_i, b_j;\r\n for (i = 0; i < a_l; ++i) {\r\n a_i = a[i];\r\n for (var j = 0; j < b_l; ++j) {\r\n b_j = b[j];\r\n product = a_i * b_j + r[i + j];\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n r[i + j + 1] += carry;\r\n }\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n carry = 0,\r\n product, i;\r\n for (i = 0; i < l; i++) {\r\n product = a[i] * b + carry;\r\n carry = Math.floor(product / base);\r\n r[i] = product - carry * base;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n function shiftLeft(x, n) {\r\n var r = [];\r\n while (n-- > 0) r.push(0);\r\n return r.concat(x);\r\n }\r\n\r\n function multiplyKaratsuba(x, y) {\r\n var n = Math.max(x.length, y.length);\r\n\r\n if (n <= 30) return multiplyLong(x, y);\r\n n = Math.ceil(n / 2);\r\n\r\n var b = x.slice(n),\r\n a = x.slice(0, n),\r\n d = y.slice(n),\r\n c = y.slice(0, n);\r\n\r\n var ac = multiplyKaratsuba(a, c),\r\n bd = multiplyKaratsuba(b, d),\r\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\r\n\r\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\r\n trim(product);\r\n return product;\r\n }\r\n\r\n // The following function is derived from a surface fit of a graph plotting the performance difference\r\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\r\n function useKaratsuba(l1, l2) {\r\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\r\n }\r\n\r\n BigInteger.prototype.multiply = function (v) {\r\n var n = parseValue(v),\r\n a = this.value, b = n.value,\r\n sign = this.sign !== n.sign,\r\n abs;\r\n if (n.isSmall) {\r\n if (b === 0) return Integer[0];\r\n if (b === 1) return this;\r\n if (b === -1) return this.negate();\r\n abs = Math.abs(b);\r\n if (abs < BASE) {\r\n return new BigInteger(multiplySmall(a, abs), sign);\r\n }\r\n b = smallToArray(abs);\r\n }\r\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\r\n return new BigInteger(multiplyKaratsuba(a, b), sign);\r\n return new BigInteger(multiplyLong(a, b), sign);\r\n };\r\n\r\n BigInteger.prototype.times = BigInteger.prototype.multiply;\r\n\r\n function multiplySmallAndArray(a, b, sign) { // a >= 0\r\n if (a < BASE) {\r\n return new BigInteger(multiplySmall(b, a), sign);\r\n }\r\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\r\n }\r\n SmallInteger.prototype._multiplyBySmall = function (a) {\r\n if (isPrecise(a.value * this.value)) {\r\n return new SmallInteger(a.value * this.value);\r\n }\r\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\r\n };\r\n BigInteger.prototype._multiplyBySmall = function (a) {\r\n if (a.value === 0) return Integer[0];\r\n if (a.value === 1) return this;\r\n if (a.value === -1) return this.negate();\r\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\r\n };\r\n SmallInteger.prototype.multiply = function (v) {\r\n return parseValue(v)._multiplyBySmall(this);\r\n };\r\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\r\n\r\n NativeBigInt.prototype.multiply = function (v) {\r\n return new NativeBigInt(this.value * parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\r\n\r\n function square(a) {\r\n //console.assert(2 * BASE * BASE < MAX_INT);\r\n var l = a.length,\r\n r = createArray(l + l),\r\n base = BASE,\r\n product, carry, i, a_i, a_j;\r\n for (i = 0; i < l; i++) {\r\n a_i = a[i];\r\n carry = 0 - a_i * a_i;\r\n for (var j = i; j < l; j++) {\r\n a_j = a[j];\r\n product = 2 * (a_i * a_j) + r[i + j] + carry;\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n }\r\n r[i + l] = carry;\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.square = function () {\r\n return new BigInteger(square(this.value), false);\r\n };\r\n\r\n SmallInteger.prototype.square = function () {\r\n var value = this.value * this.value;\r\n if (isPrecise(value)) return new SmallInteger(value);\r\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\r\n };\r\n\r\n NativeBigInt.prototype.square = function (v) {\r\n return new NativeBigInt(this.value * this.value);\r\n }\r\n\r\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n base = BASE,\r\n result = createArray(b.length),\r\n divisorMostSignificantDigit = b[b_l - 1],\r\n // normalization\r\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\r\n remainder = multiplySmall(a, lambda),\r\n divisor = multiplySmall(b, lambda),\r\n quotientDigit, shift, carry, borrow, i, l, q;\r\n if (remainder.length <= a_l) remainder.push(0);\r\n divisor.push(0);\r\n divisorMostSignificantDigit = divisor[b_l - 1];\r\n for (shift = a_l - b_l; shift >= 0; shift--) {\r\n quotientDigit = base - 1;\r\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\r\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\r\n }\r\n // quotientDigit <= base - 1\r\n carry = 0;\r\n borrow = 0;\r\n l = divisor.length;\r\n for (i = 0; i < l; i++) {\r\n carry += quotientDigit * divisor[i];\r\n q = Math.floor(carry / base);\r\n borrow += remainder[shift + i] - (carry - q * base);\r\n carry = q;\r\n if (borrow < 0) {\r\n remainder[shift + i] = borrow + base;\r\n borrow = -1;\r\n } else {\r\n remainder[shift + i] = borrow;\r\n borrow = 0;\r\n }\r\n }\r\n while (borrow !== 0) {\r\n quotientDigit -= 1;\r\n carry = 0;\r\n for (i = 0; i < l; i++) {\r\n carry += remainder[shift + i] - base + divisor[i];\r\n if (carry < 0) {\r\n remainder[shift + i] = carry + base;\r\n carry = 0;\r\n } else {\r\n remainder[shift + i] = carry;\r\n carry = 1;\r\n }\r\n }\r\n borrow += carry;\r\n }\r\n result[shift] = quotientDigit;\r\n }\r\n // denormalization\r\n remainder = divModSmall(remainder, lambda)[0];\r\n return [arrayToSmall(result), arrayToSmall(remainder)];\r\n }\r\n\r\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/\r\n // Performs faster than divMod1 on larger input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n result = [],\r\n part = [],\r\n base = BASE,\r\n guess, xlen, highx, highy, check;\r\n while (a_l) {\r\n part.unshift(a[--a_l]);\r\n trim(part);\r\n if (compareAbs(part, b) < 0) {\r\n result.push(0);\r\n continue;\r\n }\r\n xlen = part.length;\r\n highx = part[xlen - 1] * base + part[xlen - 2];\r\n highy = b[b_l - 1] * base + b[b_l - 2];\r\n if (xlen > b_l) {\r\n highx = (highx + 1) * base;\r\n }\r\n guess = Math.ceil(highx / highy);\r\n do {\r\n check = multiplySmall(b, guess);\r\n if (compareAbs(check, part) <= 0) break;\r\n guess--;\r\n } while (guess);\r\n result.push(guess);\r\n part = subtract(part, check);\r\n }\r\n result.reverse();\r\n return [arrayToSmall(result), arrayToSmall(part)];\r\n }\r\n\r\n function divModSmall(value, lambda) {\r\n var length = value.length,\r\n quotient = createArray(length),\r\n base = BASE,\r\n i, q, remainder, divisor;\r\n remainder = 0;\r\n for (i = length - 1; i >= 0; --i) {\r\n divisor = remainder * base + value[i];\r\n q = truncate(divisor / lambda);\r\n remainder = divisor - q * lambda;\r\n quotient[i] = q | 0;\r\n }\r\n return [quotient, remainder | 0];\r\n }\r\n\r\n function divModAny(self, v) {\r\n var value, n = parseValue(v);\r\n if (supportsNativeBigInt) {\r\n return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];\r\n }\r\n var a = self.value, b = n.value;\r\n var quotient;\r\n if (b === 0) throw new Error(\"Cannot divide by zero\");\r\n if (self.isSmall) {\r\n if (n.isSmall) {\r\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\r\n }\r\n return [Integer[0], self];\r\n }\r\n if (n.isSmall) {\r\n if (b === 1) return [self, Integer[0]];\r\n if (b == -1) return [self.negate(), Integer[0]];\r\n var abs = Math.abs(b);\r\n if (abs < BASE) {\r\n value = divModSmall(a, abs);\r\n quotient = arrayToSmall(value[0]);\r\n var remainder = value[1];\r\n if (self.sign) remainder = -remainder;\r\n if (typeof quotient === \"number\") {\r\n if (self.sign !== n.sign) quotient = -quotient;\r\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\r\n }\r\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\r\n }\r\n b = smallToArray(abs);\r\n }\r\n var comparison = compareAbs(a, b);\r\n if (comparison === -1) return [Integer[0], self];\r\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\r\n\r\n // divMod1 is faster on smaller input sizes\r\n if (a.length + b.length <= 200)\r\n value = divMod1(a, b);\r\n else value = divMod2(a, b);\r\n\r\n quotient = value[0];\r\n var qSign = self.sign !== n.sign,\r\n mod = value[1],\r\n mSign = self.sign;\r\n if (typeof quotient === \"number\") {\r\n if (qSign) quotient = -quotient;\r\n quotient = new SmallInteger(quotient);\r\n } else quotient = new BigInteger(quotient, qSign);\r\n if (typeof mod === \"number\") {\r\n if (mSign) mod = -mod;\r\n mod = new SmallInteger(mod);\r\n } else mod = new BigInteger(mod, mSign);\r\n return [quotient, mod];\r\n }\r\n\r\n BigInteger.prototype.divmod = function (v) {\r\n var result = divModAny(this, v);\r\n return {\r\n quotient: result[0],\r\n remainder: result[1]\r\n };\r\n };\r\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\r\n\r\n\r\n BigInteger.prototype.divide = function (v) {\r\n return divModAny(this, v)[0];\r\n };\r\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {\r\n return new NativeBigInt(this.value / parseValue(v).value);\r\n };\r\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\r\n\r\n BigInteger.prototype.mod = function (v) {\r\n return divModAny(this, v)[1];\r\n };\r\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {\r\n return new NativeBigInt(this.value % parseValue(v).value);\r\n };\r\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\r\n\r\n BigInteger.prototype.pow = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value,\r\n value, x, y;\r\n if (b === 0) return Integer[1];\r\n if (a === 0) return Integer[0];\r\n if (a === 1) return Integer[1];\r\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.sign) {\r\n return Integer[0];\r\n }\r\n if (!n.isSmall) throw new Error(\"The exponent \" + n.toString() + \" is too large.\");\r\n if (this.isSmall) {\r\n if (isPrecise(value = Math.pow(a, b)))\r\n return new SmallInteger(truncate(value));\r\n }\r\n x = this;\r\n y = Integer[1];\r\n while (true) {\r\n if (b & 1 === 1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === 0) break;\r\n b /= 2;\r\n x = x.square();\r\n }\r\n return y;\r\n };\r\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\r\n\r\n NativeBigInt.prototype.pow = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value, b = n.value;\r\n var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);\r\n if (b === _0) return Integer[1];\r\n if (a === _0) return Integer[0];\r\n if (a === _1) return Integer[1];\r\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.isNegative()) return new NativeBigInt(_0);\r\n var x = this;\r\n var y = Integer[1];\r\n while (true) {\r\n if ((b & _1) === _1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === _0) break;\r\n b /= _2;\r\n x = x.square();\r\n }\r\n return y;\r\n }\r\n\r\n BigInteger.prototype.modPow = function (exp, mod) {\r\n exp = parseValue(exp);\r\n mod = parseValue(mod);\r\n if (mod.isZero()) throw new Error(\"Cannot take modPow with modulus 0\");\r\n var r = Integer[1],\r\n base = this.mod(mod);\r\n if (exp.isNegative()) {\r\n exp = exp.multiply(Integer[-1]);\r\n base = base.modInv(mod);\r\n }\r\n while (exp.isPositive()) {\r\n if (base.isZero()) return Integer[0];\r\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\r\n exp = exp.divide(2);\r\n base = base.square().mod(mod);\r\n }\r\n return r;\r\n };\r\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\r\n\r\n function compareAbs(a, b) {\r\n if (a.length !== b.length) {\r\n return a.length > b.length ? 1 : -1;\r\n }\r\n for (var i = a.length - 1; i >= 0; i--) {\r\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\r\n }\r\n return 0;\r\n }\r\n\r\n BigInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) return 1;\r\n return compareAbs(a, b);\r\n };\r\n SmallInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = Math.abs(this.value),\r\n b = n.value;\r\n if (n.isSmall) {\r\n b = Math.abs(b);\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n return -1;\r\n };\r\n NativeBigInt.prototype.compareAbs = function (v) {\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n a = a >= 0 ? a : -a;\r\n b = b >= 0 ? b : -b;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n\r\n BigInteger.prototype.compare = function (v) {\r\n // See discussion about comparison with Infinity:\r\n // https://github.com/peterolson/BigInteger.js/issues/61\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (this.sign !== n.sign) {\r\n return n.sign ? 1 : -1;\r\n }\r\n if (n.isSmall) {\r\n return this.sign ? -1 : 1;\r\n }\r\n return compareAbs(a, b) * (this.sign ? -1 : 1);\r\n };\r\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\r\n\r\n SmallInteger.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) {\r\n return a == b ? 0 : a > b ? 1 : -1;\r\n }\r\n if (a < 0 !== n.sign) {\r\n return a < 0 ? -1 : 1;\r\n }\r\n return a < 0 ? 1 : -1;\r\n };\r\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\r\n\r\n NativeBigInt.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\r\n\r\n BigInteger.prototype.equals = function (v) {\r\n return this.compare(v) === 0;\r\n };\r\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\r\n\r\n BigInteger.prototype.notEquals = function (v) {\r\n return this.compare(v) !== 0;\r\n };\r\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\r\n\r\n BigInteger.prototype.greater = function (v) {\r\n return this.compare(v) > 0;\r\n };\r\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\r\n\r\n BigInteger.prototype.lesser = function (v) {\r\n return this.compare(v) < 0;\r\n };\r\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\r\n\r\n BigInteger.prototype.greaterOrEquals = function (v) {\r\n return this.compare(v) >= 0;\r\n };\r\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\r\n\r\n BigInteger.prototype.lesserOrEquals = function (v) {\r\n return this.compare(v) <= 0;\r\n };\r\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\r\n\r\n BigInteger.prototype.isEven = function () {\r\n return (this.value[0] & 1) === 0;\r\n };\r\n SmallInteger.prototype.isEven = function () {\r\n return (this.value & 1) === 0;\r\n };\r\n NativeBigInt.prototype.isEven = function () {\r\n return (this.value & BigInt(1)) === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isOdd = function () {\r\n return (this.value[0] & 1) === 1;\r\n };\r\n SmallInteger.prototype.isOdd = function () {\r\n return (this.value & 1) === 1;\r\n };\r\n NativeBigInt.prototype.isOdd = function () {\r\n return (this.value & BigInt(1)) === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isPositive = function () {\r\n return !this.sign;\r\n };\r\n SmallInteger.prototype.isPositive = function () {\r\n return this.value > 0;\r\n };\r\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\r\n\r\n BigInteger.prototype.isNegative = function () {\r\n return this.sign;\r\n };\r\n SmallInteger.prototype.isNegative = function () {\r\n return this.value < 0;\r\n };\r\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\r\n\r\n BigInteger.prototype.isUnit = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isUnit = function () {\r\n return Math.abs(this.value) === 1;\r\n };\r\n NativeBigInt.prototype.isUnit = function () {\r\n return this.abs().value === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isZero = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isZero = function () {\r\n return this.value === 0;\r\n };\r\n NativeBigInt.prototype.isZero = function () {\r\n return this.value === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isDivisibleBy = function (v) {\r\n var n = parseValue(v);\r\n if (n.isZero()) return false;\r\n if (n.isUnit()) return true;\r\n if (n.compareAbs(2) === 0) return this.isEven();\r\n return this.mod(n).isZero();\r\n };\r\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\r\n\r\n function isBasicPrime(v) {\r\n var n = v.abs();\r\n if (n.isUnit()) return false;\r\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\r\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\r\n if (n.lesser(49)) return true;\r\n // we don't know if it's prime: let the other functions figure it out\r\n }\r\n\r\n function millerRabinTest(n, a) {\r\n var nPrev = n.prev(),\r\n b = nPrev,\r\n r = 0,\r\n d, t, i, x;\r\n while (b.isEven()) b = b.divide(2), r++;\r\n next: for (i = 0; i < a.length; i++) {\r\n if (n.lesser(a[i])) continue;\r\n x = bigInt(a[i]).modPow(b, n);\r\n if (x.isUnit() || x.equals(nPrev)) continue;\r\n for (d = r - 1; d != 0; d--) {\r\n x = x.square().mod(n);\r\n if (x.isUnit()) return false;\r\n if (x.equals(nPrev)) continue next;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n // Set \"strict\" to true to force GRH-supported lower bound of 2*log(N)^2\r\n BigInteger.prototype.isPrime = function (strict) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var bits = n.bitLength();\r\n if (bits <= 64)\r\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\r\n var logN = Math.log(2) * bits.toJSNumber();\r\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt(i + 2));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\r\n\r\n BigInteger.prototype.isProbablePrime = function (iterations, rng) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var t = iterations === undefined ? 5 : iterations;\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt.randBetween(2, n.minus(2), rng));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\r\n\r\n BigInteger.prototype.modInv = function (n) {\r\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\r\n while (!newR.isZero()) {\r\n q = r.divide(newR);\r\n lastT = t;\r\n lastR = r;\r\n t = newT;\r\n r = newR;\r\n newT = lastT.subtract(q.multiply(newT));\r\n newR = lastR.subtract(q.multiply(newR));\r\n }\r\n if (!r.isUnit()) throw new Error(this.toString() + \" and \" + n.toString() + \" are not co-prime\");\r\n if (t.compare(0) === -1) {\r\n t = t.add(n);\r\n }\r\n if (this.isNegative()) {\r\n return t.negate();\r\n }\r\n return t;\r\n };\r\n\r\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\r\n\r\n BigInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return subtractSmall(value, 1, this.sign);\r\n }\r\n return new BigInteger(addSmall(value, 1), this.sign);\r\n };\r\n SmallInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\r\n return new BigInteger(MAX_INT_ARR, false);\r\n };\r\n NativeBigInt.prototype.next = function () {\r\n return new NativeBigInt(this.value + BigInt(1));\r\n }\r\n\r\n BigInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return new BigInteger(addSmall(value, 1), true);\r\n }\r\n return subtractSmall(value, 1, this.sign);\r\n };\r\n SmallInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\r\n return new BigInteger(MAX_INT_ARR, true);\r\n };\r\n NativeBigInt.prototype.prev = function () {\r\n return new NativeBigInt(this.value - BigInt(1));\r\n }\r\n\r\n var powersOfTwo = [1];\r\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\r\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\r\n\r\n function shift_isSmall(n) {\r\n return Math.abs(n) <= BASE;\r\n }\r\n\r\n BigInteger.prototype.shiftLeft = function (v) {\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftRight(-n);\r\n var result = this;\r\n if (result.isZero()) return result;\r\n while (n >= powers2Length) {\r\n result = result.multiply(highestPower2);\r\n n -= powers2Length - 1;\r\n }\r\n return result.multiply(powersOfTwo[n]);\r\n };\r\n NativeBigInt.prototype.shiftLeft = function(v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value << v.value)\r\n }\r\n SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\r\n\r\n BigInteger.prototype.shiftRight = function (v) {\r\n var remQuo;\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + \" is too large for shifting.\");\r\n }\r\n if (n < 0) return this.shiftLeft(-n);\r\n var result = this;\r\n while (n >= powers2Length) {\r\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\r\n remQuo = divModAny(result, highestPower2);\r\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n n -= powers2Length - 1;\r\n }\r\n remQuo = divModAny(result, powersOfTwo[n]);\r\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n };\r\n NativeBigInt.prototype.shiftRight = function (v){\r\n v = parseValue(v)\r\n return new NativeBigInt(this.value >> v.value)\r\n }\r\n SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\r\n\r\n function bitwise(x, y, fn) {\r\n y = parseValue(y);\r\n var xSign = x.isNegative(), ySign = y.isNegative();\r\n var xRem = xSign ? x.not() : x,\r\n yRem = ySign ? y.not() : y;\r\n var xDigit = 0, yDigit = 0;\r\n var xDivMod = null, yDivMod = null;\r\n var result = [];\r\n while (!xRem.isZero() || !yRem.isZero()) {\r\n xDivMod = divModAny(xRem, highestPower2);\r\n xDigit = xDivMod[1].toJSNumber();\r\n if (xSign) {\r\n xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers\r\n }\r\n\r\n yDivMod = divModAny(yRem, highestPower2);\r\n yDigit = yDivMod[1].toJSNumber();\r\n if (ySign) {\r\n yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers\r\n }\r\n\r\n xRem = xDivMod[0];\r\n yRem = yDivMod[0];\r\n result.push(fn(xDigit, yDigit));\r\n }\r\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\r\n for (var i = result.length - 1; i >= 0; i -= 1) {\r\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\r\n }\r\n return sum;\r\n }\r\n\r\n BigInteger.prototype.not = function () {\r\n return this.negate().prev();\r\n };\r\n NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;\r\n\r\n BigInteger.prototype.and = function (n) {\r\n return bitwise(this, n, function (a, b) { return a & b; });\r\n };\r\n NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;\r\n\r\n BigInteger.prototype.or = function (n) {\r\n return bitwise(this, n, function (a, b) { return a | b; });\r\n };\r\n NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;\r\n\r\n BigInteger.prototype.xor = function (n) {\r\n return bitwise(this, n, function (a, b) { return a ^ b; });\r\n };\r\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;\r\n\r\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\r\n function roughLOB(n) { // get lowestOneBit (rough)\r\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\r\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\r\n var v = n.value,\r\n x = typeof v === \"number\" ? v | LOBMASK_I :\r\n typeof v === \"bigint\" ? v | BigInt(LOBMASK_I) :\r\n v[0] + v[1] * BASE | LOBMASK_BI;\r\n return x & -x;\r\n }\r\n\r\n function integerLogarithm(value, base) {\r\n if (base.compareTo(value) <= 0) {\r\n var tmp = integerLogarithm(value, base.square(base));\r\n var p = tmp.p;\r\n var e = tmp.e;\r\n var t = p.multiply(base);\r\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\r\n }\r\n return { p: bigInt(1), e: 0 };\r\n }\r\n\r\n BigInteger.prototype.bitLength = function () {\r\n var n = this;\r\n if (n.compareTo(bigInt(0)) < 0) {\r\n n = n.negate().subtract(bigInt(1));\r\n }\r\n if (n.compareTo(bigInt(0)) === 0) {\r\n return bigInt(0);\r\n }\r\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\r\n }\r\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\r\n\r\n function max(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.greater(b) ? a : b;\r\n }\r\n function min(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.lesser(b) ? a : b;\r\n }\r\n function gcd(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n if (a.equals(b)) return a;\r\n if (a.isZero()) return b;\r\n if (b.isZero()) return a;\r\n var c = Integer[1], d, t;\r\n while (a.isEven() && b.isEven()) {\r\n d = min(roughLOB(a), roughLOB(b));\r\n a = a.divide(d);\r\n b = b.divide(d);\r\n c = c.multiply(d);\r\n }\r\n while (a.isEven()) {\r\n a = a.divide(roughLOB(a));\r\n }\r\n do {\r\n while (b.isEven()) {\r\n b = b.divide(roughLOB(b));\r\n }\r\n if (a.greater(b)) {\r\n t = b; b = a; a = t;\r\n }\r\n b = b.subtract(a);\r\n } while (!b.isZero());\r\n return c.isUnit() ? a : a.multiply(c);\r\n }\r\n function lcm(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n return a.divide(gcd(a, b)).multiply(b);\r\n }\r\n function randBetween(a, b, rng) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n var usedRNG = rng || Math.random;\r\n var low = min(a, b), high = max(a, b);\r\n var range = high.subtract(low).add(1);\r\n if (range.isSmall) return low.add(Math.floor(usedRNG() * range));\r\n var digits = toBase(range, BASE).value;\r\n var result = [], restricted = true;\r\n for (var i = 0; i < digits.length; i++) {\r\n var top = restricted ? digits[i] : BASE;\r\n var digit = truncate(usedRNG() * top);\r\n result.push(digit);\r\n if (digit < top) restricted = false;\r\n }\r\n return low.add(Integer.fromArray(result, BASE, false));\r\n }\r\n\r\n var parseBase = function (text, base, alphabet, caseSensitive) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n text = String(text);\r\n if (!caseSensitive) {\r\n text = text.toLowerCase();\r\n alphabet = alphabet.toLowerCase();\r\n }\r\n var length = text.length;\r\n var i;\r\n var absBase = Math.abs(base);\r\n var alphabetValues = {};\r\n for (i = 0; i < alphabet.length; i++) {\r\n alphabetValues[alphabet[i]] = i;\r\n }\r\n for (i = 0; i < length; i++) {\r\n var c = text[i];\r\n if (c === \"-\") continue;\r\n if (c in alphabetValues) {\r\n if (alphabetValues[c] >= absBase) {\r\n if (c === \"1\" && absBase === 1) continue;\r\n throw new Error(c + \" is not a valid digit in base \" + base + \".\");\r\n }\r\n }\r\n }\r\n base = parseValue(base);\r\n var digits = [];\r\n var isNegative = text[0] === \"-\";\r\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\r\n var c = text[i];\r\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\r\n else if (c === \"<\") {\r\n var start = i;\r\n do { i++; } while (text[i] !== \">\" && i < text.length);\r\n digits.push(parseValue(text.slice(start + 1, i)));\r\n }\r\n else throw new Error(c + \" is not a valid character\");\r\n }\r\n return parseBaseFromArray(digits, base, isNegative);\r\n };\r\n\r\n function parseBaseFromArray(digits, base, isNegative) {\r\n var val = Integer[0], pow = Integer[1], i;\r\n for (i = digits.length - 1; i >= 0; i--) {\r\n val = val.add(digits[i].times(pow));\r\n pow = pow.times(base);\r\n }\r\n return isNegative ? val.negate() : val;\r\n }\r\n\r\n function stringify(digit, alphabet) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n if (digit < alphabet.length) {\r\n return alphabet[digit];\r\n }\r\n return \"<\" + digit + \">\";\r\n }\r\n\r\n function toBase(n, base) {\r\n base = bigInt(base);\r\n if (base.isZero()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n throw new Error(\"Cannot convert nonzero numbers to base 0.\");\r\n }\r\n if (base.equals(-1)) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n if (n.isNegative())\r\n return {\r\n value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))\r\n .map(Array.prototype.valueOf, [1, 0])\r\n ),\r\n isNegative: false\r\n };\r\n\r\n var arr = Array.apply(null, Array(n.toJSNumber() - 1))\r\n .map(Array.prototype.valueOf, [0, 1]);\r\n arr.unshift([1]);\r\n return {\r\n value: [].concat.apply([], arr),\r\n isNegative: false\r\n };\r\n }\r\n\r\n var neg = false;\r\n if (n.isNegative() && base.isPositive()) {\r\n neg = true;\r\n n = n.abs();\r\n }\r\n if (base.isUnit()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n\r\n return {\r\n value: Array.apply(null, Array(n.toJSNumber()))\r\n .map(Number.prototype.valueOf, 1),\r\n isNegative: neg\r\n };\r\n }\r\n var out = [];\r\n var left = n, divmod;\r\n while (left.isNegative() || left.compareAbs(base) >= 0) {\r\n divmod = left.divmod(base);\r\n left = divmod.quotient;\r\n var digit = divmod.remainder;\r\n if (digit.isNegative()) {\r\n digit = base.minus(digit).abs();\r\n left = left.next();\r\n }\r\n out.push(digit.toJSNumber());\r\n }\r\n out.push(left.toJSNumber());\r\n return { value: out.reverse(), isNegative: neg };\r\n }\r\n\r\n function toBaseString(n, base, alphabet) {\r\n var arr = toBase(n, base);\r\n return (arr.isNegative ? \"-\" : \"\") + arr.value.map(function (x) {\r\n return stringify(x, alphabet);\r\n }).join('');\r\n }\r\n\r\n BigInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n SmallInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n NativeBigInt.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n BigInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix !== 10) return toBaseString(this, radix, alphabet);\r\n var v = this.value, l = v.length, str = String(v[--l]), zeros = \"0000000\", digit;\r\n while (--l >= 0) {\r\n digit = String(v[l]);\r\n str += zeros.slice(digit.length) + digit;\r\n }\r\n var sign = this.sign ? \"-\" : \"\";\r\n return sign + str;\r\n };\r\n\r\n SmallInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix != 10) return toBaseString(this, radix, alphabet);\r\n return String(this.value);\r\n };\r\n\r\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\r\n\r\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\r\n\r\n BigInteger.prototype.valueOf = function () {\r\n return parseInt(this.toString(), 10);\r\n };\r\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\r\n\r\n SmallInteger.prototype.valueOf = function () {\r\n return this.value;\r\n };\r\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\r\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {\r\n return parseInt(this.toString(), 10);\r\n }\r\n\r\n function parseStringValue(v) {\r\n if (isPrecise(+v)) {\r\n var x = +v;\r\n if (x === truncate(x))\r\n return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);\r\n throw new Error(\"Invalid integer: \" + v);\r\n }\r\n var sign = v[0] === \"-\";\r\n if (sign) v = v.slice(1);\r\n var split = v.split(/e/i);\r\n if (split.length > 2) throw new Error(\"Invalid integer: \" + split.join(\"e\"));\r\n if (split.length === 2) {\r\n var exp = split[1];\r\n if (exp[0] === \"+\") exp = exp.slice(1);\r\n exp = +exp;\r\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error(\"Invalid integer: \" + exp + \" is not a valid exponent.\");\r\n var text = split[0];\r\n var decimalPlace = text.indexOf(\".\");\r\n if (decimalPlace >= 0) {\r\n exp -= text.length - decimalPlace - 1;\r\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\r\n }\r\n if (exp < 0) throw new Error(\"Cannot include negative exponent part for integers\");\r\n text += (new Array(exp + 1)).join(\"0\");\r\n v = text;\r\n }\r\n var isValid = /^([0-9][0-9]*)$/.test(v);\r\n if (!isValid) throw new Error(\"Invalid integer: \" + v);\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(sign ? \"-\" + v : v));\r\n }\r\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\r\n while (max > 0) {\r\n r.push(+v.slice(min, max));\r\n min -= l;\r\n if (min < 0) min = 0;\r\n max -= l;\r\n }\r\n trim(r);\r\n return new BigInteger(r, sign);\r\n }\r\n\r\n function parseNumberValue(v) {\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(v));\r\n }\r\n if (isPrecise(v)) {\r\n if (v !== truncate(v)) throw new Error(v + \" is not an integer.\");\r\n return new SmallInteger(v);\r\n }\r\n return parseStringValue(v.toString());\r\n }\r\n\r\n function parseValue(v) {\r\n if (typeof v === \"number\") {\r\n return parseNumberValue(v);\r\n }\r\n if (typeof v === \"string\") {\r\n return parseStringValue(v);\r\n }\r\n if (typeof v === \"bigint\") {\r\n return new NativeBigInt(v);\r\n }\r\n return v;\r\n }\r\n // Pre-define numbers in range [-999,999]\r\n for (var i = 0; i < 1000; i++) {\r\n Integer[i] = parseValue(i);\r\n if (i > 0) Integer[-i] = parseValue(-i);\r\n }\r\n // Backwards compatibility\r\n Integer.one = Integer[1];\r\n Integer.zero = Integer[0];\r\n Integer.minusOne = Integer[-1];\r\n Integer.max = max;\r\n Integer.min = min;\r\n Integer.gcd = gcd;\r\n Integer.lcm = lcm;\r\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };\r\n Integer.randBetween = randBetween;\r\n\r\n Integer.fromArray = function (digits, base, isNegative) {\r\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\r\n };\r\n\r\n return Integer;\r\n})();\r\n\r\n// Node.js check\r\nif (typeof module !== \"undefined\" && module.hasOwnProperty(\"exports\")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (typeof define === \"function\" && define.amd) {\r\n define( function () {\r\n return bigInt;\r\n });\r\n}\r\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\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 (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","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: 'Invalid Password',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\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","export 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(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\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 && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","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 <= 1572864000) { // 1500MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n\n/* CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`;\n } else if (entity.firstName) {\n return entity.firstName;\n } else if (entity.lastName) {\n return entity.lastName;\n } else {\n return '';\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\nfunction getDC(dcId) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: 'pluto.web.telegram.org',\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: 'venus.web.telegram.org',\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: 'aurora.web.telegram.org',\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: 'vesta.web.telegram.org',\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: 'flora.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","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","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n if (!stickerAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute.stickerset as GramJs.InputStickerSetID;\n const emoji = stickerAttribute.alt;\n const isAnimated = document.mimeType === 'application/x-tgsticker';\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo.id ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n hash,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs && thumbs.length),\n count,\n hash,\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","/**\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","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { pick } from '../../../util/iteratees';\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: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | 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;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\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","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","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\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();\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n 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 || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | 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 if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now();\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\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 }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(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 = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\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 ((\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[randomId.toString()];\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();\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: update.channelId,\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: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\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: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\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: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\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: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\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: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\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 const {\n silent, muteUntil, showPreviews, sound,\n } = update.notifySettings;\n\n const isMuted = silent || (typeof muteUntil === 'number' && Date.now() < muteUntil * 1000);\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isMuted,\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\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: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\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 const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent || (typeof muteUntil === 'number' && Date.now() < 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.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","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 {\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","/**\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","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\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 { 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","/* 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 { 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 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","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 * 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","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');\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 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) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\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();\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);\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() {\n this._connected = false;\n await this._recvArray.push(undefined);\n await this.socket.close();\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\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 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","/* pako 1.0.10 nodeca/pako */(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.pako = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n},{\"./common\":1}],3:[function(require,module,exports){\n'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n\n},{}],4:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n},{}],5:[function(require,module,exports){\n'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n\n},{}],6:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n\n},{}],7:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n},{}],8:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n\n},{\"../utils/common\":1,\"./adler32\":3,\"./crc32\":5,\"./inffast\":7,\"./inftrees\":9}],9:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n},{\"../utils/common\":1}],10:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n},{}],11:[function(require,module,exports){\n'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n\n},{}],\"/lib/inflate.js\":[function(require,module,exports){\n'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n\n},{\"./utils/common\":1,\"./utils/strings\":2,\"./zlib/constants\":4,\"./zlib/gzheader\":6,\"./zlib/inflate\":8,\"./zlib/messages\":10,\"./zlib/zstream\":11}]},{},[])(\"/lib/inflate.js\")\n});\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","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","var S = new Uint8Array(256);\nvar Si = new Uint8Array(256);\nvar T1 = new Uint32Array(256);\nvar T2 = new Uint32Array(256);\nvar T3 = new Uint32Array(256);\nvar T4 = new Uint32Array(256);\nvar T5 = new Uint32Array(256);\nvar T6 = new Uint32Array(256);\nvar T7 = new Uint32Array(256);\nvar T8 = new Uint32Array(256);\nfunction computeTables() {\n var d = new Uint8Array(256);\n var t = new Uint8Array(256);\n var x2;\n var x4;\n var x8;\n var s;\n var tEnc;\n var tDec;\n var x = 0;\n var xInv = 0;\n // Compute double and third tables\n for (var i = 0; i < 256; i++) {\n d[i] = i << 1 ^ (i >> 7) * 283;\n t[d[i] ^ i] = i;\n }\n for (; !S[x]; x ^= x2 || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n S[x] = s;\n Si[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n T1[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T2[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T3[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T4[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T5[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T6[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T7[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T8[s] = tDec = tDec << 24 ^ tDec >>> 8;\n xInv = t[xInv] || 1;\n }\n}\n\n/**\n * Gets a uint32 from string in big-endian order order\n */\nfunction s2i(str, pos) {\n return (str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3));\n}\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Helper function for transforming string key to Uint32Array\n */\nfunction getWords(key) {\n if (key instanceof Uint32Array) {\n return key;\n }\n if (typeof key === 'string') {\n if (key.length % 4 !== 0)\n for (var i = key.length % 4; i <= 4; i++)\n key += '\\0x00';\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4)\n buf[i / 4] = s2i(key, i);\n return buf;\n }\n if (key instanceof Uint8Array) {\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4) {\n buf[i / 4] = (key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]);\n }\n return buf;\n }\n throw new Error('Unable to create 32-bit words');\n}\nfunction xor(left, right, to) {\n if (to === void 0) { to = left; }\n for (var i = 0; i < left.length; i++)\n to[i] = left[i] ^ right[i];\n}\n\ncomputeTables();\n/**\n * Low-level AES Cipher\n */\nvar AES = /** @class */ (function () {\n function AES(_key) {\n var key = getWords(_key);\n if (key.length !== 4 && key.length !== 6 && key.length !== 8) {\n throw new Error('Invalid key size');\n }\n this.encKey = new Uint32Array(4 * key.length + 28);\n this.decKey = new Uint32Array(4 * key.length + 28);\n this.encKey.set(key);\n var rcon = 1;\n var i = key.length;\n var tmp;\n // schedule encryption keys\n for (; i < 4 * key.length + 28; i++) {\n tmp = this.encKey[i - 1];\n // apply sbox\n if (i % key.length === 0 || (key.length === 8 && i % key.length === 4)) {\n tmp = S[tmp >>> 24] << 24 ^ S[(tmp >> 16) & 255] << 16 ^ S[(tmp >> 8) & 255] << 8 ^ S[tmp & 255];\n // shift rows and add rcon\n if (i % key.length === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ (rcon << 24);\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n this.encKey[i] = this.encKey[i - key.length] ^ tmp;\n }\n // schedule decryption keys\n for (var j = 0; i; j++, i--) {\n tmp = this.encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n this.decKey[j] = tmp;\n }\n else {\n this.decKey[j] = (T5[S[tmp >>> 24]]\n ^ T6[S[(tmp >> 16) & 255]]\n ^ T7[S[(tmp >> 8) & 255]]\n ^ T8[S[tmp & 255]]);\n }\n }\n }\n AES.prototype.encrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.encKey[0];\n var b = message[1] ^ this.encKey[1];\n var c = message[2] ^ this.encKey[2];\n var d = message[3] ^ this.encKey[3];\n var rounds = this.encKey.length / 4 - 2;\n var k = 4;\n var a2;\n var b2;\n var c2;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T1[a >>> 24] ^ T2[(b >> 16) & 255] ^ T3[(c >> 8) & 255] ^ T4[d & 255] ^ this.encKey[k];\n b2 = T1[b >>> 24] ^ T2[(c >> 16) & 255] ^ T3[(d >> 8) & 255] ^ T4[a & 255] ^ this.encKey[k + 1];\n c2 = T1[c >>> 24] ^ T2[(d >> 16) & 255] ^ T3[(a >> 8) & 255] ^ T4[b & 255] ^ this.encKey[k + 2];\n d = T1[d >>> 24] ^ T2[(a >> 16) & 255] ^ T3[(b >> 8) & 255] ^ T4[c & 255] ^ this.encKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n // console.log(a, b, c, d);\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[i] = (S[a >>> 24] << 24\n ^ S[(b >> 16) & 255] << 16\n ^ S[(c >> 8) & 255] << 8\n ^ S[d & 255]\n ^ this.encKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n AES.prototype.decrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.decKey[0];\n var b = message[3] ^ this.decKey[1];\n var c = message[2] ^ this.decKey[2];\n var d = message[1] ^ this.decKey[3];\n var rounds = this.decKey.length / 4 - 2;\n var a2;\n var b2;\n var c2;\n var k = 4;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T5[a >>> 24] ^ T6[(b >> 16) & 255] ^ T7[(c >> 8) & 255] ^ T8[d & 255] ^ this.decKey[k];\n b2 = T5[b >>> 24] ^ T6[(c >> 16) & 255] ^ T7[(d >> 8) & 255] ^ T8[a & 255] ^ this.decKey[k + 1];\n c2 = T5[c >>> 24] ^ T6[(d >> 16) & 255] ^ T7[(a >> 8) & 255] ^ T8[b & 255] ^ this.decKey[k + 2];\n d = T5[d >>> 24] ^ T6[(a >> 16) & 255] ^ T7[(b >> 8) & 255] ^ T8[c & 255] ^ this.decKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[3 & -i] = (Si[a >>> 24] << 24\n ^ Si[(b >> 16) & 255] << 16\n ^ Si[(c >> 8) & 255] << 8\n ^ Si[d & 255]\n ^ this.decKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n return AES;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE = /** @class */ (function () {\n function AES_IGE(key, iv, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.key = getWords(key);\n this.iv = getWords(iv);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var prevX = this.iv.subarray(this.blockSize, this.iv.length);\n var prevY = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = text.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.encrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n cipherText[j] = y[k];\n }\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n var cipherText = getWords(message);\n var text = buf || new Uint32Array(cipherText.length);\n var prevY = this.iv.subarray(this.blockSize, this.iv.length);\n var prevX = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = cipherText.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.decrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n text[j] = y[k];\n }\n return text;\n };\n return AES_IGE;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE$1 = /** @class */ (function () {\n function AES_IGE(key, counter, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.offset = 0;\n this.key = getWords(key);\n this.counter = getWords(counter);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n if (this.counter.length !== 4) {\n throw new Error('AES-CTR mode counter must be 16 bytes length');\n }\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var offset = this.offset;\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = this.cipher.encrypt(this.counter);\n for (var j = i, k = offset; j < text.length && k < this.blockSize; j++, k++)\n cipherText[j] = x[k] ^ text[j];\n if (text.length - i >= this.blockSize)\n this.incrementCounter();\n if (offset) {\n i -= offset;\n offset = 0;\n }\n }\n this.offset = (this.offset + (text.length % 4)) % 4;\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n return this.encrypt(message, buf);\n };\n AES_IGE.prototype.incrementCounter = function () {\n // increment counter\n for (var carry = this.counter.length - 1; carry >= 0; carry--) {\n if (++this.counter[carry] < 0xFFFFFFFF)\n break; // If overflowing, it'll be 0 and we'll have to continue propagating the carry\n }\n };\n return AES_IGE;\n}());\n\nexport default AES;\nexport { AES_IGE$1 as CTR, AES_IGE as IGE };\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 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 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 {\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}\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 [/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 EmailUnconfirmedError,\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","const api = require('./api');\n\nconst LAYER = 128;\nconst tlobjects = {};\n\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 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');\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n\n/**\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 the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this._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 await Helpers.sleep(this._delay);\n }\n }\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 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 // CONTEST\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n /*\n if (!Helpers.isArrayLike(request)) {\n const state = new RequestState(request)\n this._send_queue.append(state)\n return state.promise\n } else {\n throw new Error('not supported')\n } */\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.time_offset = res.timeOffset;\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._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\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 this._log.info('Broken authorization key; resetting');\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (this._onConnectionBreak && !this._isMainSender) {\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId);\n }\n\n // We don't really need to do this if we're going to sign in again\n /* await this.authKey.setKey(null)\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(null)\n } */\n // We can disconnect at sign in\n /* await this.disconnect()\n */\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n 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 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 delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\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 this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\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 to = this._state.updateTimeOffset(message.msgId);\n this._log.info(`System clock is wrong, set time offset to ${to}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 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 delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n this._log.info('Started reconnecting');\n this._reconnect();\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 await this.connect(this._connection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\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 BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, data).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { 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","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 { 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","const BigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst RSA = require('../crypto/RSA');\nconst Helpers = require('../Helpers');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { SecurityError } = require('../errors/Common');\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 */\nasync function doAuthentication(sender, log) {\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\n const resPQ = await sender.send(new requests.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof constructors.ResPQ)) {\n throw new Error(`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 log.debug('Starting authKey generation step 2');\n // Step 2 sending: DH Exchange\n let {\n p,\n q,\n } = Factorizator.factorize(pq);\n\n // TODO Bring back after `Factorizator` fix.\n p = Helpers.getByteArray(p);\n q = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n\n const pqInnerData = new constructors.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p,\n q,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n });\n\n // sha_digest + data + random_bytes\n let cipherText;\n let targetFingerprint;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n cipherText = await RSA.encrypt(fingerprint.toString(), pqInnerData.getBytes());\n if (cipherText !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (cipherText === undefined) {\n throw new SecurityError('Step 2 could not find a valid key for fingerprints');\n }\n\n const serverDhParams = await sender.send(\n new requests.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p,\n q,\n publicKeyFingerprint: targetFingerprint,\n encryptedData: cipherText,\n }),\n );\n if (!(serverDhParams instanceof constructors.ServerDHParamsOk\n || serverDhParams instanceof constructors.ServerDHParamsFail)) {\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 constructors.ServerDHParamsFail) {\n const sh = await Helpers.sha1(Helpers.toSignedLittleBuffer(newNonce, 32)\n .slice(4, 20));\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 constructors.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 {\n key,\n iv,\n } = await Helpers.generateKeyDataFromNonce(resPQ.serverNonce, newNonce);\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 constructors.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('Step 3 Invalid server nonce in encrypted answer');\n }\n const dhPrime = Helpers.readBigIntFromBuffer(serverDhInner.dhPrime, false, false);\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(Helpers.generateRandomBytes(256), false, false);\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 constructors.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: 0, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([await Helpers.sha1(clientDhInner), clientDhInner]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new requests.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [constructors.DhGenOk, constructors.DhGenRetry, constructors.DhGenFail];\n if (!(dhGen instanceof nonceTypes[0] || dhGen instanceof nonceTypes[1] || dhGen instanceof nonceTypes[2])) {\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(`Step 3 invalid ${name} server nonce from server`);\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypes.indexOf(dhGen.constructor);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\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 constructors.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return {\n authKey,\n timeOffset,\n };\n}\n\n\nmodule.exports = doAuthentication;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('../extensions/BinaryWriter');\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 this._queue.push(state);\n this.setReady(true);\n\n if (state) {\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","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","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst doAuthentication = require('./Authenticator');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n doAuthentication,\n MTProtoSender,\n UpdateConnectionState,\n};\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() {\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 }\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) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`;\n } else {\n return `ws://${ip}:${port}/apiws`;\n }\n }\n\n connect(port, ip) {\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);\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 reject(error);\n };\n this.client.onclose = () => {\n this.resolveRead(false);\n this.closed = true;\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 const release = await mutex.acquire();\n try {\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 } finally {\n release();\n }\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\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 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","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\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?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\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?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\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 isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\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.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\n\nexport function init() {\n}\n\nexport async function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result;\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\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","/*\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","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#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = 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#f4e096c3 flags:# multiple_allowed:flags.1?true can_forward:flags.2?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param: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#bba51639 call:InputGroupCall time_ms:long scale:int = InputFileLocation;\npeerUser#9db1bc6d user_id:int = Peer;\npeerChat#bad0e5bb chat_id:int = Peer;\npeerChannel#bddde532 channel_id:int = 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#200250ba id:int = User;\nuser#938458c1 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:int 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#9ba2d800 id:int = Chat;\nchat#3bda1bde flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true id:int 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#7328bdb id:int title:string = Chat;\nchannel#d31a961e flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true id:int access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int version: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#289da732 flags:# broadcast:flags.5?true megagroup:flags.8?true id:int access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#8a1e2983 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:int 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 = ChatFull;\nchannelFull#548c3f93 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:int 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?int 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?int 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 = ChatFull;\nchatParticipant#c8d7493e user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantCreator#da13538a user_id:int = ChatParticipant;\nchatParticipantAdmin#e2d6e436 user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3f460fed chat_id:int 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#bce383d2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#cbf24940 phone_number:string first_name:string last_name:string vcard:string user_id:int = 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#a6638b9a title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#488a7337 users:Vector = MessageAction;\nmessageActionChatDeleteUser#b2ae9b0c user_id:int = MessageAction;\nmessageActionChatJoinedByLink#f89cf5e8 inviter_id:int = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#51bdb021 channel_id:int = MessageAction;\nmessageActionChannelMigrateFrom#b055eaee title:string chat_id:int = 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#76b9f11a call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#df969c2d id:int bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#8af40b25 flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#139a9a77 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int 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#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#86cadb6c chat_id:int from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int 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#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int 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#12b9417b user_id:int 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#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int 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#3f2038db flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int 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#e73547e1 flags:# query_id:long user_id:int 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#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int 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#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int 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#89893b45 channel_id:int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int 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#42f88f2c poll_id:long user_id:int options:Vector = 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#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#6b171718 flags:# channel_id:int 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#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector pts:int pts_count:int = Update;\nupdateChat#1330a196 chat_id:int = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#a45eb99b chat_id:int call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#f3b3781f flags:# chat_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#7fecb1ec flags:# channel_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#7f9488a user_id:int date:int stopped:Bool qts:int = 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#faeff833 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#1157b858 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int 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#1da7158f flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int 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;\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#4c81c1ba chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 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#e4599bbd hash:int stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = account.Authorizations;\naccount.password#ad2641f8 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 = 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#6e24fc9d flags:# revoked:flags.0?true permanent:flags.5?true link:string admin_id:int date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#f4108aa0 flags:# single_use:flags.1?true selective:flags.2?true = ReplyMarkup;\nreplyKeyboardMarkup#3502758c flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector = 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#352dca58 offset:int length:int user_id:int = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = 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#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#50a1dfd6 flags:# left:flags.0?true peer:Peer kicked_by:int 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#2e0709a5 hash:int 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#d5348d85 flags:# multiple_allowed:flags.1?true can_forward:flags.3?true title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\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#b6abc341 hash:int count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int 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#58fffcd0 pos:int user_id:int 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#8d0b2415 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:int invoice:Invoice provider_id:int 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#10b555d0 flags:# date:int bot_id:int provider_id:int 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#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int 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#a26f881b prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = 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#cac943f2 hash:long bot_id:int 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#5108d648 hash:int 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#badcc1a3 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#8427bbac = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#5086cf8 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?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#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int 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#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int 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#18f3d0f7 user_id:int messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#6014f412 user_id:int deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#31962a4c user_id:int 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#f5dd8f9d flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?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#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?int 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#c95c6654 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 id:long access_hash:long participants_count:int params:flags.0?DataJSON title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#b96b25ee 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 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 params:flags.6?DataJSON = 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#1e3e6680 user_id:int date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#dfd2330f admin_id:int 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;\n---functions---\n// Only needed functions from \\`api.tl\\` are manually copied here to reduce package size\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int 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#b1b41517 api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#3076c4bf 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.getWallPapers#aabb1763 hash:int = 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;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = 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#d4982db5 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:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec 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:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.getChats#3c6aa187 id:Vector = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = 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#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.migrateChat#15a3b8e3 chat_id:int = 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#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\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#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\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#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = 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#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = 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;\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;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\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#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = 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.exportMessageLink#e63fadeb flags:# grouped:flags.0?true thread:flags.1?true channel:InputChannel id:int = ExportedMessageLink;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n// LAYER 128\n`;","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\n`;","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst DEFAULT_IPV4_IP = 'venus.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\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 };\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 === undefined || apiHash === undefined) {\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._borrowedSenderPromises = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n }\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 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 const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log,\n );\n\n await this._sender.connect(connection);\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n this._updateLoop();\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (this.isConnected()) {\n await Helpers.sleep(3 * 1000);\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.Ping({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n })), 1500);\n }, 3, 100);\n } catch (err) {\n await this.disconnect();\n this.connect();\n\n return;\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n }\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._borrowedSenderPromises)\n .map((promise) => {\n return promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._borrowedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n await this.disconnect();\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 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 _cleanupBorrowedSender(dcId) {\n delete this._borrowedSenderPromises[dcId];\n }\n\n _borrowExportedSender(dcId) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n let senderPromise = this._borrowedSenderPromises[dcId];\n if (!senderPromise) {\n senderPromise = this._createExportedSender(dcId);\n this._borrowedSenderPromises[dcId] = senderPromise;\n\n senderPromise.then((sender) => {\n if (!sender) {\n delete this._borrowedSenderPromises[dcId];\n }\n });\n }\n return senderPromise;\n }\n\n async _createExportedSender(dcId) {\n const dc = utils.getDC(dcId);\n const sender = new MTProtoSender(this.session.getAuthKey(dcId),\n {\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._cleanupBorrowedSender.bind(this),\n });\n for (let i = 0; i < 5; i++) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ));\n if (this.session.dcId !== dcId) {\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 }\n sender.dcId = dcId;\n return sender;\n } catch (e) {\n await sender.disconnect();\n }\n }\n return undefined;\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\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadWebDocument(media, args) {\n throw new Error('not implemented');\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n try {\n const promise = this._sender.send(request);\n const result = await promise;\n // this.session.processEntities(result)\n // this._entityCache.add(result)\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 {\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\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\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n 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","exports.endianness = function () { return 'LE' };\n\nexports.hostname = function () {\n if (typeof location !== 'undefined') {\n return location.hostname\n }\n else return '';\n};\n\nexports.loadavg = function () { return [] };\n\nexports.uptime = function () { return 0 };\n\nexports.freemem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.totalmem = function () {\n return Number.MAX_VALUE;\n};\n\nexports.cpus = function () { return [] };\n\nexports.type = function () { return 'Browser' };\n\nexports.release = function () {\n if (typeof navigator !== 'undefined') {\n return navigator.appVersion;\n }\n return '';\n};\n\nexports.networkInterfaces\n= exports.getNetworkInterfaces\n= function () { return {} };\n\nexports.arch = function () { return 'javascript' };\n\nexports.platform = function () { return 'browser' };\n\nexports.tmpdir = exports.tmpDir = function () {\n return '/tmp';\n};\n\nexports.EOL = '\\n';\n\nexports.homedir = function () {\n\treturn '/'\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\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","/* eslint-disable max-len */\nconst BigInt = require('big-integer');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n generateRandomBytes,\n modExp,\n} = require('../Helpers');\n\nconst PUBLIC_KEYS = [{\n fingerprint: [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],\n n: BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),\n e: 65537,\n}, {\n fingerprint: [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],\n n: BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),\n e: 65537,\n}, {\n fingerprint: [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],\n n: BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),\n e: 65537,\n}, {\n fingerprint: [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],\n n: BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),\n e: 65537,\n}];\n\nconst _serverKeys = {};\n\nPUBLIC_KEYS.forEach(({\n fingerprint,\n ...keyInfo\n}) => {\n _serverKeys[readBigIntFromBuffer(fingerprint.slice(-8), true, true)] = 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 None if no key matching this fingerprint is found.\n */\nasync function encrypt(fingerprint, data) {\n const key = _serverKeys[fingerprint];\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\nmodule.exports = {\n encrypt,\n};\n","class RequestState {\n constructor(request, after = undefined) {\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.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\nmodule.exports = RequestState;\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","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex_1 = require(\"./Mutex\");\nexports.Mutex = Mutex_1.default;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Mutex = /** @class */ (function () {\n function Mutex() {\n this._queue = [];\n this._pending = false;\n }\n Mutex.prototype.isLocked = function () {\n return this._pending;\n };\n Mutex.prototype.acquire = function () {\n var _this = this;\n var ticket = new Promise(function (resolve) { return _this._queue.push(resolve); });\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this\n .acquire()\n .then(function (release) {\n var result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw (e);\n }\n return Promise\n .resolve(result)\n .then(function (x) { return (release(), x); }, function (e) {\n release();\n throw e;\n });\n });\n };\n Mutex.prototype._dispatchNext = function () {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n };\n return Mutex;\n}());\nexports.default = Mutex;\n","var _global = (function () {\n\tif (!this && typeof global !== 'undefined') {\n\t\treturn global;\n\t}\n\treturn this;\n})();\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar websocket_version = require('./version');\n\n\n/**\n * Expose a W3C WebSocket class with just one or two arguments.\n */\nfunction W3CWebSocket(uri, protocols) {\n\tvar native_instance;\n\n\tif (protocols) {\n\t\tnative_instance = new NativeWebSocket(uri, protocols);\n\t}\n\telse {\n\t\tnative_instance = new NativeWebSocket(uri);\n\t}\n\n\t/**\n\t * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket\n\t * class). Since it is an Object it will be returned as it is when creating an\n\t * instance of W3CWebSocket via 'new W3CWebSocket()'.\n\t *\n\t * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2\n\t */\n\treturn native_instance;\n}\nif (NativeWebSocket) {\n\t['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) {\n\t\tObject.defineProperty(W3CWebSocket, prop, {\n\t\t\tget: function() { return NativeWebSocket[prop]; }\n\t\t});\n\t});\n}\n\n/**\n * Module exports.\n */\nmodule.exports = {\n 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null,\n 'version' : websocket_version\n};\n","module.exports = require('../package.json').version;\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","// 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}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n const me = 'phoneNumber' in authParams\n ? await signInUser(client, apiCredentials, authParams)\n : await signInBot(client, apiCredentials, authParams);\n\n // TODO @logger\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep } from '../Helpers';\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 REQUEST_TIMEOUT = 15000;\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 let sender: any;\n if (dcId) {\n try {\n sender = await client._borrowExportedSender(dcId);\n } catch (e) {\n // This should never raise\n client._log.error(e);\n if (e.message === 'DC_ID_INVALID') {\n // Can't export a sender for the ID we are currently in\n sender = client._sender;\n } else {\n throw e;\n }\n }\n } else {\n sender = client._sender;\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 // 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 await foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async () => {\n try {\n const result = await Promise.race([\n await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset,\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(REQUEST_TIMEOUT).then(() => Promise.reject(new Error('REQUEST_TIMEOUT'))),\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 return result.bytes;\n } catch (err) {\n hasEnded = true;\n throw err;\n } finally {\n foreman.releaseWorker();\n }\n })());\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\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\n\nfunction createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve: resolve!,\n };\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';\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 UPLOAD_TIMEOUT = 15 * 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 // We always upload from the DC we are in.\n const sender = await client._borrowExportedSender(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 () => {\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: j,\n fileTotalParts: partCount,\n bytes,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: j,\n bytes,\n }),\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 })());\n }\n try {\n await Promise.race([\n await Promise.all(sendingParts),\n sleep(UPLOAD_TIMEOUT * workers).then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n } catch (err) {\n if (err.message === 'TIMEOUT') {\n // eslint-disable-next-line no-console\n console.warn('Upload timeout. Retrying...');\n i -= workers;\n continue;\n }\n\n throw err;\n }\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","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","module.exports = '0.0.2';\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","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 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 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","/* 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 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 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","function 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 request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","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","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\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: number;\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 fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { 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 } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\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 }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs && stickerSet.thumbs.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: 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({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n 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: result.hash,\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport { buildApiWallpaper, buildApiSession, buildPrivacyRules } from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\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 hash: result.hash,\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: number) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildPeer(chatOrUserId),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, 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 const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }), true);\n\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updateLocalDb(result);\n }\n}\n\nexport async function fetchNotificationSettings() {\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 || (typeof privateMuteUntil === 'number' && Date.now() < privateMuteUntil * 1000)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number' && Date.now() < groupMuteUntil * 1000)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number' && Date.now() < broadcastMuteUntil * 1000)\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 : undefined,\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 }: { sourceLangPacks: string[]; langCode: string }) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function 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: IInputPrivacyRules,\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 }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\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\nfunction updateLocalDb(\n result: GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined,\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\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 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 providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\n\nexport async function validateRequestedInfo({\n messageId,\n requestInfo,\n shouldSave,\n}: {\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 msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n messageId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n messageId: number;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n messageId,\n}: {\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n msgId: messageId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({ msgId }));\n if (!result) {\n return undefined;\n }\n return buildReceipt(result);\n}\n","import {\n ApiOnProgress, ApiSessionData, ApiUpdate, OnApiUpdate,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, sessionData?: ApiSessionData) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, sessionData);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n }\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"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/index.html b/dist/index.html index 74018f8d..4420fd02 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.7c95ea3f46a28615bf1a.js b/dist/main.8fc50c5cddc24213b18b.js similarity index 99% rename from dist/main.7c95ea3f46a28615bf1a.js rename to dist/main.8fc50c5cddc24213b18b.js index 9fa3fb67..fa64de0a 100644 --- a/dist/main.7c95ea3f46a28615bf1a.js +++ b/dist/main.8fc50c5cddc24213b18b.js @@ -1,2 +1,2 @@ -!function(e){function t(t){for(var n,r,d=t[0],o=t[1],c=0,a=[];c=0&&w(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),I[n].renderTimes.push(t),I[n].renderCount++}}catch(t){Object(c.a)(t),u=e.renderedValue}if(e.isMounted&&u===e.renderedValue)return e.$element;e.renderedValue=u;const d=O(u);return e.$element=y(e,[d]),e.$element}function C(e,t){return typeof e!=typeof t||(e.type!==t.type||(b(e)&&b(t)?e.value!==t.value:h(e)&&h(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!m(e)||!m(t))&&(e.componentInstance.Component!==t.componentInstance.Component||e.props.key!==t.props.key)))}function E(e){p(e)&&(m(e)?function(e){if(!e.isMounted)return;e.hooks.memos.byCursor.forEach(e=>{e.current=null}),e.hooks.effects.byCursor.forEach(({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}}),e.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach(e=>{e.cleanup=null,e.effect=null,e.dependencies=null}),e.hooks.state.byCursor.forEach(e=>{e.value=null,e.nextValue=null,e.setter=null}),e.hooks.memos.byCursor.forEach(e=>{e.dependencies=null}),e.hooks=null,e.$element=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(e)}(e.componentInstance):e.target&&(Object(a.b)(e.target),e.target=null),e.children.forEach(E))}function S(e){return j(e),e.isMounted=!0,e.$element}function M(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;j(e),e.$element!==t&&e.onUpdate()}function A(e){return m(e)?A(e.children[0]):e.target}function k(e,t){m(e)?k(e.children[0],t):e.target=t}function T(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=Object(u.h)(()=>function e(t){t.isMounted&&(t.hooks.state.byCursor.forEach(e=>{e.value=e.nextValue}),t.prepareForFrame=Object(u.h)(()=>e(t)),t.forceUpdate=Object(u.i)(()=>M(t)))}(d)),d.forceUpdate=Object(u.i)(()=>M(d))),d.prepareForFrame(),d.forceUpdate(),r.r&&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 N(e,t,n){const{cursor:r,byCursor:u}=f.hooks.effects,d=f,o=()=>{if(!d.isMounted)return;const{cleanup:e}=u[r];if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}u[r].cleanup=t()};void 0!==u[r]&&n&&u[r].dependencies?n.some((e,t)=>e!==u[r].dependencies[t])&&e(o):e(o),u[r]={effect:t,dependencies:n,cleanup:u[r]?u[r].cleanup:void 0},f.hooks.effects.cursor++}function P(e,t){return N(u.b,e,t)}function D(e,t){return N(u.d,e,t)}function F(e,t){const{cursor:n,byCursor:r}=f.hooks.memos;let{current:u}=r[n]||{};return(void 0===r[n]||t.some((e,t)=>e!==r[n].dependencies[t]))&&(u=e()),r[n]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function L(e,t){return F(()=>e,t)}function B(e){return F(()=>({current:e}),[])}function x(e,t=o.a,n=!1){return function(u){const d=B(u),c=B();return(!c.current||d.current&&!t(d.current,u))&&(r.p&&n&&console.log(`[Teact.memo] ${e.name}: Update is caused by:`,Object(o.b)(d.current,u).join(", ")),d.current=u,c.current=g(e,u)),c.current}}document.addEventListener("dblclick",()=>{console.log("COMPONENTS",Object(d.k)(Object.values(I),"renderCount","desc"))}),t.a={createElement:g,Fragment:s}},function(e,t,n){"use strict";n.d(t,"eb",(function(){return r})),n.d(t,"D",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"g",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"r",(function(){return a})),n.d(t,"E",(function(){return i})),n.d(t,"q",(function(){return s})),n.d(t,"nb",(function(){return f})),n.d(t,"H",(function(){return l})),n.d(t,"A",(function(){return b})),n.d(t,"B",(function(){return h})),n.d(t,"z",(function(){return m})),n.d(t,"C",(function(){return p})),n.d(t,"M",(function(){return g})),n.d(t,"N",(function(){return y})),n.d(t,"O",(function(){return v})),n.d(t,"P",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"F",(function(){return I})),n.d(t,"Y",(function(){return C})),n.d(t,"U",(function(){return E})),n.d(t,"V",(function(){return S})),n.d(t,"W",(function(){return M})),n.d(t,"i",(function(){return A})),n.d(t,"k",(function(){return k})),n.d(t,"j",(function(){return T})),n.d(t,"ob",(function(){return N})),n.d(t,"X",(function(){return P})),n.d(t,"y",(function(){return D})),n.d(t,"R",(function(){return F})),n.d(t,"Q",(function(){return L})),n.d(t,"fb",(function(){return B})),n.d(t,"Db",(function(){return x})),n.d(t,"a",(function(){return R})),n.d(t,"e",(function(){return U})),n.d(t,"d",(function(){return _})),n.d(t,"s",(function(){return G})),n.d(t,"u",(function(){return $})),n.d(t,"v",(function(){return W})),n.d(t,"w",(function(){return H})),n.d(t,"kb",(function(){return K})),n.d(t,"jb",(function(){return z})),n.d(t,"ab",(function(){return V})),n.d(t,"Z",(function(){return q})),n.d(t,"db",(function(){return J})),n.d(t,"cb",(function(){return Y})),n.d(t,"bb",(function(){return Q})),n.d(t,"J",(function(){return Z})),n.d(t,"c",(function(){return X})),n.d(t,"vb",(function(){return ee})),n.d(t,"wb",(function(){return te})),n.d(t,"qb",(function(){return ne})),n.d(t,"rb",(function(){return re})),n.d(t,"yb",(function(){return ue})),n.d(t,"ub",(function(){return de})),n.d(t,"zb",(function(){return oe})),n.d(t,"Ab",(function(){return ce})),n.d(t,"xb",(function(){return ae})),n.d(t,"Bb",(function(){return ie})),n.d(t,"sb",(function(){return se})),n.d(t,"tb",(function(){return fe})),n.d(t,"S",(function(){return le})),n.d(t,"T",(function(){return be})),n.d(t,"pb",(function(){return he})),n.d(t,"l",(function(){return me})),n.d(t,"gb",(function(){return pe})),n.d(t,"ib",(function(){return ge})),n.d(t,"hb",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"b",(function(){return we})),n.d(t,"h",(function(){return Oe})),n.d(t,"L",(function(){return Ie})),n.d(t,"K",(function(){return je})),n.d(t,"lb",(function(){return Ce})),n.d(t,"G",(function(){return Ee})),n.d(t,"Cb",(function(){return Se})),n.d(t,"x",(function(){return Me})),n.d(t,"I",(function(){return Ae})),n.d(t,"n",(function(){return ke})),n.d(t,"o",(function(){return Te})),n.d(t,"t",(function(){return Ne}));const r="Telegram",u=" [Inactive]",d="Telegram WebZ",o="1.0.6",c=!1,a=!1,i=!1,s="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",f="user_auth",l="GramJs:sessionId",b=!1,h="tt-global-state",m=30,p=5e3,g=!1,y="tt-media",v="tt-media-avatars",w="tt-media-progressive",O="tt-custom-bg",I="tt-lang-packs-v4",j=(new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight>=900),C=1,E=500,S=j?60:40,M=2*S,A=72,k=j?30:25,T=100,N=42,P=42,D=20,F=30,L=200,B=500,x=20,R=!1,U=2,_=U,G=16,$=1e4,W="editable-message-text",H="editable-message-text-modal",K=1440,z=1150,V=1275,q=925,J=600,Y=950,Q=450,Z=1e9,X=100,ee=13,te=11,ne=160,re=120,ue=64,de=48,oe=32,ce=64,ae=64,ie=160,se=140,fe=80,le="MEMOJI_STICKER",be=200,he=450,me="image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime",pe="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",ge=/^(?:https?:\/\/)?(?:t\.me\/)([\d\w_]+)(?:\/([\d]+))?$/gm,ye=/^(?:https?:\/\/)?(?:t\.me\/joinchat\/)([\d\w_]+)?$/gm,ve=777e3,we=0,Oe=1,Ie=10,je=5,Ce=2147483646,Ee=["android","ios","tdesktop","macos"],Se="TelegramTips",Me="https://bugs.telegram.org/?tag_ids=41&sort=time",Ae="#A2AF8E",ke="#0F0F0F",Te="#0a0a0a8c",Ne="rgba(90, 110, 70, 0.6)"},function(e,t,n){"use strict";n.d(t,"g",(function(){return y})),n.d(t,"e",(function(){return v})),n.d(t,"d",(function(){return w})),n.d(t,"b",(function(){return O})),n.d(t,"a",(function(){return I})),n.d(t,"f",(function(){return j})),n.d(t,"h",(function(){return C}));var r=n(0),u=n(1),d=n(26),o=n(28),c=n(9),a=n(24),i=n(3),s=n(22);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],m={},p=new Map;const g=Object(c.i)((function(){h.forEach(e=>e(l))}));function y(e){"object"==typeof e&&e!==l&&(l=e,g())}function v(){return l}function w(){return m}function O(e,t){b[e]||(b[e]=[],m[e]=t=>{!function(e,t){b[e]&&b[e].forEach(e=>{const n=e(l,m,t);n&&y(n)})}(e,t)}),b[e].push(t)}function I(e){h.push(e)}function j(e){const t=h.indexOf(e);-1!==t&&h.splice(t,1)}function C(e=(()=>({})),t=(()=>({}))){return n=>function u(c){u.DEBUG_contentComponentName=n.name;const[i]=Object(r.r)(Object(o.a)(p)),b=Object(d.a)();Object(r.n)(()=>()=>{p.delete(i)},[i]);let h=p.get(i);if(h||(h={mapStateToProps:e,mapReducersToProps:t,ownProps:c,areMappedPropsChanged:!1,forceUpdate:b,DEBUG_updates:0,DEBUG_componentName:n.name},p.set(i,h)),h.areMappedPropsChanged&&(h.areMappedPropsChanged=!1),!h.mappedProps||!Object(a.a)(h.ownProps,c)){h.ownProps=c;try{h.mappedProps={...e(l,c),...t(y,m)}}catch(e){Object(s.a)(e)}}return r.a.createElement(n,f({},h.mappedProps,c))}}u.p&&(window.getGlobal=v,document.addEventListener("dblclick",()=>{console.log("GLOBAL CONTAINERS",Object(i.k)(Object.values(p),"DEBUG_updates","desc"))}))},function(e,t,n){"use strict";function r(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function u(e,t){return Object.keys(e).reduce((n,r,u)=>(n[r]=t(e[r],r,u,e),n),{})}function d(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function o(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}function c(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter(e=>!n.has(e)))}function a(e,t,n="asc"){return e.sort((e,r)=>{if(Array.isArray(t)){const[u,d]=Array.isArray(n)?n:[n,n],[o,c]=t;let a,i;if("function"==typeof o?(a=o(e)||0,i=o(r)||0):"string"==typeof o&&(a=e[o]||0,i=r[o]||0),a!==i)return"asc"===u?a-i:i-a;{let t,n;return"function"==typeof c?(t=c(e)||0,n=c(r)||0):"string"==typeof c&&(t=e[c]||0,n=r[c]||0),"asc"===d?t-n:n-t}}let u,d;return"function"==typeof t?(u=t(e)||0,d=t(r)||0):"string"==typeof t&&(u=e[t]||0,d=r[t]||0),"asc"===n?u-d:d-u})}function i(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e),[])}function s(e){return Array.from(new Set(e))}function f(e){return e.filter(Boolean)}function l(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function b(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function h(e,t){return e.filter(e=>t.has(e))}function m(e,t){const n=[];for(let r=0;r(t[n]=p(e[n]),t),{})}function g(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,"c",(function(){return r})),n.d(t,"i",(function(){return u})),n.d(t,"l",(function(){return d})),n.d(t,"m",(function(){return o})),n.d(t,"j",(function(){return c})),n.d(t,"k",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"d",(function(){return p})),n.d(t,"g",(function(){return g}))},function(e,t,n){"use strict";n.d(t,"Y",(function(){return r.b})),n.d(t,"Z",(function(){return r.c})),n.d(t,"ab",(function(){return r.d})),n.d(t,"xb",(function(){return r.g})),n.d(t,"pb",(function(){return r.e})),n.d(t,"wb",(function(){return r.f})),n.d(t,"Eb",(function(){return r.h})),n.d(t,"X",(function(){return r.a})),n.d(t,"lb",(function(){return u.w})),n.d(t,"kb",(function(){return u.v})),n.d(t,"ib",(function(){return u.t})),n.d(t,"nb",(function(){return u.y})),n.d(t,"jb",(function(){return u.u})),n.d(t,"ob",(function(){return u.z})),n.d(t,"m",(function(){return u.j})),n.d(t,"U",(function(){return u.p})),n.d(t,"l",(function(){return u.i})),n.d(t,"g",(function(){return u.e})),n.d(t,"h",(function(){return u.f})),n.d(t,"f",(function(){return u.d})),n.d(t,"mb",(function(){return u.x})),n.d(t,"gb",(function(){return u.r})),n.d(t,"q",(function(){return u.m})),n.d(t,"yb",(function(){return u.A})),n.d(t,"e",(function(){return u.c})),n.d(t,"c",(function(){return u.a})),n.d(t,"K",(function(){return u.o})),n.d(t,"k",(function(){return u.h})),n.d(t,"j",(function(){return u.g})),n.d(t,"hb",(function(){return u.s})),n.d(t,"Cb",(function(){return u.D})),n.d(t,"d",(function(){return u.b})),n.d(t,"Bb",(function(){return u.C})),n.d(t,"Ab",(function(){return u.B})),n.d(t,"p",(function(){return u.l})),n.d(t,"o",(function(){return u.k})),n.d(t,"fb",(function(){return u.q})),n.d(t,"J",(function(){return u.n})),n.d(t,"Db",(function(){return u.E})),n.d(t,"A",(function(){return i})),n.d(t,"zb",(function(){return s})),n.d(t,"F",(function(){return f})),n.d(t,"N",(function(){return l})),n.d(t,"O",(function(){return b})),n.d(t,"x",(function(){return h})),n.d(t,"L",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"tb",(function(){return g})),n.d(t,"ub",(function(){return y})),n.d(t,"qb",(function(){return v})),n.d(t,"db",(function(){return w})),n.d(t,"vb",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"V",(function(){return j})),n.d(t,"W",(function(){return C})),n.d(t,"sb",(function(){return E})),n.d(t,"rb",(function(){return S})),n.d(t,"v",(function(){return k})),n.d(t,"cb",(function(){return T})),n.d(t,"G",(function(){return N})),n.d(t,"P",(function(){return P})),n.d(t,"I",(function(){return D})),n.d(t,"t",(function(){return F})),n.d(t,"u",(function(){return L})),n.d(t,"M",(function(){return B})),n.d(t,"y",(function(){return x})),n.d(t,"H",(function(){return R})),n.d(t,"z",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"R",(function(){return G})),n.d(t,"E",(function(){return $})),n.d(t,"D",(function(){return W})),n.d(t,"C",(function(){return K})),n.d(t,"B",(function(){return z})),n.d(t,"b",(function(){return q})),n.d(t,"i",(function(){return J})),n.d(t,"S",(function(){return Y})),n.d(t,"T",(function(){return Q})),n.d(t,"bb",(function(){return Z})),n.d(t,"s",(function(){return X})),n.d(t,"w",(function(){return ee})),n.d(t,"r",(function(){return te})),n.d(t,"a",(function(){return ne}));var r=n(30),u=n(31),d=n(5),o=n(1),c=n(64);const a=new RegExp(o.gb,"i");function i(e){const{chatId:t,id:n}=e;return`msg${t}-${n}`}function s(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:Number(t[1]),messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function l(e,t,n=!1){const{text:r,photo:u,video:d,audio:o,voice:c,document:a,sticker:i,contact:s,poll:f,invoice:l}=t.content;if(t.groupedId)return`${n?"":"🖼 "}${r?r.text:e("lng_in_dlg_album")}`;if(u)return`${n?"":"🖼 "}${r?r.text:e("AttachPhoto")}`;if(d)return`${n?"":"📹 "}${r?r.text:e(d.isGif?"AttachGif":"AttachVideo")}`;if(i)return`${i.emoji} ${e("AttachSticker")} `;if(o){return`${n?"":"🎧 "}${[o.title,o.performer].filter(Boolean).join(" — ")||r&&r.text||e("AttachMusic")}`}return c?`${n?"":"🎤 "}${r?r.text:e("AttachAudio")}`:a?`${n?"":"📎 "}${r?r.text:a.fileName}`:s?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:l?"Invoice":r?r.text:"The message is not supported on this version of Telegram"}function b(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:c,poll:a,webPage:i,contact:s,invoice:f}=e.content;return t?t.text:n||r||u||d||o||c||s||a||i||f?void 0:"The message is not supported on this version of Telegram"}function h(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:a,poll:i,webPage:s,contact:f}=e.content;return!!(n||u&&u.isRound)||!(!t||r||u||d||o||a||i||s||f)&&(Object(c.a)(t.text)||!1)}function m(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===h(e))return t.text}function p(e){const{text:t}=e.content;let n;if(t&&t.entities){let e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.TextUrl);if(e&&(n=e.url.match(a)),!n&&(e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.Url),e)){const{offset:r,length:u}=e;n=t.text.substring(r,r+u).match(a)}}if(!n&&t&&(n=t.text.match(a)),n)return{url:n[0],domain:n[3]}}function g(e){return e.isOutgoing}function y(e){return Boolean(e.replyToMessageId)}function v(e){return Boolean(e.forwardInfo)}function w(e){return!!e.content.action}function O(e){return e.chatId===o.mb&&E(e)}function I(e){return Boolean(e.senderId)&&e.senderId<0&&g(e)}function j(e,t){return t.id>0?Object(r.c)(t):Object(u.i)(e,t)}function C(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function E(e){return e.id>=o.J}function S(e){return e.content.action&&"historyClear"===e.content.action.type}var M=n(7),A=n(59);function k(e){return e.content}function T(e){return Boolean(N(e)||P(e)||x(e)||B(e)||function(e){return e.content.contact}(e)||R(e)||F(e)||L(e)||function(e){return e.content.voice}(e))}function N(e){return e.content.photo}function P(e){return e.content.video}function D(e){const{video:t}=e.content;return t&&t.isRound?t:void 0}function F(e){return e.content.action}function L(e){return e.content.audio}function B(e){return e.content.sticker}function x(e){return e.content.document}function R(e){return e.content.poll}function U(e){return e.content.invoice}function _(e){return e.content.webPage}function G(e){const t=_(e);return t?t.photo:void 0}function $(e){const t=function(e){const t=N(e)||P(e)||x(e)||B(e)||G(e);if(t)return t.thumbnail}(e);return t?t.dataUri:void 0}function W(e,t){const{photo:n,video:r,sticker:u,audio:d,voice:o,document:c}=e.content,a=G(e);if(!(n||r||u||a||d||o||c))return;const s=i(e);if(n||a)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return s+"?size=x";case"viewerPreview":return s+"?size=x";case"viewerFull":return s+"?size=z"}if(r)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return q(r)?H(r,s):s+"?size=z";case"viewerPreview":return s+"?size=m";case"viewerFull":return H(r,s);case"download":return s+"?download"}if(c)switch(t){case"micro":case"pictogram":case"inline":if(!Object(A.c)(c)||V(e))return;return s+"?size=m";default:return s}if(u)switch(t){case"micro":return;case"pictogram":return s+"?size=m";default:return s}if(d)switch(t){case"micro":case"pictogram":return;default:return H(d,s)}if(o)switch(t){case"micro":case"pictogram":return;default:return s}}function H(e,t){return M.i&&M.j?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function K(e,t){const{sticker:n,video:r,audio:u,voice:o}=e.content;return n&&"inline"===t&&n.isAnimated?d.ApiMediaFormat.Lottie:r&&M.i&&("viewerFull"===t||"inline"===t&&q(r))?d.ApiMediaFormat.Progressive:u||o?o&&!M.h?d.ApiMediaFormat.BlobUrl:d.ApiMediaFormat.Progressive:d.ApiMediaFormat.BlobUrl}function z(e){const{photo:t,video:n,webPage:r}=e.content;return t||r&&r.photo?`photo${e.date}.jpeg`:n?n.fileName:void 0}function V(e){const{photo:t,video:n,document:r}=e.content;return t&&t.blobUrl||n&&n.blobUrl||r&&r.previewBlobUrl}function q(e){return e.isGif||e.isRound||e.size<=10485760}function J(e,t,n=!1){const r=ee(e,t,"media");return n?r.reverse():r}function Y(e){return e.sizes.find(e=>"z"===e.type)||e.sizes.find(e=>"y"===e.type)||Q(e)}function Q(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 Z(e){if(e.width&&e.height)return e}function X(e,t,n=!1){const r=E(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ee(e,t,n){let r;switch(n){case"media":r=e=>{const t=P(e);return N(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=x;break;case"links":r=e=>_(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(a);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=L;break;default:return[]}return t.reduce((t,n)=>(e[n]&&r(e[n])&&t.push(n),t),[])}function te(e){const{audio:t,voice:n,video:r}=k(e),u=t||n||r;if(u)return u.duration}function ne(e,t){return`${e}_${t}`}n(60)},function(e,t,n){"use strict";var r=n(68);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat})),n.o(r,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return r.ApiMessageEntityTypes})),n.o(r,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return r.MAIN_THREAD_ID})),n.o(r,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return r.MESSAGE_DELETED}));var u=n(69);n.o(u,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return u.ApiMediaFormat})),n.o(u,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return u.ApiMessageEntityTypes})),n.o(u,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return u.MAIN_THREAD_ID})),n.o(u,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return u.MESSAGE_DELETED}));var d=n(70);n.d(t,"ApiMessageEntityTypes",(function(){return d.a})),n.d(t,"MAIN_THREAD_ID",(function(){return d.b})),n.d(t,"MESSAGE_DELETED",(function(){return d.c}));var o=n(71);n.o(o,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return o.ApiMediaFormat}));var c=n(72);n.d(t,"ApiMediaFormat",(function(){return c.a}));n(73),n(74),n(75)},function(e,t,n){"use strict";n.d(t,"T",(function(){return Fe})),n.d(t,"nb",(function(){return Le})),n.d(t,"W",(function(){return Be})),n.d(t,"Gb",(function(){return a})),n.d(t,"f",(function(){return f})),n.d(t,"o",(function(){return l})),n.d(t,"P",(function(){return b})),n.d(t,"O",(function(){return h})),n.d(t,"Ab",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"g",(function(){return g})),n.d(t,"L",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"M",(function(){return w})),n.d(t,"j",(function(){return O})),n.d(t,"i",(function(){return I})),n.d(t,"N",(function(){return j})),n.d(t,"h",(function(){return C})),n.d(t,"q",(function(){return E})),n.d(t,"y",(function(){return D})),n.d(t,"r",(function(){return F})),n.d(t,"m",(function(){return L})),n.d(t,"qb",(function(){return B})),n.d(t,"Y",(function(){return R})),n.d(t,"gb",(function(){return U})),n.d(t,"x",(function(){return _})),n.d(t,"Hb",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"ob",(function(){return W})),n.d(t,"rb",(function(){return H})),n.d(t,"mb",(function(){return K})),n.d(t,"C",(function(){return z})),n.d(t,"E",(function(){return V})),n.d(t,"B",(function(){return q})),n.d(t,"cb",(function(){return J})),n.d(t,"Cb",(function(){return Y})),n.d(t,"G",(function(){return Q})),n.d(t,"Db",(function(){return Z})),n.d(t,"Eb",(function(){return X})),n.d(t,"Bb",(function(){return ee})),n.d(t,"a",(function(){return te})),n.d(t,"X",(function(){return ne})),n.d(t,"k",(function(){return re})),n.d(t,"pb",(function(){return ue})),n.d(t,"D",(function(){return de})),n.d(t,"l",(function(){return oe})),n.d(t,"I",(function(){return ce})),n.d(t,"U",(function(){return ae})),n.d(t,"fb",(function(){return ie})),n.d(t,"tb",(function(){return se})),n.d(t,"K",(function(){return fe})),n.d(t,"b",(function(){return le})),n.d(t,"e",(function(){return be})),n.d(t,"Fb",(function(){return he})),n.d(t,"lb",(function(){return me})),n.d(t,"H",(function(){return pe})),n.d(t,"R",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"S",(function(){return ve})),n.d(t,"V",(function(){return we})),n.d(t,"J",(function(){return Oe})),n.d(t,"ab",(function(){return Ie})),n.d(t,"Q",(function(){return je})),n.d(t,"sb",(function(){return Ce})),n.d(t,"bb",(function(){return Ee})),n.d(t,"ub",(function(){return Se})),n.d(t,"vb",(function(){return Me})),n.d(t,"wb",(function(){return Ae})),n.d(t,"t",(function(){return xe})),n.d(t,"A",(function(){return ke})),n.d(t,"w",(function(){return Te})),n.d(t,"v",(function(){return Ne})),n.d(t,"Z",(function(){return Pe})),n.d(t,"u",(function(){return De})),n.d(t,"z",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"xb",(function(){return k})),n.d(t,"yb",(function(){return T})),n.d(t,"c",(function(){return N})),n.d(t,"F",(function(){return P})),n.d(t,"hb",(function(){return Re})),n.d(t,"ib",(function(){return Ue})),n.d(t,"kb",(function(){return _e})),n.d(t,"zb",(function(){return Ge})),n.d(t,"eb",(function(){return i})),n.d(t,"db",(function(){return s}));var r=n(20),u=n(7),d=n(5),o=n(1),c=n(4);function a(e,t){return e.users.byId[t]}function i(e){return e.settings.byKey}function s(e){return e.settings.notifyExceptions}function f(e,t){return e.chats.byId[t]}function l(e,t){const n=Object(c.U)(t);return!!n&&a(e,n)}function b(e,t){return t===e.currentUserId}function h(e,t){const n=l(e,t);return n&&Object(c.wb)(n)}function m(e){return Object.values(e.chats.byId).find(({isSupport:e})=>e)}function p(e,t){if(!Object(c.lb)(t.id)&&!Object(c.jb)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==o.Q?t.fullInfo.members.reduce((t,{userId:n})=>e.users.byId[n]&&Object(c.xb)(e.users.byId[n])&&n!==e.currentUserId?t+1:t,0):t.fullInfo.onlineCount}function g(e,t){const n=f(e,t),r=n&&Object(c.U)(n),u=r&&a(e,r);if(u&&Object(c.wb)(u))return u}function y(e,t){const n=f(e,t),r=g(e,t);if(!n||!r)return!1;if(n.lastMessage&&Object(c.rb)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:o}=u.threadsById[d.MAIN_THREAD_ID]||{};return o&&!o.length}function v(e){return Boolean(e.chats.listIds.active)}function w(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 O(e,t){const n=f(e,t);if(n&&w(e,t))return n.folderId===o.h?"archived":"active"}function I(e,t){return e.chatFolders.byId[t]}function j(e,t,n=o.b){const{active:r,archived:u}=e.chats.orderedPinnedIds;if(n===o.b)return!!r&&r.includes(t);if(n===o.h)return!!u&&u.includes(t);const{byId:d}=e.chatFolders,{pinnedChatIds:c}=d[n]||{};return!!c&&c.includes(t)}function C(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find(e=>e.username&&e.username.toLowerCase()===n)}function E(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId;return t.reduce((t,r)=>{const u=n[r];return u&&u.unreadCount&&!Object(c.Cb)(u,i(e),s(e))?t+u.unreadCount:t},0)}var S=n(3);function M(e){return e.stickers.search}function A(e){return e.gifs.search}function k(e,t){return e.stickers.setsById[t]}function T(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach(({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))}),r}function N(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=t.replace("️","");return n.stickers.find(e=>e.emoji===t||e.emoji===r)}function P(e,t){return e.emojiKeywords[t]&&void 0!==e.emojiKeywords[t]?e.emojiKeywords[t]:void 0}function D(e){const{messageLists:t}=e.messages;if(t&&t.length)return t[t.length-1]}function F(e){const{chatId:t}=D(e)||{};return t?f(e,t):void 0}function L(e,t){const n=e.messages.byChatId[t];return n?n.byId:void 0}function B(e,t){const n=e.scheduledMessages.byChatId[t];return n?n.byId:void 0}function x(e,t,n,r){const u=e.messages.byChatId[t];if(!u)return;const d=u.threadsById[n];return d?d[r]:void 0}function R(e,t,n){return x(e,t,n,"listedIds")}function U(e,t,n){return x(e,t,n,"outlyingIds")}function _(e,t,n,r){switch(r){case"thread":return G(e,t,n);case"pinned":return $(e,t);case"scheduled":return W(e,t)}}function G(e,t,n){return x(e,t,n,"viewportIds")}function $(e,t){return x(e,t,d.MAIN_THREAD_ID,"pinnedIds")}function W(e,t){return x(e,t,d.MAIN_THREAD_ID,"scheduledIds")}function H(e,t,n){return x(e,t,n,"scrollOffset")}function K(e,t,n){return x(e,t,n,"replyingToId")}function z(e,t,n){return x(e,t,n,"editingId")}function V(e,t){return x(e,t,d.MAIN_THREAD_ID,"editingScheduledId")}function q(e,t,n){return x(e,t,n,"draft")}function J(e,t,n){return x(e,t,n,"noWebPage")}function Y(e,t,n){return x(e,t,n,"threadInfo")}function Q(e,t,n){return x(e,t,n,"firstMessageId")}function Z(e,t,n){if(n===d.MAIN_THREAD_ID)return f(e,t);const r=Y(e,t,n);return r?f(e,r.originChannelId||t):void 0}function X(e,t,n){if(n===d.MAIN_THREAD_ID)return;const r=Y(e,t,n);return r?r.topMessageId:void 0}function ee(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:u,replyToTopMessageId:d}=n;return u||d?Object.values(r.threadsById).find(e=>e.threadInfo&&(u&&u===e.threadInfo.topMessageId||d&&d===e.threadInfo.topMessageId)):void 0}function te(e,t,n){const r=D(e);if(!r)return!1;const{threadInfo:u}=ee(e,t,n)||{};return t===r.chatId&&(r.threadId===d.MAIN_THREAD_ID||u&&r.threadId===u.threadId)}function ne(e,t,n){const r=G(e,t,n);if(!r||!r.length)return!0;let u;if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n||!n.lastMessage)return!0;u=n.lastMessage.id}else{const r=Y(e,t,n);if(!r||!r.lastMessageId)return;u=r.lastMessageId}return u>=o.J&&!re(e,t,u)||r[r.length-1]>=u}function re(e,t,n){const r=L(e,t);return r?r[n]:void 0}function ue(e,t,n){const r=B(e,t);return r?r[n]:void 0}function de(e,t,n,r){if("scheduled"===r){const n=V(e,t);return n?ue(e,t,n):void 0}{const r=z(e,t,n);return r?re(e,t,r):void 0}}function oe(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 ce(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function ae(e,t){const n=ce(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function ie(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=f(e,t.chatId)||{};return Object(c.sb)(t)||!n||n0?a(e,n):f(e,n)}function fe(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?f(e,n.fromChatId):n.senderUserId?a(e,n.senderUserId):void 0}function le(e,t,n){const r=f(e,t.chatId);if(!r||r.isRestricted)return{};const u=Object(c.lb)(r.id),d=b(e,t.chatId),o=Object(c.ib)(r),a=Object(c.nb)(r),i=Object(c.jb)(r),s=Object(c.vb)(t),l=Object(c.tb)(t),h=Object(c.db)(t),{content:m}=t,p=(d||Date.now()-1e3*t.date<1728e5)&&!(m.sticker||m.contact||m.poll||m.action||m.audio||m.video&&m.video.isRound)&&!Object(c.qb)(t)&&!t.viaBotId,g=Object(c.e)(r,n)&&!s,y=u||r.isCreator||!i&&!Object(c.yb)(r,"pinMessages")||Object(c.q)(r,"pinMessages");let v=!h&&y,w=!1;const O=$(e,r.id);v&&(w=Boolean(O&&O.includes(t.id)),v=!w);const I=u||l||o||r.isCreator||Object(c.q)(r,"deleteMessages"),j=I&&!s&&(u&&!d||o&&(l||Object(c.q)(r,"deleteMessages"))),C=!h&&p&&(l||i&&(r.isCreator||Object(c.q)(r,"editMessages"))),E=!h&&!s,S=Boolean(t.content.sticker),M=S&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some(({id:e})=>e===t.id)}(e,t.content.sticker),A=!h&&S&&!M,k=!h&&M,T=!h,N=!h&&(i||a),P=!h;return{noOptions:[g,C,v,w,I,j,E,A,k,T,N,P].every(e=>!e),canReply:g,canEdit:C,canPin:v,canUnpin:w,canDelete:I,canDeleteForAll:j,canForward:E,canFaveSticker:A,canUnfaveSticker:k,canCopy:T,canCopyLink:N,canSelect:P}}function be(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=D(e)||{},u=n&&L(e,n);if(!u||!t||!r)return{};const d=t.map(t=>u[t]&&le(e,u[t],r)).filter(Boolean);return{canDelete:d.every(e=>e.canDelete),canDeleteForAll:d.every(e=>e.canDeleteForAll)}}function he(e,t){const n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id];return n?n.progress:void 0}function me(e,t,n){if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?Object(c.sb)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=Y(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function pe(e,t,n){const r=f(e,t);if(n===d.MAIN_THREAD_ID){if(!r)return}else{const r=Y(e,t,n);if(!r||r.lastMessageId===r.lastReadInboxMessageId)return}const u=U(e,t,n),o=R(e,t,n),c=L(e,t);if(!c||!u&&!o)return;const a=me(e,t,n);if(a||!r||!r.isNotJoined){if(u){const e=a?u.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):u[0];if(e)return e}if(o){const e=a?o.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):o[0];if(e)return e}}}function ge(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ye(e,t){const n=Object.values(e.chats.byId).find(e=>Object(c.ob)(e)&&e.lastMessage&&e.lastMessage.id===t);if(n)return n.id;const{byChatId:r}=e.messages;return Number(Object.keys(r).find(n=>{const u=f(e,Number(n));return u&&Object(c.ob)(u)&&r[u.id].byId[t]}))}function ve(e){const{selectedMessages:t}=e;return Boolean(t)}function we(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function Oe(e,t,n){const r=L(e,t);if(r)return Object.values(r).filter(e=>e.groupedId===n&&e.forwardInfo).map(({forwardInfo:e})=>e.fromMessageId)}function Ie(e,t,n){const r=L(e,t);if(r)return Object.keys(r).map(Number).filter(e=>r[e].groupedId===n)}function je(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const u=Ie(e,t,n);return u&&u.every(e=>r.includes(e))}function Ce(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Ee(e,t){const n=f(e,t);if(!n)return;if(!h(e,n))return;const r=L(e,t),u=G(e,t,d.MAIN_THREAD_ID);if(!r||!u)return;const o=Object(S.g)(u,e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons)),c=Object(S.g)(u,e=>Boolean(r[e].shouldHideKeyboardButtons));return o&&c&&c>o?void 0:o?r[o]:void 0}function Se(e,t,n,r){const{shouldAutoDownloadMediaFromContacts:u,shouldAutoDownloadMediaInPrivateChats:d,shouldAutoDownloadMediaInGroups:o,shouldAutoDownloadMediaInChannels:a}=e.settings.byKey;return Boolean(d&&Object(c.lb)(n.id)||o&&Object(c.kb)(n)||a&&Object(c.jb)(n)||u&&r&&(r.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,r)))}function Me(e,t){const n=Object(c.P)(t);if(!n)return;const{shouldAutoPlayVideos:r,shouldAutoPlayGifs:u}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||u&&d}function Ae(e){return e.settings.byKey.shouldLoopStickers}function ke(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=Object(c.a)(t,n),u=e.localTextSearch.byChatThreadKey[r];return u&&u.isActive?u:void 0}function Te(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=D(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ne(e){const t=Te(e);if(t)return e.localMediaSearch.byChatId[t]}function Pe(e,t){return e.management.byChatId[t]}function De(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;if(Object(c.lb)(t))return"user";const r=f(e,t);return r?Object(c.kb)(r)?"group":"channel":void 0}function Fe(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Le(e){const{users:t,isChatInfoShown:n}=e,d=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),o=Boolean(!u.g&&ke(e)),c=function(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),a=void 0!==M(e).query,i=void 0!==A(e).query,{chatId:s}=D(e)||{},f=t.selectedId,l=v(e),b=Boolean(f&&l),h=Boolean(s&&l)&&n;return d?r.l.PollResults:o?r.l.Search:c?r.l.Management:a?r.l.StickerSearch:i?r.l.GifSearch:b?r.l.UserInfo:h?r.l.ChatInfo:void 0}function Be(e){return void 0!==Le(e)}function xe(e){return e.globalSearch.query}function Re(e){return e.payment.messageId}function Ue(e){return e.payment.formId}function _e(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function Ge(e){return e.payment.stripeCredentials}},function(e,t,n){"use strict";n.d(t,"o",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"e",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"j",(function(){return a})),n.d(t,"l",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"m",(function(){return f})),n.d(t,"d",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"h",(function(){return m})),n.d(t,"c",(function(){return p})),n.d(t,"a",(function(){return g})),n.d(t,"n",(function(){return y})),n.d(t,"p",(function(){return w}));var r=n(1);const u=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="Mac OS":-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}(),d="Mac OS"===u,o="iOS"===u,c="Android"===u,a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=window.matchMedia("(pointer: coarse)").matches,s=window.innerWidth<=r.db||window.innerWidth<=r.cb&&window.innerHeight<=r.bb,f=navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext),l=(document.documentElement.style,u&&(d||o)),b="serviceWorker"in navigator,h=b,m=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),p=!r.E&&"filter"in(document.createElement("canvas").getContext("2d")||{}),g=window.devicePixelRatio||1,y=!0;let v;function w(){return Boolean(v)}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=>{v=e})},function(e,t,n){"use strict";t.a=(...e)=>e.filter(Boolean).join(" ")},function(e,t,n){"use strict";function r(e,t,n=!0,r=!0){let u;return(...d)=>{u?(clearTimeout(u),u=void 0):n&&e(...d),u=self.setTimeout(()=>{r&&e(...d),u=void 0},t)}}function u(e,t,n=!0){let r,u,d;return(...o)=>{u=!0,d=o,r||(n&&(u=!1,e(...d)),r=self.setInterval(()=>{if(!u)return self.clearInterval(r),void(r=void 0);u=!1,e(...d)},t))}}function d(e){return c(h,e)}function o(e){return c(m,e)}function c(e,t){let n,r=!1;return(...u)=>{n=u,r||(r=!0,e(()=>{r=!1,t(...n)}))}}function a(e){Promise.resolve().then(e)}function i(e){self.requestIdleCallback?self.requestIdleCallback(e):a(e)}n.d(t,"a",(function(){return r})),n.d(t,"g",(function(){return u})),n.d(t,"i",(function(){return d})),n.d(t,"h",(function(){return o})),n.d(t,"d",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return s})),n.d(t,"f",(function(){return f})),n.d(t,"b",(function(){return h}));const s=e=>new Promise(t=>{setTimeout(()=>t(),e)});function f(){return new Promise(e=>{h(e)})}let l,b;function h(e,t=!1){l?t?b.push(e):l.push(e):(l=t?[]:[e],b=t?[e]:[],requestAnimationFrame(()=>{const e=l,t=b;l=void 0,b=void 0,t.forEach(e=>e()),e.forEach(e=>e())}))}function m(e){h(e,!0)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));var r=n(80),u=n.n(r),d=n(1),o=n(28);let c;const a=new Map,i=new Map;function s(e,t){return c||(d.p&&console.log(">>> START LOAD WORKER"),c=new u.a,function(e){c.addEventListener("message",({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){const e=a.get(t.messageId);e&&e.callback&&e.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}(e)),b({type:"initApi",args:[t]})}function f(e,...t){if(c)return b({type:"callMethod",name:e,args:t});d.p&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&c.postMessage({type:"cancelProgress",messageId:t})}function b(e){const t=Object(o.a)(a),n={messageId:t,...e},r={messageId:t},u=new Promise((e,t)=>{Object.assign(r,{resolve:e,reject:t})});if("function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,i.set(e,r)}return a.set(t,r),u.catch(()=>{}).finally(()=>{a.delete(t),r.callback&&i.delete(r.callback)}),c.postMessage(n),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(1);let u;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(u||(u={}));const d={},o={};async function c(e,t){if(!d[e]){switch(e){case u.Auth:d[u.Auth]=n.e(5).then(n.bind(null,105));break;case u.Main:r.p&&console.log(">>> START LOAD MAIN BUNDLE"),d[u.Main]=Promise.all([n.e(0),n.e(4)]).then(n.bind(null,104));break;case u.Extra:d[u.Extra]=Promise.all([n.e(0),n.e(3)]).then(n.bind(null,103))}d[e].then(f)}const c=await d[e];return o[e]||(o[e]=c),a(e,t)}function a(e,t){const n=o[e];if(n)return n[t]}const i=[];function s(e){i.includes(e)||i.push(e)}function f(){i.forEach(e=>{e()})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"c",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"b",(function(){return c}));const r=self.caches;let u;async function d(e,t,n){if(r)try{const d=new Request(t),o=await r.open(e),c=await o.match(d);if(!c)return;switch(n){case u.Text:return await c.text();case u.Blob:{const e=await c.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=c.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case u.Json:return await c.json();default:return}}catch(e){return void console.warn(e)}}async function o(e,t,n){if(r)try{const u="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t),o=new Response(u),c=await r.open(e);return await c.put(d,o)}catch(e){return void console.warn(e)}}async function c(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"}(u||(u={}))},function(e,t,n){"use strict";n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l}));var r=n(9);function u(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,...r}=n;super(e,{type:t}),u(this,"name",void 0),Object.assign(this,r)}else super(e),u(this,"name",void 0);this.name=t}});function d(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let u=r.length;const d=new Uint8Array(u);for(;u--;)d[u]=r.charCodeAt(u);return new Blob([d],{type:n})}function o(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 c(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function a(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e})}function i(e){return new Promise((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e})}async function s(e){const t=await i(e);return Promise.race([Object(r.e)(2e3),new Promise((e,n)=>{t.onseeked=()=>{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 f(e){return(await fetch(e)).blob()}function l(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return v})),n.d(t,"b",(function(){return j})),n.d(t,"c",(function(){return C}));var r=n(1),u=n(12),d=n(10);var o=n(3),c=n.p+"en-extra.e73049da90714ecdae3233e8ffa74d39.json",a=n.p+"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json",i=n.p+"it-extra.78e5568451a888818c7e2209e05a9602.json",s=n.p+"pl-extra.38fd67a6c26e58f5c912568332c7c074.json",f=n.p+"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json",l=n(49),b=n(2);const h={en:c,es:a,it:i,pl:s,ru:f},m=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],p={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},g=new Map;let y;const{addCallback:v,removeCallback:w,runCallbacks:O}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach(e=>{e(...t)})},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let I;const j=(e,t,n)=>{if(void 0!==t){const r=g.get(`${e}_${t}_${n}`);if(r)return r}if(!y)return e;const r=y[e];if(!r)return e;const u=r["number"==typeof t?function(e){const t=I&&p[I]?p[I](e):0;return m[t]}(t):"value"];if(!u||!u.trim()){const t=e.split(".");return t[t.length-1]}if(void 0!==t){const r=function(e,t){return e.replace(/%\d?\$?[sdf@]/,String(t))}(u,"i"===n?Object(l.a)(t):t);return g.set(`${e}_${t}_${n}`,r),r}return u};async function C(e,t){if(y&&e===I)return void(t&&t());const n=await async function(e){const t=await u.c(r.F,e,u.a.Json);if(t)return t;const n=await Object(d.a)("fetchLangPack",{sourceLangPacks:r.G,langCode:e});if(n)return await u.d(r.F,e,n.langPack),n.langPack;return}(e);if(!n)return;if(h[e])try{const t=await fetch(h[e]),r=await t.json(),u=Object(o.i)(r,(e,t)=>({key:t,value:e}));Object.assign(n,u)}catch(e){r.p&&console.error(e)}g.clear(),I=e,y=n,document.documentElement.lang=e;const{languages:c}=Object(b.e)().settings.byKey,a=c?c.find(t=>t.langCode===e):void 0;j.isRtl=Boolean(a&&a.rtl),t&&t(),O(y)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d}));const r=/\uFE0F/g,u=String.fromCharCode(8205);function d(e){return e.indexOf(u)<0?e.replace(r,""):e}t.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},function(e,t,n){"use strict";var r=n(0),u=n(21);n(94);t.a=Object(r.h)(({color:e="blue"})=>r.a.createElement("div",{className:"Loading"},r.a.createElement(u.a,{color:e,withBackground:"white"===e})))},function(e,t,n){"use strict";var r=n(0),u=n(11),d=n(26);t.a=(e,t,n=!1,o=!1)=>{const c=Object(u.c)(e,t),a=Object(d.a)();return o&&Object(u.b)(a),Object(r.n)(()=>{n||c||Object(u.d)(e,t).then(a)},[e,a,c,t,n]),c}},function(e,t,n){"use strict";n.d(t,"d",(function(){return o})),n.d(t,"e",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return d}));const r={},u=/(\d{1,3})(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,3})?/;var d="AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234".split("\n").map(e=>({id:e.substr(0,2),flag:e.substr(2,4),code:"+"+e.match(/\d+/)[0],name:e.split(/\d+/)[1],phoneFormat:function(e){if(!e)return u;const t=e[0];let n;if(!r[t]){const e=t.split("").map(Number);n=e.reduce((e,t,n)=>`${e}(\\d{1,${t}})${n>0?"?":""}`,""),r[t]=new RegExp(`${n}${"()?".repeat(5-e.length)}`)}return r[t]}(e.match(/\d+$/))}));function o(e){return d.find(t=>t.id===e)}function c(e){let t=e.replace(/[^\d+]+/g,"");t.startsWith("+")||(t="+"+t);const n=d.filter(e=>t.startsWith(e.code)).sort((e,t)=>e.code.length-t.code.length);return n[n.length-1]}function a(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.code.length-1);else if(e.startsWith("+"))return e;return n=n.replace(function(e){return e?e.phoneFormat:u}(t),(e,n,r,u,d,o)=>{const c=t&&"GB"===t.id?" ":"-";let a="";return n&&(a=""+n),r&&(a+=" "+r),u&&(a+=`${c}${u}`),d&&(a+=`${c}${d}`),o&&(a+=`${c}${o}`),a}),n}function i(e){const t=e.startsWith("+")?e:"+"+e,n=c(t);return n?`${n.code} ${a(t,n)}`:t}},function(e,t,n){"use strict";(function(e){n.d(t,"f",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"e",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"d",(function(){return l}));var r=n(41),u=n(1),d=n(12);const o=[1,2,3,4,5];function c(e,t){const{mainDcId:n,keys:r,hashes:d}=e;localStorage.setItem(u.nb,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]))}),Object.keys(d).map(Number).forEach(e=>{localStorage.setItem(`dc${e}_hash`,JSON.stringify(d[e]))})}function a(){[u.nb,"dc",...o.map(e=>`dc${e}_auth_key`),...o.map(e=>`dc${e}_hash`)].forEach(e=>{localStorage.removeItem(e)})}function i(){const e=localStorage.getItem(u.nb);if(!e)return;let t;const n={},r={};try{const n=JSON.parse(e);t=Number(n.dcID)}catch(e){}return t&&(o.forEach(e=>{try{const t=localStorage.getItem(`dc${e}_auth_key`);t&&(n[e]=JSON.parse(t));const u=localStorage.getItem(`dc${e}_hash`);u&&(r[e]=JSON.parse(u))}catch(e){u.p&&console.warn("Failed to load stored session",e)}}),Object.keys(n).length)?{mainDcId:t,keys:n,hashes:r}:void 0}async function s(){const e=localStorage.getItem(u.H);if(!e)return;const t=await r.b("GramJs:"+e);try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load legacy session",e)}}async function f(){localStorage.removeItem(u.H);const e=await r.c();await Promise.all([d.b("GramJs"),...e.filter(e=>"string"==typeof e&&e.startsWith("GramJs:GramJs-session-")).map(e=>r.a(e))])}function l(){const t=e.env.TEST_SESSION;try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load test session",e)}}}).call(this,n(86))},function(e,t,n){"use strict";let r,u,d,o,c,a,i,s,f,l,b,h;n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"m",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"a",(function(){return s})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"g",(function(){return p})),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"}(u||(u={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.Language=3]="Language",e[e.General=4]="General",e[e.GeneralChatBackground=5]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=6]="GeneralChatBackgroundColor",e[e.Privacy=7]="Privacy",e[e.PrivacyPhoneNumber=8]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=9]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=10]="PrivacyProfilePhoto",e[e.PrivacyForwarding=11]="PrivacyForwarding",e[e.PrivacyGroupChats=12]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=13]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=14]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=15]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=16]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=17]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=18]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=19]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=20]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=21]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=22]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=23]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=24]="PrivacyBlockedUsers",e[e.Folders=25]="Folders",e[e.FoldersCreateFolder=26]="FoldersCreateFolder",e[e.FoldersEditFolder=27]="FoldersEditFolder",e[e.FoldersIncludedChats=28]="FoldersIncludedChats",e[e.FoldersExcludedChats=29]="FoldersExcludedChats",e[e.TwoFaDisabled=30]="TwoFaDisabled",e[e.TwoFaNewPassword=31]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=32]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=33]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=34]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=35]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=36]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=37]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=38]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=39]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=40]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=41]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=42]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=43]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=44]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=45]="TwoFaCongratulations"}(d||(d={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(o||(o={})),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"}(c||(c={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults"}(a||(a={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.MiddleHeaderAvatar=4]="MiddleHeaderAvatar",e[e.Album=5]="Album",e[e.ScheduledAlbum=6]="ScheduledAlbum",e[e.SearchResult=7]="SearchResult"}(i||(i={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(s||(s={})),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"}(l||(l={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(b||(b={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(h||(h={}));const m="UPLOADING_WALLPAPER_SLUG";let p;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(p||(p={}))},function(e,t,n){"use strict";var r=n(0),u=n(8);n(90);t.a=({color:e="blue",withBackground:t})=>r.a.createElement("div",{className:Object(u.a)("Spinner",e,t&&"with-background")},r.a.createElement("div",null))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(1),u=n(9);window.addEventListener("error",c),window.addEventListener("unhandledrejection",c);const d=Date.now();let o=!1;function c(e){e.preventDefault(),a(e instanceof ErrorEvent?e.error:e.reason)}Object(u.g)(window.alert,1e3);function a(e){if(console.error(e),!o)return Date.now()-d<=5e3&&localStorage.getItem(r.B)?(localStorage.removeItem(r.B),o=!0,void window.location.reload()):void 0}},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(0),u=n(15),d=n(1),o=n(7),c=n(65),a=n(8),i=n(76),s=n(57);const f=/^[\d\wа-яё]$/i,l=/(\*\*|__).+?\1/g;function b(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML]),[])}(e);case"hq_emoji":return u.a.lastIndex=0,h(e,"big","jsx");case"emoji":return u.a.lastIndex=0,h(e,"small","jsx");case"emoji_html":return u.a.lastIndex=0,h(e,"small","html");case"br":return m(e,"jsx");case"br_html":return m(e,"html");case"highlight":return d=e,o=n.highlight,d.reduce((e,t)=>{if("string"!=typeof t||!o)return[...e,t];const n=t.toLowerCase(),u=n.indexOf(o.toLowerCase()),d=n[u+o.length];if(u<0||d&&d.match(f))return[...e,t];const c=[];return c.push(t.substring(0,u)),c.push(r.a.createElement("span",{className:"matching-text-highlight"},t.substring(u,u+o.length))),c.push(t.substring(u+o.length)),[...e,...c]},[]);case"links":return function(e){return e.reduce((e,t)=>{if("string"!=typeof t)return[...e,t];const n=[...t.match(p)||[],...t.match(g)||[]];if(!n.length)return[...e,t];const u=[];let d=n.shift(),o=0;for(;d;){const e=t.indexOf(d,o);u.push(t.substring(o,e)),d.startsWith("@")?u.push(r.a.createElement(i.a,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),u.push(r.a.createElement(s.a,{text:d,url:d}))),o=e+d.length,d=n.shift()}return u.push(t.substring(o)),[...e,...u]},[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var d,o;return e},[e])}function h(e,t,n){return e.reduce((e,d)=>{if("string"!=typeof d)return[...e,d];const i=d.split(u.a),s=d.match(u.a)||[];return e.push(i[0]),s.reduce((e,d,s)=>{const f=Object(c.a)(Object(u.b)(d)),l=Object(a.a)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(o.d?r.a.createElement("span",{className:"font-emoji"},d):r.a.createElement("img",{className:l,src:`./img-apple-${"big"===t?"160":"64"}/${f}.png`,alt:d})),"html"===n&&e.push(o.d?d:`${d}`);const b=2*s+2;return i[b]&&e.push(i[b]),e},e)},[])}function m(e,t){return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce((e,n,u,d)=>{const o=n.trimLeft(),c=n.length-o.length;return e.push(String.fromCharCode(160).repeat(c)+o),u!==d.length-1&&e.push("jsx"===t?r.a.createElement("br",null):"
"),e},[])],[])}const p=new RegExp(d.gb,"ig"),g=/@[\w\d_-]+/gi;function y(e,t){return e.reduce((e,n)=>{if("string"!=typeof n)return[...e,n];const u=n.split(l),d=n.match(l)||[];return e.push(u[0]),d.reduce((e,n,d)=>{"jsx"===t?e.push(n.startsWith("**")?r.a.createElement("b",null,n.replace(/\*\*/g,"")):r.a.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const o=2*d+2;return u[o]&&e.push(u[o]),e},e)},[])}},function(e,t,n){"use strict";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 u=0;ue[n]!==t[n])}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u}))},function(e,t,n){"use strict";var r=n(14),u=n(26),d=n(51);t.a=()=>{const e=Object(u.a)();return Object(d.a)(()=>r.a(e),[e]),r.b}},function(e,t,n){"use strict";var r=n(0);t.a=()=>{const[,e]=Object(r.r)(!1);return Object(r.m)(()=>{e(e=>!e)},[])}},function(e,t,n){"use strict";var r=n(0),u=n(8);n(88);t.a=({children:e,className:t,isRtl:n,onClick:d})=>{const o=Object(r.m)(e=>{e.preventDefault(),d(e)},[d]);return r.a.createElement("a",{href:"#",className:Object(u.a)("Link",t),dir:n?"rtl":"auto",onClick:d?o:void 0},e)}},function(e,t,n){"use strict";t.a=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},function(e,t,n){"use strict";n.d(t,"d",(function(){return p})),n.d(t,"c",(function(){return g})),n.d(t,"b",(function(){return y})),n.d(t,"a",(function(){return v}));var r=n(10),u=n(67),d=n(1),o=n(2),c=n(4),a=n(14),i=n(37),s=n(6),f=n(7);function l(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function b(){return!!f.k&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(d.p&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(d.p&&console.warn("[PUSH] Push messaging isn't supported."),!1):(d.p&&console.warn("[PUSH] Push notifications aren't supported."),!1))}async function h(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function m(e){const t=Object(o.e)(),n=Object(o.d)();if(e)try{const t=l(e);return await Object(r.a)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){d.p&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await Object(r.a)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function p(){if(!b())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await m(t)}async function g(){if(async function(){const[e]=await Promise.all([Object(r.a)("fetchNotificationSettings"),Object(r.a)("fetchNotificationExceptions")]);e&&Object(o.g)(Object(i.v)(Object(o.e)(),e))}(),!b())return void await h();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=Object(o.e)();return!t.push||!e||(l(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5)}(t)){await m(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=l(t);d.p&&console.log("[PUSH] Received push subscription: ",n),await Object(r.a)("registerDevice",n),Object(o.d)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?d.p&&console.warn("[PUSH] The user has blocked push notifications."):d.p&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await h())}}}function y({chat:e,message:t,isActiveChat:n}){if(!("Notification"in window?"denied"!==Notification.permission||(d.p&&console.warn("[PUSH] The user has blocked push notifications."),0):(d.p&&console.warn("[PUSH] This browser does not support desktop notification"),0)))return;if(!t.id)return;if(!function(e,t){const n=Object(o.e)();if(Object(c.Cb)(e,Object(s.eb)(n),Object(s.db)(n))||e.isNotJoined)return!1;if(t&&document.hasFocus())return!1;switch(e.type){case"chatTypePrivate":case"chatTypeSecret":return Boolean(n.settings.byKey.hasPrivateChatsNotifications);case"chatTypeBasicGroup":case"chatTypeSuperGroup":return Boolean(n.settings.byKey.hasGroupNotifications);case"chatTypeChannel":return Boolean(n.settings.byKey.hasBroadcastNotifications)}return!1}(e,n))return;const{title:r,body:i}=function(e,t){const n=Object(o.e)(),{senderId:r,replyToMessageId:d}=t,i=r?Object(s.Gb)(n,r):void 0,f=Object(c.t)(t),l=f&&d?Object(s.k)(n,e.id,d):void 0,{targetUserId:b,targetChatId:h}=f||{},m=b?Object(s.Gb)(n,b):void 0,p=Object(c.U)(e),g=p?Object(s.Gb)(n,p):void 0;let y;if(Object(c.db)(t)){const n=e&&(Object(c.jb)(e)||t.senderId===t.chatId)?e:i;y=Object(u.a)(a.b,t,n,m,l,h,{asPlain:!0})}else{const n=Object(c.J)(a.b,e.id,i),r=Object(c.N)(a.b,t);y=n?`${n}: ${r}`:r}return{title:Object(c.l)(a.b,e,g),body:y}}(e,t);if(b())navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"newMessageNotification",payload:{title:r,body:i,chatId:e.id,messageId:t.id}});else{const n=Object(o.d)(),u={body:i,icon:"icon-192x192.png",badge:"icon-192x192.png",tag:t.id.toString()};"vibrate"in navigator&&(u.vibrate=[200,100,200]);const d=new Notification(r,u);d.onclick=()=>{d.close(),n.focusMessage({chatId:e.id,messageId:t.id}),window.focus&&window.focus()}}}function v(){navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"h",(function(){return b})),n.d(t,"a",(function(){return h}));var r=n(1),u=n(36),d=n(3);const o=[1,8,5,2,7,4,6];function c(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function a(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function i(e,t){if(t.id===r.mb)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!t.status)return"";switch(t.status.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:n}=t.status;if(!n)return e("LastSeen.Offline");const r=new Date,d=new Date(1e3*n);if(d>=r)return e("LastSeen.JustNow");const o=new Date(r.getTime()-d.getTime());if(o.getTime()/1e3<60)return e("LastSeen.JustNow");if(o.getTime()/1e3<3600){return e("LastSeen.MinutesAgo",Math.floor(o.getTime()/1e3/60))}const c=new Date;if(c.setHours(0,0,0,0),d>c){if(o.getTime()/1e3<21600){return e("LastSeen.HoursAgo",Math.floor(o.getTime()/1e3/60/60))}return e("LastSeen.TodayAt",Object(u.h)(d))}const a=new Date;return a.setDate(r.getDate()-1),c.setHours(0,0,0,0),d>a?e("LastSeen.YesterdayAt",Object(u.h)(d)):e("LastSeen.AtDate",Object(u.b)(e,d))}case"userStatusOnline":return e("Online");case"userStatusRecently":return e("Lately");default:return}}function s(e){const{id:t,status:n,type:u}=e;return!!n&&(t!==r.mb&&("userStatusOnline"===n.type&&"userTypeBot"!==u))}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.mb)&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function l(e){return"userTypeBot"===e.type}function b(e,t,n){return Object(d.k)(e,e=>{const r=Date.now()/1e3;if(n&&n.includes(e))return r+172800-(n.length-n.indexOf(e));const u=t[e];if(!u||!u.status)return 0;if("userStatusOnline"===u.status.type)return u.status.expires;if("userStatusOffline"===u.status.type&&u.status.wasOnline)return u.status.wasOnline;switch(u.status.type){case"userStatusRecently":return r-86400;case"userStatusLastWeek":return r-604800;case"userStatusLastMonth":return r-18144e3;default:return 0}},"desc")}function h(e){const t=e?Math.abs(e.id)%7:0;return o[t]}},function(e,t,n){"use strict";n.d(t,"w",(function(){return c})),n.d(t,"v",(function(){return a})),n.d(t,"t",(function(){return i})),n.d(t,"y",(function(){return s})),n.d(t,"u",(function(){return f})),n.d(t,"z",(function(){return l})),n.d(t,"j",(function(){return b})),n.d(t,"p",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"e",(function(){return p})),n.d(t,"f",(function(){return g})),n.d(t,"d",(function(){return y})),n.d(t,"x",(function(){return v})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"A",(function(){return I})),n.d(t,"c",(function(){return j})),n.d(t,"a",(function(){return C})),n.d(t,"o",(function(){return E})),n.d(t,"h",(function(){return S})),n.d(t,"g",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"D",(function(){return k})),n.d(t,"b",(function(){return T})),n.d(t,"C",(function(){return N})),n.d(t,"B",(function(){return P})),n.d(t,"l",(function(){return D})),n.d(t,"k",(function(){return F})),n.d(t,"q",(function(){return L})),n.d(t,"n",(function(){return B})),n.d(t,"E",(function(){return x}));var r=n(5),u=n(1),d=n(3),o=n(30);function c(e){return e>0}function a(e){return i(e)||s(e)}function i(e){return"chatTypeBasicGroup"===e.type}function s(e){return"chatTypeSuperGroup"===e.type}function f(e){return"chatTypeChannel"===e.type}function l(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function b(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function h(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function m(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function p(e){if(e.fullInfo)return e.fullInfo.about}function g(e){const{username:t}=e,{inviteLink:n}=e.fullInfo||{};return n&&n.length?n:t?"t.me/"+t:""}function y(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function v(e){return!e.lastMessage}function w(e){return Boolean(e.adminRights)}function O(e,t){return!!e.adminRights&&e.adminRights[t]}function I(e,t){return Boolean(e.currentUserBannedRights&&e.currentUserBannedRights[t]||e.defaultBannedRights&&e.defaultBannedRights[t])}function j(e,t){return t!==r.MAIN_THREAD_ID||!(e.isRestricted||e.migratedTo||e.isNotJoined)&&(!!e.isCreator||(!!c(e.id)||(f(e)?O(e,"postMessages"):w(e)||!I(e,"sendMessages"))))}function C(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=w(e);return{canAttachMedia:n||!I(e,"sendMedia"),canAttachPolls:(n||!I(e,"sendPolls"))&&(!c(e.id)||t),canSendStickers:n||!I(e,"sendStickers"),canSendGifs:n||!I(e,"sendGifs"),canAttachEmbedLinks:n||!I(e,"embedLinks")}}function E(e){return e.currentUserBannedRights&&e.currentUserBannedRights.sendMessages?"You are not allowed to send messages in this chat.":e.defaultBannedRights&&e.defaultBannedRights.sendMessages?"Sending messages is not allowed in this chat.":void 0}function S(e){if(e&&e.fullInfo)return e.fullInfo.slowMode}function M(e){return Math.max(e.joinDate||0,e.lastMessage?e.lastMessage.date:0)}function A(e){return e.folderId===u.h}function k(e,t,n){return!(n&&n[e.id]&&!n[e.id].isMuted)&&(e.isMuted||c(e.id)&&!t.hasPrivateChatsNotifications||f(e)&&!t.hasBroadcastNotifications||a(e)&&!t.hasGroupNotifications)}function T(e){return i(e)||(s(e)||f(e))&&e.isCreator}function N(e,t,n,r,u,d){const o=n.excludedChatIds?new Set(n.excludedChatIds):void 0,i=n.excludedChatIds?new Set(n.includedChatIds):void 0,s=n.excludedChatIds?new Set(n.pinnedChatIds):void 0;return[(d||Object.keys(e).map(Number)).filter(d=>function(e,t,n,r,u,d,o,i){if(d&&d.has(e.id))return!1;if(o&&o.has(e.id))return!0;if(i&&i.has(e.id))return!0;if(A(e)&&t.excludeArchived)return!1;if(t.excludeMuted&&!e.unreadMentionsCount&&k(e,r,u))return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(c(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(a(e))return!!t.groups;if(f(e))return!!t.channels}return!1}(e[d],n,t,r,u,o,i,s)),n.pinnedChatIds]}function P(e,t,n,r="all"){function u(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(A(e))return!1;break;case"archived":if(!A(e))return!1}return!e.isRestricted&&!e.isNotJoined}const o=t.map(t=>e[t]).filter(u),c=new Set(t);return{pinnedChats:n?n.map(t=>e[t]).filter(u).filter(e=>c.has(e.id)):[],otherChats:Object(d.k)(n?o.filter(e=>!n.includes(e.id)):o,M,"desc")}}function D(e,t,n,r,u,d){const[o]=N(e,t,n,u,d,r),c=o.map(t=>e[t]).filter(e=>e&&e.lastMessage&&!e.isRestricted&&!e.isNotJoined);return{unreadDialogsCount:c.reduce((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e,0),hasActiveDialogs:c.some(e=>e.unreadMentionsCount||!k(e,u,d)&&(e.unreadCount||e.hasUnreadMark))}}function F(e,t,n,r,u,d,o){const{id:c,title:a,emoticon:i,description:s,pinnedChatIds:f,excludedChatIds:l,includedChatIds:b,excludeArchived:h,excludeMuted:m,excludeRead:p,...g}=r;if(Object.values(g).filter(Boolean).length>1||l&&l.length||b&&b.length){return e("Chats",function(e,t,n,r,u,d){const[o,c]=N(e,t,n,u,d,r),{pinnedChats:a,otherChats:i}=P(e,o,c,"folder");return a.length+i.length}(t,n,r,u,d,o))}return g.bots?e("FilterBots"):g.groups?e("FilterGroups"):g.channels?e("FilterChannels"):g.contacts?e("FilterContacts"):g.nonContacts?e("FilterNonContacts"):void 0}function L(e){return!!e&&e.id<0}function B(e,t,n){if(n&&!c(t))return n.isSelf?e("FromYou"):Object(o.b)(n)}function x(e,t,n=!1,r){return Object(d.k)(e,e=>{const u=t[e];if(!u)return 0;let d=0;return u.lastMessage&&(d+=u.lastMessage.date),n&&u.isVerified&&(d+=3e9),r&&r.includes(e)&&(d+=Date.now()+(r.length-r.indexOf(e))),d},"desc")}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(21),o=n(43);n(92);t.a=({ref:e,type:t="button",onClick:n,onContextMenu:c,onMouseDown:a,onMouseEnter:i,onMouseLeave:s,onFocus:f,children:l,size:b="default",color:h="primary",className:m,round:p,pill:g,fluid:y,isText:v,isLoading:w,ariaLabel:O,href:I,download:j,disabled:C,ripple:E,faded:S,tabIndex:M,isRtl:A})=>{let k=Object(r.q)(null);e&&(k=e);const[T,N]=Object(r.r)(!1),P=Object(u.a)("Button",m,b,h,p&&"round",g&&"pill",y&&"fluid",C&&"disabled",v&&"text",w&&"loading",E&&"has-ripple",S&&"faded",T&&"clicked"),D=Object(r.m)(e=>{!C&&n&&n(e),N(!0),setTimeout(()=>{N(!1)},400)},[C,n]),F=Object(r.m)(e=>{e.preventDefault(),!C&&a&&a(e)},[a,C]);return I?r.a.createElement("a",{ref:k,className:P,href:I,title:O,download:j,tabIndex:M,dir:A?"rtl":void 0},l,!C&&E&&r.a.createElement(o.a,null)):r.a.createElement("button",{ref:k,type:t,className:P,onClick:D,onContextMenu:c,onMouseDown:F,onMouseEnter:i&&!C?i:void 0,onMouseLeave:s&&!C?s:void 0,onFocus:f&&!C?f:void 0,"aria-label":O,title:O,tabIndex:M,dir:A?"rtl":void 0},w?r.a.createElement("div",null,r.a.createElement("span",{dir:A?"auto":void 0},"Please wait.."),r.a.createElement(d.a,{color:v?"blue":"white"})):l,!C&&E&&r.a.createElement(o.a,null))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return b}));var r=n(1);const u=new Set(["scroll","mouseenter","mouseleave"]),d={},o=new Map,c={};function a(e,t,n){const r=s(t,e);f(r,e)?function(e,t,n){c[e]||(c[e]=0,document.addEventListener(e,h));(function(e){d[e]||(d[e]=new Map);return d[e]})(e).set(t,n),function(e){const t=o.get(e);if(t)return t;const n=new Set;return o.set(e,n),n}(t).add(e),c[e]++}(r,e,n):e.addEventListener(r,n)}function i(e,t,n){const r=s(t,e);f(r,e)?l(r,e):e.removeEventListener(r,n)}function s(e,t){const n=e.replace(/^on/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function f(e,t){return!u.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function l(e,t){c[e]--,c[e]||document.removeEventListener(e,h),d[e].delete(t),o.get(t).delete(e)}function b(e){const t=o.get(e);t&&(t.forEach(t=>l(t,e)),o.delete(e))}function h(e){const t=d[e.type];if(t){let n=!1,r=e.target;const u=()=>{n=!0},d=()=>{e.preventDefault()},o=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?u:"preventDefault"===t?d:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(o),n))return;r=r.parentNode}}}r.p&&document.addEventListener("dblclick",()=>{console.log("DELEGATED EVENTS",{delegationRegistry:d,delegatedEventsByElement:o,documentEventCounters:c})})},function(e,t,n){"use strict";var r=n(0);t.a=(e=!1)=>{const[t,n]=Object(r.r)(e);return[t,Object(r.m)(()=>{n(!0)},[]),Object(r.m)(()=>{n(!1)},[])]}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=(e=!1,t,n=!1,d="fast",o=!1)=>{const[c,a]=Object(r.r)(!e),i=Object(r.q)(),[s,f]=Object(r.r)(e&&n);e?(a(!1),f(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(f(!1),c||i.current||(i.current=window.setTimeout(()=>{a(!0),t&&t(),i.current=void 0},o?0:350)));const l=Boolean(i.current),b=e||l;return{shouldRender:b,transitionClassNames:Object(u.a)(d&&"opacity-transition",d,s&&"open",b&&"shown",l&&"closing")}}},function(e,t,n){"use strict";n.d(t,"j",(function(){return o})),n.d(t,"k",(function(){return c})),n.d(t,"n",(function(){return a})),n.d(t,"h",(function(){return s})),n.d(t,"g",(function(){return f})),n.d(t,"b",(function(){return l})),n.d(t,"f",(function(){return b})),n.d(t,"c",(function(){return h})),n.d(t,"d",(function(){return p})),n.d(t,"e",(function(){return g})),n.d(t,"i",(function(){return y})),n.d(t,"a",(function(){return v})),n.d(t,"l",(function(){return O})),n.d(t,"m",(function(){return I}));const r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"],d=u.map(e=>e.toLowerCase());function o(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function c(e){return o(e).getTime()}function a(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function i(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function s(e){const t="number"==typeof e?new Date(e):e;return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function f(e,t){const n="number"==typeof t?new Date(t):t,u=o(new Date);if(n>=u)return s(n);const d=new Date(u);if(d.setDate(u.getDate()-7),n>=d)return e("Weekday.Short"+r[n.getDay()]);const c=n.getFullYear()!==u.getFullYear(),a=e(c?"formatDateScheduleYear":"formatDateSchedule")||(c?"d MMM yyyy":"d MMM");return m(e,n,a)}function l(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return m(e,n,r)}function b(e,t,n=!1){const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return m(e,t,r)}function h(e,t,n=!1,u=!1){const d="number"==typeof t?new Date(t):t,c=o(new Date);if(!u){if(i(d)===i(c))return(n?j:C)(e("Weekday.Today"));const t=new Date(c);if(t.setDate(c.getDate()-1),i(d)===i(t))return(n?j:C)(e("Weekday.Yesterday"));const u=new Date(c),o=new Date(c);if(u.setDate(c.getDate()-7),o.setDate(c.getDate()+7),d>=u&&d<=o){const t=r[d.getDay()];return n?j(e("Weekday.Short"+t)):C(e("Weekday."+t))}}const a=d.getFullYear()!==c.getFullYear(),s=e(n?a?"formatDateScheduleYear":"formatDateSchedule":a?"chatFullDate":"chatDate")||"d MMMM yyyy";return(n?j:C)(m(e,d,s))}function m(e,t,n){const r=t.getDate(),d=t.getMonth();return n.replace("LLLL",e(u[d])).replace("MMMM",e("Month.Gen"+u[d])).replace("MMM",e("Month.Short"+u[d])).replace("MM",String(d+1).padStart(2,"0")).replace("dd",String(r).padStart(2,"0")).replace("d",String(r)).replace("yyyy",String(t.getFullYear()))}function p(e,t){const n="number"==typeof t?new Date(t):t;return`${h(e,n,!0)}, ${s(n)}`}function g(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%3600%60);let u="";return t>0?(u+=String(t).padStart(2,"0")+":",u+=String(n).padStart(2,"0")+":"):u+=String(n)+":",u+=String(r).padStart(2,"0"),u}function y(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 u=(e=Math.floor(e/60))%60;e-=u;const d=(e=Math.floor(e/60))%60;return d>0&&t.push(String(d).padStart(2,"0")),t.push(String(u).padStart(d>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function v(e){return e.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function O(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?r+"-":""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const u=e.split(" "),o=t?u[0]:u[1],c=(t?u[1]:u[0]).toLowerCase(),a=d.findIndex(e=>e.startsWith(c));return-1!==a&&w(Number(o),a)?`${String(a+1).padStart(2,"0")}-${String(o).padStart(2,"0")}`:void 0}function I(e){return e+86400}function j(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function C(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},function(e,t,n){"use strict";n.d(t,"r",(function(){return d})),n.d(t,"I",(function(){return o})),n.d(t,"s",(function(){return c})),n.d(t,"H",(function(){return a})),n.d(t,"M",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"K",(function(){return f})),n.d(t,"J",(function(){return l})),n.d(t,"N",(function(){return m})),n.d(t,"x",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"b",(function(){return w})),n.d(t,"L",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"j",(function(){return j})),n.d(t,"k",(function(){return C})),n.d(t,"V",(function(){return E})),n.d(t,"db",(function(){return S})),n.d(t,"g",(function(){return A})),n.d(t,"z",(function(){return k})),n.d(t,"kb",(function(){return T})),n.d(t,"lb",(function(){return N})),n.d(t,"u",(function(){return P})),n.d(t,"P",(function(){return D})),n.d(t,"O",(function(){return F})),n.d(t,"m",(function(){return L})),n.d(t,"G",(function(){return B})),n.d(t,"n",(function(){return x})),n.d(t,"ib",(function(){return R})),n.d(t,"hb",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"q",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"o",(function(){return W})),n.d(t,"y",(function(){return K})),n.d(t,"nb",(function(){return z})),n.d(t,"ob",(function(){return V})),n.d(t,"f",(function(){return q})),n.d(t,"fb",(function(){return J})),n.d(t,"l",(function(){return Y})),n.d(t,"R",(function(){return Z})),n.d(t,"S",(function(){return X})),n.d(t,"U",(function(){return ee})),n.d(t,"T",(function(){return te})),n.d(t,"Y",(function(){return ue})),n.d(t,"t",(function(){return de})),n.d(t,"Z",(function(){return oe})),n.d(t,"X",(function(){return ae})),n.d(t,"W",(function(){return ie})),n.d(t,"bb",(function(){return fe})),n.d(t,"ab",(function(){return le})),n.d(t,"v",(function(){return be})),n.d(t,"w",(function(){return he})),n.d(t,"e",(function(){return me})),n.d(t,"cb",(function(){return pe})),n.d(t,"a",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"gb",(function(){return we})),n.d(t,"E",(function(){return Oe})),n.d(t,"C",(function(){return Ie})),n.d(t,"A",(function(){return je})),n.d(t,"F",(function(){return Ce})),n.d(t,"B",(function(){return Ee})),n.d(t,"D",(function(){return Se})),n.d(t,"h",(function(){return Me})),n.d(t,"i",(function(){return Ae}));var r=n(1),u=n(3);function d(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function o(e,t,n){const{[t]:r}=e.chats.listIds,u=r&&r.length?n.filter(e=>!r.includes(e)):n;return r&&!u.length?e:d(e,t,[...r||[],...u])}function c(e,t){return{...e,chats:{...e.chats,byId:t}}}function a(e,t,n,r){const{byId:d}=e.chats,o=d[t],a=n.isMin&&o&&!o.isMin,i={...o,...a?Object(u.j)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...o.photos||[]]}};return i.id&&i.type?c(e,{...d,[t]:i}):e}function i(e,t){return Object.keys(t).forEach(n=>{e=a(e,Number(n),t[Number(n)])}),e}function s(e,t){const{byId:n}=e.chats;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=a(e,r,t[r]))}),e}function f(e,t,n){const u=n===r.h?"archived":"active";let d=e.chats.listIds;return Object.keys(d).forEach(e=>{const n=d[e]||[];e!==u||n.includes(t)?e!==u&&n.includes(t)&&(d={...d,[e]:n.filter(e=>e!==t)}):d={...d,[e]:[...n,t]}}),e=a(e={...e,chats:{...e.chats,listIds:d}},t,{folderId:n||void 0})}function l(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}}}}var b=n(5),h=n(6);function m(e,t,n=b.MAIN_THREAD_ID,r="thread"){return{...e,messages:{...e.messages,messageLists:t?[{chatId:t,threadId:n,type:r}]:void 0}}}function p(e,t,n){return g(e,t,{byId:n})}function g(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function y(e,t,n,r,u){return function(e,t,n,r){const u=e.messages.byChatId[t];return g(e,t,{threadsById:{...u&&u.threadsById,[n]:{...u&&u.threadsById[n],...r}}})}(e,t,n,{[r]:u})}function v(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).map(Number).forEach(t=>{e=w(e,t,n[t])}),e}function w(e,t,n){const r=Object(h.m)(e,t);return r&&Object.keys(n).every(e=>Boolean(r[Number(e)]))?e:p(e,t,{...n,...r})}function O(e,t,n,r){const u=Object(h.m)(e,t)||{},d={...u[n],...r};return d.id?p(e,t,{...u,[n]:d}):e}function I(e,t,n,r){const u=Object(h.qb)(e,t)||{},d={...u[n],...r};return d.id?P(e,t,{...u,[n]:d},void 0):e}function j(e,t,n){const r=Object(h.m)(e,t);if(!r)return e;const d=Object(u.j)(r,n),o=Object.values(Object(u.m)(r,n)).filter(({forwardInfo:e})=>e&&e.isLinkedChannelPost);if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach(r=>{let u=Object(h.Y)(e,t,r),d=Object(h.gb)(e,t,r),o=Object(h.Hb)(e,t,r),c=Object(h.jb)(e,t);n.forEach(e=>{u&&u.includes(e)&&(u=u.filter(t=>t!==e)),d&&d.includes(e)&&(d=d.filter(t=>t!==e)),o&&o.includes(e)&&(o=o.filter(t=>t!==e)),c&&c.includes(e)&&(c=c.filter(t=>t!==e))}),e=y(e,t,r,"listedIds",u),e=y(e,t,r,"outlyingIds",d),e=y(e,t,r,"viewportIds",o),e=y(e,t,r,"pinnedIds",c)}),o.length){const n=Object(h.y)(e),r=n&&n.chatId===t&&"thread"===n.type,u=n&&n.threadId;o.forEach(n=>{const{fromChatId:d,fromMessageId:o}=n.forwardInfo,c=Object(h.k)(e,d,o);r&&u===o&&(e=m(e,t)),c&&(e=O(e,d,o,{threadInfo:void 0}))})}return e=p(e,t,d)}function C(e,t,n){const r=Object(h.qb)(e,t);if(!r)return e;const d=Object(u.j)(r,n);let o=Object(h.ob)(e,t);return o&&(n.forEach(e=>{o.includes(e)&&(o=o.filter(t=>t!==e))}),e=y(e,t,b.MAIN_THREAD_ID,"scheduledIds",o)),e=P(e,t,d,void 0)}function E(e,t,n,r){const u=Object(h.Y)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"listedIds",M([...u||[],...d]))}function S(e,t,n,r){const u=Object(h.gb)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"outlyingIds",M([...u||[],...d]))}function M(e){return e.sort((e,t)=>e-t)}function A(e,t,n,u){const d=Object(h.Hb)(e,t,n)||[];if(d.includes(u))return e;return y(e,t,n,"viewportIds",M([...d.length{e=T(e,t.chatId,t.threadId,t)}),e}function P(e,t,n,r){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,hash:r})}function D(e,t,n,r=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r}}}function F(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function L(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function B(e,t,n,r,d,o,c,a=!1){const{selectedMessages:i}=e;o&&(c=Object(h.ab)(e,t,o));const s=c||[d];if(!i)return L(e,t,s);const{messageIds:f}=i;let l;const b=s.filter(e=>!f.includes(e));if(b&&!b.length)l=f.filter(e=>!s.includes(e));else if(a&&f.length){const o=Object(h.x)(e,t,n,r),c=o.indexOf(f[f.length-1]),a=o.indexOf(d),i=Math.min(c,a),s=Math.max(c,a),b=o.slice(i,s+1);l=Object(u.o)([...f,...b])}else l=[...f,...b];return l.length?{...e,selectedMessages:{...i,messageIds:l}}:x(e)}function x(e){return{...e,selectedMessages:void 0}}function R(e,t,n,r,d){const o=r.map(t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t});return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...Object(u.c)(o,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:d}:{setIds:r.map(({id:e})=>e)}}}}}function U(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function _(e,t,n,r){const{results:u}=e.gifs.search;let d;if(t||!u)d=n;else{const e=new Set(u.map(e=>e.id));d=[...u,...n.filter(t=>!e.has(t.id))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:d}}}}function G(e,t){return{...e,animatedEmojis:t}}function $(e,t,n,r){const d=[...Object(h.yb)(e,t),...n||[]],o=Object(u.o)(d.map(({id:e})=>e)),c=Object(u.c)(d,"id"),a=o.map(e=>c[e]);return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:a,hash:r}}}}function W(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?$(e,t,n,r):e}var H=n(50);function K(e,t){return{...e,users:{...e.users,byId:t}}}function z(e,t,n){const{byId:r}=e.users,{hash:d,userIds:o}=e.contactList||{},c=r[t],a=n.isMin&&c&&!c.isMin,i={...c,...a?Object(u.j)(n,["isMin","accessHash"]):n};return i.id&&i.type?(i.isContact&&o&&!o.includes(t)&&(e={...e,contactList:{hash:d||0,userIds:[t,...o]}}),K(e,{...r,[t]:i})):e}function V(e,t){return Object.keys(t).map(Number).forEach(n=>{e=z(e,n,t[n])}),e}function q(e,t){const{byId:n}=e.users;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=z(e,r,t[r]))}),e}function J(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function Y(e,t){const{byId:n}=e.users,{hash:r,userIds:u}=e.contactList||{};return delete n[t],K(e={...e,contactList:{hash:r||0,userIds:u?u.filter(e=>e!==t):H.a}},n)}const Q=e=>`${e.chatId}_${e.id}`;function Z(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function X(e,t){return Z(e,{currentContent:t})}function ee(e,t,n,r,d){const{resultsByType:o}=e.globalSearch||{},c=t.reduce((e,t)=>(e[Q(t)]=t,e),{}),a=o&&o[r]?o[r].foundIds:void 0;if(void 0!==a&&Object.keys(c).every(e=>a.includes(Q(c[e]))))return te(e,{messages:!1});const i=a||[],s=t.map(e=>Q(e)),f=Array.prototype.concat(i,s),l=Object(u.a)(i,f)?i:f;return Z(e=te(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:d,foundIds:l}}})}function te(e,t){return Z(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ne=n(4);function re(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,u){const d=Object(ne.a)(t,n);return re(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:u})}function de(e,t,n,r,u,d){const o=Object(ne.a)(t,n);return re(e,o,{...e.localTextSearch.byChatThreadKey[o],results:{foundIds:r,totalCount:u,nextOffsetId:d}})}function oe(e,t,n,r,d,o){const c=Object(ne.a)(t,n),{results:a}=e.localTextSearch.byChatThreadKey[c]||{},i=a&&a.foundIds||[],s=se(Object(u.o)(Array.prototype.concat(i,r)));return de(e,t,n,Object(u.a)(i,s)?i:s,d,o)}function ce(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ae(e,t,n){return ce(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ie(e,t,n,r,d,o){const{resultsByType:c}=e.localMediaSearch.byChatId[t]||{},a=c&&c[n]?c[n].foundIds:[],i=se(Object(u.o)(Array.prototype.concat(a,r)));return function(e,t,n,r,u,d){return ce(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:u,nextOffsetId:d}}})}(e,t,n,Object(u.a)(a,i)?a:i,d,o)}function se(e){return e.sort((e,t)=>e-t)}function fe(e,t){return{...e,management:{...e.management,progress:t}}}function le(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function be(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function he(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function me(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function pe(e,t,n,r){switch(t){case"contact":return be(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return be(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return be(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function ge(e,t){return{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function ye(e,t){return{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter(e=>e!==t),totalCount:e.blocked.totalCount-1}}}function ve(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function we(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Oe(e,t){return{...e,payment:{...e.payment,formId:t}}}function Ie(e,t){return{...e,payment:{...e.payment,step:t}}}function je(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,description:u,photoUrl:d}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,description:u,photoUrl:d}}}}function Ce(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function Ee(e,t){return{...e,payment:{...e.payment,...t}}}function Se(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:u,text:d,title:o}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:u,text:d,title:o}}}}function Me(e){return{...e,payment:{}}}function Ae(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},function(e,t,n){"use strict";var r=n(0);t.a=function(e,t){const n=Object(r.q)(),{current:u}=n;return t&&void 0===e||(n.current=e),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));function r(e,t=30){return!e||e.length<=t?e:e.substr(0,t)+"..."}},function(e){e.exports=JSON.parse('{"--color-primary":["#50A2E9","#8378DB"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#121212"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFEDF","#8378DB"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d4fcae","#7b71c6"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#4C90E6","#8378DB"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-borders":["#DADCE0","#100F10"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-links":["#52A1EF","#868DF6"],"--color-links-hover":["#2d8dec","#6b5fcc"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#1010109c"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#4DCD5E","#8378DB"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#DBF4CE","#6458bc"],"--color-reply-own-active":["#C8EBBC","#4F4A9F"],"--color-accent-own":["#4FAE4E","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#52A1EF","#FFFFFF"],"--color-code-own":["#3C7940","#FFFFFF"]}')},function(e,t,n){"use strict";function r(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}let u;function d(){return u||(u=function(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const u=r(n);return(e,n)=>u.then(r=>n(r.transaction(t,e).objectStore(t)))}("keyval-store","keyval")),u}function o(e,t=d()){return t("readonly",t=>r(t.get(e)))}function c(e,t=d()){return t("readwrite",t=>(t.delete(e),r(t.transaction)))}function a(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction)))}function i(e=d()){const t=[];return a(e,e=>t.push(e.key)).then(()=>t)}n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return i}))},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);n(97);t.a=e=>{const{icon:t,className:n,children:o,onClick:c,href:a,download:i,disabled:s,destructive:f,ariaLabel:l}=e,b=Object(d.a)(),h=Object(r.m)(e=>{if(s||!c)return e.stopPropagation(),void e.preventDefault();c(e)},[s,c]),m=Object(r.m)(e=>{if(13===e.keyCode||32===e.keyCode)return s||!c?(e.stopPropagation(),void e.preventDefault()):void c(e)},[s,c]),p=Object(u.a)("MenuItem",n,s&&"disabled",f&&"destructive"),g=r.a.createElement(r.a.Fragment,null,t&&r.a.createElement("i",{className:"icon-"+t,"data-char":t.startsWith("char-")?t.replace("char-",""):void 0}),o);return a?r.a.createElement("a",{tabIndex:0,className:p,href:a,download:i,"aria-label":l,title:l,target:a.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:b.isRtl?"rtl":void 0,onClick:c},g):r.a.createElement("div",{role:"button",tabIndex:0,className:p,onClick:h,onKeyDown:m,"aria-label":l,title:l,dir:b.isRtl?"rtl":void 0},g)}},function(e,t,n){"use strict";var r=n(0),u=n(9);n(91);t.a=Object(r.h)(()=>{const[e,t]=Object(r.r)([]),n=Object(r.p)(()=>Object(u.a)(()=>{t([])},700,!1),[]),d=Object(r.m)(r=>{if(0!==r.button)return;const u=r.currentTarget,d=u.getBoundingClientRect(),o=u.offsetWidth/2;t([...e,{x:r.clientX-d.x-o/2,y:r.clientY-d.y-o/2,size:o}]),requestAnimationFrame(()=>{n()})},[e,n]);return r.a.createElement("div",{className:"ripple-container",onMouseDown:d},e.map(({x:e,y:t,size:n})=>r.a.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"c",(function(){return l}));var r=n(83),u=n.n(r),d=n(7),o=n(13),c=n(9);let a,i;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function f(e,t){for(b();!i.wasmReady;)await Object(c.e)(2e3);const{result:n,width:r,height:u}=await function(e,t){return new Promise(n=>{i.requests=i.requests||new Map,i.requests.set(e,n),i.postMessage({id:e,blob:t})})}(e,t);if(r&&u)return function({result:e,width:t,height:n}){a||(a=document.createElement("canvas"));return new Promise(r=>{const u=new ImageData(e,t,n);a.width=t,a.height=n;a.getContext("2d").putImageData(u,0,0),a.toBlob(e=>{r(null!=e?e:void 0)},"image/png",1)})}({result:n,width:r,height:u})}async function l(e,t){if(Object(d.p)()||"data:image/webp"!==t.substr(0,15))return t;b();const n=await f(e,Object(o.d)(t));if(!n)throw new Error("Can't convert webp to png. Url: "+t);return Object(o.a)(n)}function b(){i||(i=new u.a,i.wasmReady=!1,i.onmessage=h)}function h(e){const{id:t}=e.data;switch(e.data.type){case"initialized":i.wasmReady=!0;break;case"result":if(i.requests.has(t)){const n=i.requests.get(t);i.requests.delete(t),n(e.data)}}}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);t.a=Object(r.h)(({ref:e,id:t,className:n,value:o,label:c,error:a,success:i,disabled:s,readOnly:f,placeholder:l,autoComplete:b,inputMode:h,maxLength:m,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w})=>{const O=Object(d.a)(),I=a||i||c,j=Object(u.a)("input-group",o&&"touched",a?"error":i&&"success",s&&"disabled",f&&"disabled",I&&"with-label",n);return r.a.createElement("div",{className:j,dir:O.isRtl?"rtl":void 0},r.a.createElement("input",{ref:e,className:"form-control",type:"text",id:t,dir:"auto",value:o||"",placeholder:l,maxLength:m,autoComplete:b,inputMode:h,disabled:s,readOnly:f,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w}),I&&r.a.createElement("label",{htmlFor:t},I))})},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25),o=n(21);n(93);t.a=Object(r.h)(({id:e,name:t,value:n,label:c,subLabel:a,checked:i,disabled:s,round:f,blocking:l,isLoading:b,onChange:h,onCheck:m})=>{const p=Object(d.a)(),g=Object(r.m)(e=>{h&&h(e),m&&m(e.currentTarget.checked)},[h,m]),y=Object(u.a)("Checkbox",s&&"disabled",f&&"round",b&&"loading",l&&"blocking");return r.a.createElement("label",{className:y,dir:p.isRtl?"rtl":void 0},r.a.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:i,disabled:s,onChange:g}),r.a.createElement("div",{className:"Checkbox-main"},r.a.createElement("span",{className:"label",dir:"auto"},c),a&&r.a.createElement("span",{className:"subLabel",dir:"auto"},a)),b&&r.a.createElement(o.a,null))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(55);function u(e){return Object(r.a)({onEsc:e})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));var r=n(0);let u,d=!1;const o=e=>{document.dispatchEvent(new Event("tt-event-heavy-animation-start")),d=!0,u&&(clearTimeout(u),u=void 0),u=window.setTimeout(()=>{d=!1,document.dispatchEvent(new Event("tt-event-heavy-animation-end")),u=void 0},e)};t.a=(e,t)=>{Object(r.n)(()=>(d&&e(),document.addEventListener("tt-event-heavy-animation-start",e),document.addEventListener("tt-event-heavy-animation-end",t),()=>{document.removeEventListener("tt-event-heavy-animation-end",t),document.removeEventListener("tt-event-heavy-animation-start",e)}),[t,e])}},function(e,t,n){"use strict";function r(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function d(e){return e<1e3?e:e<1e6?u(e/1e3)+"K":u(e/1e6)+"M"}function o(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map(e=>e.length&&e.match(/./u)[0].toUpperCase()).join("")}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return o}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r=[]},function(e,t,n){"use strict";var r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));const r=/[^\wа-яё]+/;function u(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every(e=>n.some(t=>t.startsWith(e)))}},function(e,t,n){"use strict";var r=n(0),u=n(35),d=n(63),o=n(79),c=n(58),a=n(47),i=n(8),s=n(48);n(95);t.a=({ref:e,containerRef:t,isOpen:n,className:f,style:l,children:b,positionX:h="left",positionY:m="top",autoClose:p=!1,footer:g,noCloseOnBackdrop:y=!1,onCloseAnimationEnd:v,onClose:w,onMouseEnter:O,onMouseLeave:I})=>{let j=Object(r.q)(null);e&&(j=e);const C=t||j,{transitionClassNames:E}=Object(u.a)(n,v);Object(r.n)(()=>n&&w?Object(a.a)(w):void 0,[n,w]),Object(c.a)(([e])=>{void 0!==e&&Object(s.b)(200)},[n]);const S=Object(d.a)(j,n,p?w:void 0,void 0,!0);Object(o.a)(n,C,y?void 0:w);const M=Object(i.a)("bubble menu-container custom-scroll",m,h,g&&"with-footer",E);return r.a.createElement("div",{className:Object(i.a)("Menu no-selection",f),onKeyDown:n?S:void 0,onMouseEnter:O,onMouseLeave:n?I:void 0,style:l},n&&r.a.createElement("div",{className:"backdrop"}),r.a.createElement("div",{ref:j,className:M,style:`transform-origin: ${m} ${h}`,onClick:p?w:void 0},b,g&&r.a.createElement("div",{className:"footer"},g)))}},function(e,t,n){"use strict";n.d(t,"b",(function(){return y})),n.d(t,"c",(function(){return v})),n.d(t,"a",(function(){return w}));var r=n(5),u=n(1),d=n(10),o=n(12),c=n(13),a=n(7),i=n(81),s=n.n(i),f=n(82),l=n.n(f);async function b(e){const t=await new Response(e).arrayBuffer();return new Promise(e=>{const n=new Uint8Array(t);let r=new s.a,u=new l.a;r.onmessage=e=>{null===e.data?u.postMessage({command:"done"}):u.postMessage({command:"encode",buffers:e.data},e.data.map(({buffer:e})=>e))},u.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),r.terminate(),r=void 0,u.terminate(),u=void 0)},u.postMessage({command:"init",wavBitDepth:16,wavSampleRate:48e3}),r.postMessage({command:"init",decoderSampleRate:48e3,outputBufferSampleRate:48e3}),r.postMessage({command:"decode",pages:n},[n.buffer])})}var h=n(44);const m={[r.ApiMediaFormat.DataUri]:o.a.Text,[r.ApiMediaFormat.BlobUrl]:o.a.Blob,[r.ApiMediaFormat.Lottie]:o.a.Json,[r.ApiMediaFormat.Progressive]:void 0,[r.ApiMediaFormat.Stream]:void 0},p=new Map,g=new Map;function y(e,t,n){if(t===r.ApiMediaFormat.Progressive)return a.i?function(e){const t="./progressive/"+e;return p.set(e,t),Promise.resolve(t)}(e):y(e,r.ApiMediaFormat.BlobUrl,n);if(!g.has(e)){const i=async function(e,t,n){if(!u.M){const n=e.startsWith("avatar")?u.O:u.N,r=await o.c(n,e,m[t]);if(r){let t=r;if("audio/ogg"!==r.type||a.h||(t=await b(t)),"image/webp"===r.type&&!Object(a.p)()&&t){const n=await Object(h.b)(e,t);n&&(t=n)}const n=O(t);return p.set(e,n),n}}if(t===r.ApiMediaFormat.Stream){const r=new MediaSource,u=URL.createObjectURL(r);let o=!1;return r.addEventListener("sourceopen",()=>{if(o)return;o=!0;const u=r.addSourceBuffer("audio/mpeg");Object(d.a)("downloadMedia",{url:e,mediaFormat:t},(e,t)=>{n&&n(e),1===e&&r.endOfStream(),t&&u.appendBuffer(t)})}),p.set(e,u),u}const i=await Object(d.a)("downloadMedia",{url:e,mediaFormat:t},n);if(!i)throw new Error("Failed to fetch media");let{prepared:s,mimeType:f}=i;if("audio/ogg"===f&&!a.h){const e=await Object(c.e)(s);URL.revokeObjectURL(s);const t=await b(e);s=O(t),f=e.type}if("image/webp"===f&&!Object(a.p)()){const t=await Object(c.e)(s);URL.revokeObjectURL(s);const n=await Object(h.b)(e,t);n&&(s=O(n))}return p.set(e,s),s}(e,t,n).catch(e=>{u.p&&console.warn(e)}).finally(()=>{g.delete(e)});g.set(e,i)}return g.get(e)}function v(e){return p.get(e)}function w(e){Object(d.b)(e)}function O(e){return e instanceof Blob?URL.createObjectURL(e):e}a.i&&navigator.serviceWorker.addEventListener("message",async e=>{const{type:t,messageId:n,params:u}=e.data;if("requestPart"!==t)return;const o=await Object(d.a)("downloadMedia",{mediaFormat:r.ApiMediaFormat.Progressive,...u});if(!o)return;const{arrayBuffer:c,mimeType:a,fullSize:i}=o;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:c,mimeType:a,fullSize:i}},[c])})},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",ArrowLeft:"onLeft",ArrowRight:"onRight",Tab:"onTab"},u={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onLeft:[],onRight:[],onTab:[]};function d(e){return o()||document.addEventListener("keydown",c,!0),Object.keys(e).forEach(t=>{const n=e[t];if(!n)return;const r=u[t];r&&r.push(n)}),()=>{!function(e){Object.keys(e).forEach(t=>{const n=e[t],r=u[t];if(r){const e=r.findIndex(e=>e===n);-1!==e&&r.splice(e,1)}}),o()||document.removeEventListener("keydown",c,!1)}(e)}}function o(){return Object.values(u).some(e=>Boolean(e.length))}function c(e){const t=r[e.key];if(!t)return;const{length:n}=u[t];if(!n)return;e.stopPropagation();(0,u[t][n-1])(e)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i}));var r=n(9),u=n(1),d=n(7);const o=d.g&&s();let c=i();const a=Object(r.g)(()=>{c=i(),((c.width<=u.db||c.width<=u.cb&&c.height<=u.bb)!==d.g||d.g&&o!==s())&&window.location.reload()},250,!0);function i(){const e=.01*window.innerHeight;return document.documentElement.style.setProperty("--vh",e+"px"),{width:window.innerWidth,height:window.innerHeight}}function s(){return d.e?window.matchMedia("(orientation: landscape)").matches:window.matchMedia("screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)").matches}window.addEventListener("resize",a),window.addEventListener("orientationchange",a),t.a={get:()=>c}},function(e,t,n){"use strict";var r=n(0),u=n(2);const d=e=>{const t=[];let n=0;const r=e.length;let u;for(;n65535&&(u-=65536,t.push(String.fromCharCode(u>>>10&1023|55296)),u=56320|1023&u),t.push(String.fromCharCode(u))}return t.join("")};function o(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=36)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function c(e,t){const n=[],r=[],u=e.length;let c,a,i,s,f,l,b,h,m,p,g,y,v;for(c=128,i=0,s=72,f=e.lastIndexOf("-"),f<0&&(f=0),l=0;l=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(l))}for(b=f>0?f+1:0;b=u)throw RangeError("punycode_bad_input(1)");if(g=(w=e.charCodeAt(b++))-48<10?w-22:w-65<26?w-65:w-97<26?w-97:36,g>=36)throw RangeError("punycode_bad_input(2)");if(g>Math.floor((2147483647-i)/m))throw RangeError("punycode_overflow(1)");if(i+=g*m,y=p<=s?1:p>=s+26?26:p-s,gMath.floor(2147483647/(36-y)))throw RangeError("punycode_overflow(2)");m*=36-y}if(a=n.length+1,s=o(i-h,a,0===h),Math.floor(i/a)>2147483647-c)throw RangeError("punycode_overflow(3)");c+=Math.floor(i/a),i%=a,t&&r.splice(i,0,e.charCodeAt(b-1)-65<26),n.splice(i,0,c),i++}var w;if(t)for(i=0,v=n.length;iObject(s.l)(t,["toggleSafeLinkModal","openTelegramLink"]))(({url:e,text:t,className:n,children:u,isRtl:d,toggleSafeLinkModal:o,openTelegramLink:c})=>{const a=u||t,s=e!==a,h=Object(r.m)(t=>t.ctrlKey||t.altKey||t.shiftKey||t.metaKey||!e||!e.match(i.ib)&&!e.match(i.hb)?!s||(o({url:e}),t.preventDefault(),!1):(t.preventDefault(),c({url:e}),!1),[s,c,o,e]);if(!e)return;const m=Object(f.a)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.a.createElement("a",{href:l(e),title:b(e),target:"_blank",rel:"noopener noreferrer",className:m,onClick:h,dir:d?"rtl":"auto"},a)}))},function(e,t,n){"use strict";var r=n(0),u=n(38);t.a=(e,t)=>{const n=Object(u.a)(t);return Object(r.n)(()=>e(n||[]),t)}},function(e,t,n){"use strict";n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c}));function r(e){return e>536870912?(e/1073741824).toFixed(1)+" GB":e>524288?(e/1048576).toFixed(1)+" MB":(e/1024).toFixed(1)+" KB"}function u(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 o(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 c(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return o}));const r={missing_payment_information:{field:"cardNumber",fieldError:"Incorrect card number"},invalid_number:{field:"cardNumber",fieldError:"Incorrect card number"},number:{field:"cardNumber",fieldError:"Incorrect card number"},exp_year:{field:"expiry",fieldError:"Incorrect year"},exp_month:{field:"expiry",fieldError:"Incorrect month"},invalid_expiry_year:{field:"expiry",fieldError:"Incorrect year"},invalid_expiry_month:{field:"expiry",fieldError:"Incorrect month"},cvc:{field:"cvv",fieldError:"Incorrect CVV"},invalid_cvc:{field:"cvv",fieldError:"Incorrect CVV"}};function u(e){const{message:t,code:n,param:u}=e,{field:d,fieldError:o,description:c}=u?r[u]:r[n];return{field:d,fieldError:o,description:c||t}}const d={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",fieldError:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",fieldError:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",fieldError:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",fieldError:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",fieldError:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",fieldError:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",fieldError:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",fieldError:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",fieldError:"Incorrect email"}};function o(e){return Object.values(e).reduce((e,t)=>{const n=d[t.message];return n&&(e={...e,[n.field]:n.fieldError}),e},{})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"a",(function(){return o}));var r=n(9);let u;function d(e,t){t||(u&&!u.isCancelled&&(u.isCancelled=!0),u=t={isCancelled:!1}),Object(r.b)(()=>{!t.isCancelled&&e()&&d(e,t)})}function o(e){Object(r.b)(()=>{e()&&o(e)})}},function(e,t,n){"use strict";var r=n(0),u=n(53);n(96);t.a=({trigger:e,className:t,children:n,positionX:d="left",positionY:o="top",footer:c})=>{const a=Object(r.q)(null),i=Object(r.q)(null),[s,f]=Object(r.r)(!1);return r.a.createElement("div",{ref:i,className:"DropdownMenu "+(t||""),onKeyDown:e=>{const t=a.current;if(!s||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{f(!s)},isOpen:s}),r.a.createElement(u.a,{ref:a,containerRef:i,isOpen:s,className:t||"",positionX:d,positionY:o,footer:c,autoClose:!0,onClose:()=>{f(!1)}},n))}},function(e,t,n){"use strict";var r=n(0);t.a=(e,t,n,u,d)=>{const[o,c]=Object(r.r)(-1);Object(r.n)(()=>{c(-1);const n=e.current;t&&n&&!d&&(n.tabIndex=-1,n.focus())},[e,t,d]);return Object(r.m)(t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n(o);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,a=Array.from(u?r.querySelectorAll(u):r.children);let i=d&&a.indexOf(d)||o;if(38===t.keyCode&&i>0)i--;else if(40===t.keyCode&&i{if(e.length>24)return!1;if(!Boolean(e.match(u)))return!1;let t=0;for(;r.a.exec(e);)if(t++,t>3)return r.a.lastIndex=0,!1;return t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return o}));const r=["female_sign","male_sign","medical_symbol"];function u(e){const t=e.split("-").map(e=>parseInt(e,16));return String.fromCodePoint(...t)}function d(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 o(e){const t={categories:[],emojis:{}};for(let n=0;n{void 0!==e.props[r]&&void 0===t.props[r]&&g(n,r,e.props[r])}),u.forEach(r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?p(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(g(e,t,n),p(e,t,r))}(n,r,e.props[r],t.props[r]))})}(t,n,Object(r.b)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const u=new Set(t.children.map(e=>{const t="props"in e&&e.props.key;return d.p&&Object(r.f)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t}));let o=0;const c=e.children.reduce((e,r,d)=>{let c="props"in r?r.props.key:void 0;if(c&&!u.has(c))return f(n,r,void 0,t,-1),e;if(!c){const u=t.children[d],o=u&&"props"in u?u.props.key:void 0;if(!u||o)return f(n,r,void 0,t,-1),e;c="__indexKey#"+d}return e[c]={$element:r,index:o++,order:"props"in r?r.props.teactOrderKey:void 0},e},{});let a,i,s=[],l=0;t.children.forEach((e,r)=>{const u="props"in e?e.props.key:"__indexKey#"+r,d=c[u];if(!d)return a||(a=[],i=r),void a.push(e);a&&(s=s.concat(m(a,i,n,t)),i=void 0,a=void 0);const o="props"in e?e.props.teactOrderKey:void 0,b=d.index!==l&&d.order!==o,h=b&&l>d.index;b&&!h||l++,s.push(f(n,d.$element,e,t,r,{forceIndex:!0,...b&&{moveDirection:h?"down":"up"}}))}),a&&(s=s.concat(m(a,i,n,t)));return s}(e,t,n);const u=Math.max(e.children.length,t.children.length),o=[],c=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:c}:void 0);u&&o.push(u)}c&&n.appendChild(c);return o}(t,n,u?e:Object(r.b)(t))}}return n}function l(e,t,n,u){if(!Object(r.d)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){b(e=Object(r.i)(d),t,n,u);const o=e.children[0];Object(r.d)(o)&&(e.children=[l(o,e,0,u)]),d.isMounted=!0}return e}function b(e,t,n,r){const{componentInstance:u}=e;u.onUpdate=()=>{t.children[n]=f(r,t.children[n],u.$element,t,n,{skipComponentUpdate:!0})}}function h(e){if(Object(r.e)(e))return document.createTextNode("");if(Object(r.g)(e))return document.createTextNode(e.value);if(Object(r.d)(e))return h(e.children[0]);const{tag:t,props:n,children:u=[]}=e,d=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=d),Object.keys(n).forEach(e=>{p(d,e,n[e])}),e.children=u.map((t,n)=>f(d,void 0,t,e,n)),d}function m(e,t,n,r){if(1===e.length)return[f(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const u=document.createDocumentFragment(),d=e.map(e=>f(n,void 0,e,r,t,{fragment:u}));return n.childNodes[t]?n.insertBefore(u,n.childNodes[t]):n.appendChild(u),d}throw new Error("Unexpected input")}function p(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?Object(o.a)(e,t,n):t.startsWith("data-")||a.has(t)?e.setAttribute(t,n):c.has(t)||(e[i[t]||t]=n))}function g(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?Object(o.c)(e,t,n):t.startsWith("data-")||a.has(t)?e.removeAttribute(t):c.has(t)||delete e[i[t]||t]}t.a={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=Object(u.a)(s),s[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=s[n];r.children=[f(t,r.children[0],e,r,0)]}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(0),u=n(4),d=n(39),o=n(23),c=n(2),a=n(3),i=n(8),s=n(27);var f=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openUserInfo"]))(({className:e,sender:t,openUserInfo:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t.id})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("UserLink",e),onClick:d},u):u});var l=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["focusMessage"]))(({className:e,message:t,children:n,focusMessage:u})=>{const d=Object(r.m)(()=>{t&&u({chatId:t.chatId,messageId:t.id})},[u,t]);return t?r.a.createElement(s.a,{className:Object(i.a)("MessageLink",e),onClick:d},n):n});var b=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openChat"]))(({className:e,chatId:t,openChat:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("ChatLink",e),onClick:d},u):u});function h(e,t,n,c,a,i,s={}){if(!t.content.action)return[];const{text:f}=t.content.action,h=[],g={...s,maxTextLength:16};let y,v=p(f,"%action_origin%",n?!s.isEmbedded&&function(e,t,n){return Object(u.fb)(t)?function(e,t,n){const c=Object(d.a)(Object(u.l)(e,t));if(n)return c;return r.a.createElement(b,{className:"action-link",chatId:t.id},t&&Object(o.a)(c))}(e,t,n):m(t,n)}(e,n,s.asPlain)||" ":"User");return y=v.pop(),h.push(...v),v=p(y,"%target_user%",c?m(c,s.asPlain):"User"),y=v.pop(),h.push(...v),v=p(y,"%message%",a?function(e,t,n={}){const c=Object(u.N)(e,t),{photo:a,video:i,document:s,sticker:f}=Object(u.v)(t),b=c&&!a&&!i&&!s&&!f;let h=Object(d.a)(c,n.maxTextLength);a?h="a photo":i?h=i.isGif?"a GIF":"a video":s?h="a document":f&&(h=`«${c}»`);if(n.asPlain)return b?`«${h}»`:h;if(b)return r.a.createElement("span",null,"«",r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h)),"»");return r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h))}(e,a,g):"a message"),y=v.pop(),h.push(...v),v=p(y,"%product%",a?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(a):"a product"),y=v.pop(),h.push(...v),v=p(y,"%target_chat%",i?function(e,t){if(t)return"another chat";return r.a.createElement(b,{className:"action-link",chatId:e},"another chat")}(i,s.asPlain):"another chat"),h.push(...v),s.asPlain?h.join("").trim():h}function m(e,t){const n=Object(d.a)(Object(u.Z)(e));return t?n:r.a.createElement(f,{className:"action-link",sender:e},e&&Object(o.a)(n))}function p(e,t,n){const r=e.indexOf(t);if(r<0||!n)return[e];const u=[];return u.push(e.substring(0,r)),u.push(n),u.push(e.substring(r+t.length)),u}},function(e,t){},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return d})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const u=-1,d="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var r=n(0),u=n(2),d=n(3),o=n(6);t.a=Object(u.h)((e,{userId:t})=>({userOrChat:t?Object(o.Gb)(e,t):void 0}),(e,t)=>Object(d.l)(t,["openChat","openChatByUsername"]))(({username:e,userOrChat:t,children:n,openChat:u,openChatByUsername:d})=>r.a.createElement("a",{onClick:()=>{t?u({id:t.id}):e&&d({username:e.substring(1)})},className:"text-entity-link",dir:"auto"},n))},function(e,t,n){"use strict";var r=n(61),u=n(40);let d=!1;const o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,c=(e,t,n)=>(1-n)*e+n*t,a=Object.keys(u).map(e=>({property:e,colors:[i(u[e][0]),i(u[e][1])]}));function i(e){const t=o.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 s(e,t,n=1){a.forEach(({property:r,colors:u})=>{const d=Math.round(c(u[e].r,u[t].r,n)),o=Math.round(c(u[e].g,u[t].g,n)),a=Math.round(c(u[e].b,u[t].b,n)),i=void 0!==u[e].a?Math.round(c(u[e].a,u[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==i?`rgba(${d},${o},${a},${i/255})`:`rgb(${d},${o},${a})`)})}t.a=(e,t)=>{const n="dark"===e,u=d&&t,o=n?0:1,c=n?1:0,a=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),d&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add("theme-"+e),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout(()=>{document.documentElement.classList.remove("no-animations")},500),d=!0,u?Object(r.b)(()=>{const e=Math.min((Date.now()-a)/200,1);return s(o,c,function(e){return 1-(1-e)**3.5}(e)),e<1}):s(o,c)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(1);function u(e){"function"==typeof window.navigator.setAppBadge&&window.navigator.setAppBadge(e).catch(e=>{r.p&&console.error(e)})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(0);function u(e,t,n){Object(r.n)(()=>{const r=e=>{const r=t.current,u=e.target;r&&u&&(r.contains(e.target)&&!u.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}},[e,t,n])}},function(e,t,n){e.exports=function(){return new Worker(n.p+"7c2292f972e10d28cc51.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"01705582fc3eca0e007b.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0dbbe0a906f6c2adf071.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"a66075669d8d0ac2d740.worker.js")}},function(e,t,n){"use strict";var r=n(2),u=n(7),d=n(14),o=n(77);Object(r.b)("init",e=>{const{theme:t,animationLevel:n,messageTextSize:r,language:c}=e.settings.byKey;Object(d.c)(c),document.documentElement.style.setProperty("--message-text-size",r+"px"),document.body.classList.add("initial"),document.body.classList.add("animation-level-"+n),document.body.classList.add(u.l?"is-touch-env":"is-pointer-env"),Object(o.a)(t,n>0),u.j&&document.body.classList.add("is-safari"),u.e?document.body.classList.add("is-ios"):u.b&&document.body.classList.add("is-android")}),Object(r.b)("setIsUiReady",(e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}}),Object(r.b)("setAuthRememberMe",(e,t,n)=>({...e,authRememberMe:Boolean(n)})),Object(r.b)("clearAuthError",e=>({...e,authError:void 0}))},function(e,t,n){"use strict";var r=n(2),u=n(1),d=n(10),o=n(29),c=n(12),a=n(78),i=n(19);Object(r.b)("initApi",(e,t)=>{(async()=>{u.E?Object(i.d)():(await Object(i.c)(),Object(i.a)()),Object(d.c)(t.apiUpdate,Object(i.e)())})()}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return Object(d.a)("provideAuthPhoneNumber",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthCode",(e,t,n)=>{const{code:r}=n;return Object(d.a)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthPassword",(e,t,n)=>{const{password:r}=n;return Object(d.a)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("uploadProfilePhoto",(e,t,n)=>{const{file:r}=n;Object(d.a)("uploadProfilePhoto",r)}),Object(r.b)("signUp",(e,t,n)=>{const{firstName:r,lastName:u}=n;return Object(d.a)("provideAuthRegistration",{firstName:r,lastName:u}),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("returnToAuthPhoneNumber",e=>(Object(d.a)("restartAuth"),{...e,authError:void 0})),Object(r.b)("gotToAuthQrCode",e=>(Object(d.a)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0})),Object(r.b)("saveSession",(e,t,n)=>{const{sessionData:r}=n;r?Object(i.f)(n.sessionData,e.currentUserId):Object(i.b)()}),Object(r.b)("signOut",()=>{(async()=>{await Object(o.d)(),await Object(d.a)("destroy"),Object(r.d)().reset()})()}),Object(r.b)("reset",()=>{Object(i.b)(),c.b(u.N),c.b(u.O),c.b(u.P),c.b(u.m);const e=u.F.replace(/\d+$/,""),t=(u.F.match(/\d+$/)||[0])[0];for(let n=0;n{(async()=>{await Object(d.a)("disconnect")})()}),Object(r.b)("loadNearestCountry",e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await Object(d.a)("fetchNearestCountry");Object(r.g)({...Object(r.e)(),authNearestCountry:e})})()}),Object(r.b)("setDeviceToken",(e,t,n)=>{Object(r.g)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})}),Object(r.b)("deleteDeviceToken",e=>{const t={...e};delete t.push,Object(r.g)(t)})},function(e,t){var n,r,u=e.exports={};function d(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function c(e){if(n===setTimeout)return setTimeout(e,0);if((n===d||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:d}catch(e){n=d}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,i=[],s=!1,f=-1;function l(){s&&a&&(s=!1,a.length?i=a.concat(i):f=-1,i.length&&b())}function b(){if(!s){var e=c(l);s=!0;for(var t=i.length;t;){for(a=i,i=[];++f1)for(var n=1;n{switch(u.p&&"updateUserStatus"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){Object(d.c)(),Object(c.c)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=Object(r.e)();const n="authorizationStateReady"===t.authState,u=e.authorizationState;switch(Object(r.g)({...t,authState:u,authIsLoading:!1}),t=Object(r.e)(),u){case"authorizationStateLoggingOut":Object(r.g)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":Object(r.g)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":Object(r.g)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":Object(r.g)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":if(n)break;Object(r.g)({...t,isLoggingOut:!1,lastSyncTime:Date.now()})}}(n);break;case"updateAuthorizationError":!function(e){Object(r.g)({...Object(r.e)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=Object(r.e)();Object(r.g)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?Object(r.d)().sync():"connectionStateBroken"===t&&Object(r.d)().signOut()}(n);break;case"updateSession":!function(e){if(!Object(r.e)().authRememberMe)return;const{sessionData:t}=e;Object(r.d)().saveSession({sessionData:t})}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;Object(r.g)({...Object(o.nb)(Object(r.e)(),t.id,t),currentUserId:t.id}),function(e){const t=localStorage.getItem(u.nb);if(!t)return;const n=JSON.parse(t);n.id=e,localStorage.setItem(u.nb,JSON.stringify(n))}(t.id)}(n);break;case"error":"SESSION_REVOKED"===n.error.message&&t.signOut(),t.showError({error:n.error})}})},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(22),function(){function e(){var t=Error.call(this,"ServiceWorker is not supported.");return Object.setPrototypeOf(t,e.prototype),t}e.prototype=Object.create(Error.prototype)}();var r=n.p+"serviceWorker.js";var u=n(1),d=n(2),o=n(7),c=n(29);function a(e){const t=e.data;if(!t.type)return;const n=Object(d.d)();switch(t.type){case"focusMessage":n.focusMessage(t.payload)}}function i(){navigator.serviceWorker.removeEventListener("message",a),navigator.serviceWorker.addEventListener("message",a),Object(c.a)()}o.k&&(window.addEventListener("load",async()=>{try{await navigator.serviceWorker.register(r),u.p&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(u.p&&console.log("[SW] ServiceWorker ready"),i()):(u.p&&console.error("[SW] ServiceWorker not available"),Object(d.d)().showError({error:{message:"SERVICE_WORKER_DISABLED"}}))}catch(e){u.p&&console.error("[SW] ServiceWorker registration failed: ",e)}}),window.addEventListener("focus",async()=>{await navigator.serviceWorker.ready,i()}));var s=n(66);const f={isLeftColumnShown:!0,isChatInfoShown:!1,uiReadyState:0,authRememberMe:!0,blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{}},scheduledMessages:{byChatId:{}},chatFolders:{byId:{},activeChatFolder:0},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},emojiKeywords:{},gifs:{saved:{},search:{}},globalSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},mediaViewer:{},audioPlayer:{},forwardMessages:{},pollResults:{},payment:{},notifications:[],errors:[],activeSessions:[],settings:{byKey:{messageTextSize:u.s,animationLevel:u.d,messageSendKeyCombo:"enter",theme:"light",shouldAutoDownloadMediaFromContacts:!0,shouldAutoDownloadMediaInPrivateChats:!0,shouldAutoDownloadMediaInGroups:!0,shouldAutoDownloadMediaInChannels:!0,shouldAutoPlayGifs:!0,shouldAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en"},themes:{light:{isBlurred:!0,patternColor:u.t},dark:{isBlurred:!0,patternColor:u.o}},privacy:{},notifyExceptions:{}},twoFaSettings:{}};var l=n(5),b=n(9),h=n(3),m=n(6);const p=Object(b.g)((function(){Object(b.c)(()=>{if(!g)return;const e=Object(d.e)();if(e.isLoggingOut)return;const t={...f,...Object(h.l)(e,["authState","authPhoneNumber","authRememberMe","authNearestCountry","currentUserId","contactList","chatFolders","topPeers","recentEmojis","emojiKeywords","push"]),isChatInfoShown:v(e),users:w(e),chats:O(e),messages:I(e),globalSearch:{recentlyFoundChatIds:e.globalSearch.recentlyFoundChatIds},settings:j(e)},n=JSON.stringify(t);localStorage.setItem(u.B,n)})}),1e3,!1);let g=!1;function y(e){if(!u.A){if(localStorage.getItem(u.nb)||localStorage.getItem(u.H))return g=!0,Object(d.a)(p),function(e){u.p&&console.time("global-state-cache-read");const t=localStorage.getItem(u.B),n=t?JSON.parse(t):void 0;u.p&&console.timeEnd("global-state-cache-read");n&&(n.settings.byKey={...e.settings.byKey,...n.settings.byKey},n.settings.themes={...e.settings.themes,...n.settings.themes},n.chatFolders={...e.chatFolders,...n.chatFolders});return{...e,...n}}(e);g=!1}}function v(e){return window.innerWidth>u.ab&&e.isChatInfoShown}function w(e){const{users:{byId:t,selectedId:n}}=e,r=[...(e.chats.listIds.active||[]).slice(0,u.z).filter(e=>e>0),...Object.keys(t)].slice(0,u.C);return{byId:Object(h.l)(t,r),selectedId:window.innerWidth>u.ab?n:void 0}}function O(e){const t=[...(e.chats.listIds.active||[]).slice(0,u.z)],{chatId:n}=Object(m.y)(e)||{};return{...e.chats,byId:Object(h.l)(e.chats.byId,n?[...t,n]:t),listIds:{active:t},isFullyLoaded:{},orderedPinnedIds:{active:e.chats.orderedPinnedIds.active}}}function I(e){const t={},{chatId:n}=Object(m.y)(e)||{};[...(e.chats.listIds.active||[]).slice(0,u.z),...n?[n]:[]].forEach(n=>{const r=e.messages.byChatId[n];if(!r)return;const u=r.threadsById[l.MAIN_THREAD_ID];u&&u.viewportIds&&(t[n]={byId:Object(h.l)(r.byId,u.viewportIds),threadsById:{[l.MAIN_THREAD_ID]:u}})});const r=Object(m.y)(e);return{byChatId:t,messageLists:!r||o.g?void 0:[{...r,threadId:l.MAIN_THREAD_ID,type:"thread"}]}}function j(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}u.A||(Object(d.b)("saveSession",()=>{g=!0,Object(d.a)(p)}),Object(d.b)("reset",()=>{g=!1,Object(d.f)(p),localStorage.removeItem(u.B)})),Object(d.b)("init",()=>{const e=Object(h.d)(f),t=y(e)||e,n=Object(m.y)(t)||{};return window.history.replaceState(n,""),t});var C=n(0),E=n(56);const S=String(Date.now()+Math.random());let M;localStorage.setItem("tt-active-tab",S);const A=window.setInterval(()=>{M&&localStorage.getItem("tt-active-tab")!==S&&(M(),clearInterval(A))},2e3);var k=n(34),T=(n(84),n(85),n(87),n(31)),N=n(35),P=n(13);const D=["400 1em Roboto","500 1em Roboto"];function F(){if("fonts"in document)return Promise.all(D.map(e=>document.fonts.load(e)))}var L=n(54),B=n(11),x=n(8),R=(n(89),n.p+"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg"),U=n.p+"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg";function _(){const{listIds:e,byId:t}=Object(d.e)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map(e=>{const n=t[e];if(!n)return;const r=Object(T.d)(n);return r?L.b(r,l.ApiMediaFormat.DataUri):void 0}))}const G={main:()=>Promise.all([Object(B.d)(B.a.Main,"Main").then(F),_()]),authPhoneNumber:()=>Promise.all([F(),Object(P.g)(R)]),authCode:()=>Object(P.g)(U),authPassword:()=>Object(P.g)(U),authQrCode:F};var $=Object(d.h)(e=>{const{theme:t}=e.settings.byKey,{background:n,backgroundColor:r}=e.settings.themes[t]||{};return{uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(n),hasCustomBackgroundColor:Boolean(r),isRightColumnShown:Object(m.W)(e)}},(e,t)=>Object(h.l)(t,["setIsUiReady"]))(({page:e,children:t,hasCustomBackground:n,hasCustomBackgroundColor:r,isRightColumnShown:u,setIsUiReady:d})=>{const[o,c]=Object(k.a)(),{shouldRender:a,transitionClassNames:i}=Object(N.a)(!o,void 0,!0);return Object(C.n)(()=>{let t;return Promise.race([Object(b.e)(700),(async()=>{try{await G[e]()}catch(e){}})()]).then(()=>{c(),d({uiReadyState:1}),t=window.setTimeout(()=>{d({uiReadyState:2})},1e3)}),()=>{t&&(clearTimeout(t),t=void 0),d({uiReadyState:0})}},[]),C.a.createElement("div",{id:"UiLoader"},t,a&&C.a.createElement("div",{className:Object(x.a)("mask",i)},"main"===e?C.a.createElement(C.a.Fragment,null,C.a.createElement("div",{className:"left"}),C.a.createElement("div",{className:Object(x.a)("middle",n&&"custom-bg-image",r&&"custom-bg-color",u&&"with-right-column")}),u&&C.a.createElement("div",{className:"right"})):C.a.createElement("div",{className:"blank"})))}),W=n(18),H=n(32),K=n(46),z=n(45),V=n(16),q=n(52),J=n(23),Y=n(62),Q=n(42),Z=n(21);n(98);const X=200+u.c;var ee=Object(C.h)(({id:e,value:t,isLoading:n,onChange:r})=>{const u=Object(C.q)(null),[d,o]=Object(C.r)(),[c,a]=Object(C.r)(W.a);function i(e){o(e),a(function(e=""){return e.length?W.a.filter(t=>Object(q.a)(t.name,e)):W.a}(e))}const s=Object(C.m)(e=>{const{countryId:t}=e.currentTarget.firstElementChild.dataset,n=W.a.find(e=>e.id===t);n&&r(n),setTimeout(()=>i(void 0),X)},[r]),f=Object(C.m)(e=>{i(e.currentTarget.value)},[]),l=Object(C.m)(e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===d&&(n.value=""),i(n.value)},[d,t]);return C.a.createElement(Y.a,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:o})=>{const c=()=>{if(o)return;setTimeout(()=>{u.current.select()},50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},a=void 0!==d?d:t&&t.name||"";return C.a.createElement("div",{className:Object(x.a)("input-group",t&&"touched")},C.a.createElement("input",{ref:u,className:Object(x.a)("form-control",o&&"focus"),type:"text",id:e,value:a,autoComplete:"off",onClick:c,onFocus:c,onInput:f,onKeyDown:l}),C.a.createElement("label",null,"Country"),n?C.a.createElement(Z.a,{color:"black"}):C.a.createElement("i",{onClick:c,className:Object(x.a)("css-icon-down",o&&"open")}))}},c.map(e=>C.a.createElement(Q.a,{key:e.id,className:t&&e.id===t.id?"selected":"",onClick:s},C.a.createElement("span",{"data-country-id":e.id}),C.a.createElement("span",{className:"country-flag"},Object(J.a)(e.flag,["hq_emoji"])),C.a.createElement("span",{className:"country-name"},e.name),C.a.createElement("span",{className:"country-code"},e.code))),!c.length&&C.a.createElement(Q.a,{key:"no-results",className:"no-results",disabled:!0},C.a.createElement("span",null,"No countries matched your filter.")))});let te=!1;var ne=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),(e,t)=>Object(h.l)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","gotToAuthQrCode"]))(({connectionState:e,authState:t,authPhoneNumber:n,authIsLoading:r,authIsLoadingQrCode:u,authError:d,authRememberMe:c,authNearestCountry:a,setAuthPhoneNumber:i,setAuthRememberMe:s,loadNearestCountry:f,clearAuthError:l,gotToAuthQrCode:b})=>{const h=Object(C.q)(null),[m,p]=Object(C.r)(),[g,y]=Object(C.r)(),[v,w]=Object(C.r)(!1),[O,I]=Object(C.r)(),j=m?`${m.code} ${g||""}`:g,E=j&&j.replace(/[^\d]+/g,"").length>=7;Object(C.n)(()=>{o.l||h.current.focus()},[m]),Object(C.n)(()=>{"connectionStateReady"!==e||a||f()},[e,a,f]),Object(C.n)(()=>{!a||m||v||p(Object(W.d)(a))},[m,a,v]);const S=Object(C.m)(e=>{const t=Object(W.e)(e),n=!m||t&&t.id!==m.id?t:m;e.length?(!m||n&&n.code!==m.code)&&p(n):p(void 0),y(Object(W.b)(e,n))},[m]);Object(C.n)(()=>{void 0===g&&n&&S(n)},[n,g,S]),Object(C.o)(()=>{h.current&&O&&h.current.setSelectionRange(...O)},[O]);const M=Object(C.m)(e=>{d&&l(),te||(te=!0,F(),Object(P.g)(U));const{value:t,selectionStart:n,selectionEnd:r}=e.target;I(n&&r&&r{s(e.target.checked)},[s]);const k="authorizationStateWaitPhoneNumber"===t;return C.a.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},C.a.createElement("div",{className:"auth-form"},C.a.createElement("div",{id:"logo"}),C.a.createElement("h2",null,"Sign in to Telegram"),C.a.createElement("p",{className:"note"},"Please confirm your country and",C.a.createElement("br",null),"enter your phone number."),C.a.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),r||E&&i({phoneNumber:j})}},C.a.createElement(ee,{id:"sign-in-phone-code",value:m,isLoading:!a&&!m,onChange:p}),C.a.createElement(z.a,{ref:h,id:"sign-in-phone-number",label:"Phone Number",value:j,error:d,inputMode:"tel",onChange:M}),C.a.createElement(K.a,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(c),onChange:A}),E&&(k?C.a.createElement(H.a,{type:"submit",ripple:!0,isLoading:r},"Next"):C.a.createElement(V.a,null)),k&&C.a.createElement(H.a,{isText:!0,ripple:!0,isLoading:u,onClick:b},"Log in by QR code"))))})),re=n(17);var ue=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthCode");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});var de=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthPassword");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});var oe=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthRegister");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});var ce=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthQrCode");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});n(99);var ae=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["reset","initApi"]))(({authState:e,reset:t,initApi:n})=>{switch(Object(C.n)(()=>{t(),n()},[t,n]),Object(C.n)(()=>{},[]),e){case"authorizationStateWaitCode":return C.a.createElement($,{page:"authCode",key:"authCode"},C.a.createElement(ue,null));case"authorizationStateWaitPassword":return C.a.createElement($,{page:"authPassword",key:"authPassword"},C.a.createElement(de,null));case"authorizationStateWaitRegistration":return C.a.createElement(oe,null);case"authorizationStateWaitQrCode":return C.a.createElement($,{page:"authQrCode",key:"authQrCode"},C.a.createElement(ce,null));case"authorizationStateWaitPhoneNumber":default:return C.a.createElement($,{page:"authPhoneNumber",key:"authPhoneNumber"},C.a.createElement(ne,null))}}));var ie=Object(C.h)(()=>{const e=Object(re.a)(B.a.Main,"Main");return e?C.a.createElement(e,null):void 0}),se=n.p+"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png";n(100);var fe=()=>C.a.createElement("div",{id:"AppInactive"},C.a.createElement("div",{className:"content"},C.a.createElement("img",{src:se,alt:""}),C.a.createElement("h3",{className:"title"},"Such error, many tabs"),C.a.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",C.a.createElement("br",null),"Please reload this page to continue using this tab or close it."),C.a.createElement("div",{className:"actions"},C.a.createElement(H.a,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function le(){return d.c.createElement($,{page:"main",key:"main"},d.c.createElement(ie,null))}var be=Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["disconnect"]))(({authState:e,disconnect:t})=>{const[n,r]=Object(k.a)(!1);if(Object(C.n)(()=>{Object(E.b)(),M=()=>{t(),document.title=`${u.eb}${u.D}`,r()}},[t,r]),n)return d.c.createElement(fe,null);if(e)switch(e){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return d.c.createElement(ae,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return le()}return localStorage.getItem(u.nb)||localStorage.getItem(u.H)?le():d.c.createElement(ae,null)});n(101);u.p&&console.log(">>> INIT"),Object(d.d)().init(),u.p&&console.log(">>> START INITIAL RENDER"),s.a.render(d.c.createElement(be,null),document.getElementById("root")),u.p&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",()=>{console.log("GLOBAL STATE",Object(d.e)())})}]); -//# sourceMappingURL=main.7c95ea3f46a28615bf1a.js.map \ No newline at end of file +!function(e){function t(t){for(var n,r,d=t[0],o=t[1],c=0,a=[];c=0&&w(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),I[n].renderTimes.push(t),I[n].renderCount++}}catch(t){Object(c.a)(t),u=e.renderedValue}if(e.isMounted&&u===e.renderedValue)return e.$element;e.renderedValue=u;const d=O(u);return e.$element=y(e,[d]),e.$element}function C(e,t){return typeof e!=typeof t||(e.type!==t.type||(b(e)&&b(t)?e.value!==t.value:h(e)&&h(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!m(e)||!m(t))&&(e.componentInstance.Component!==t.componentInstance.Component||e.props.key!==t.props.key)))}function E(e){p(e)&&(m(e)?function(e){if(!e.isMounted)return;e.hooks.memos.byCursor.forEach(e=>{e.current=null}),e.hooks.effects.byCursor.forEach(({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}}),e.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach(e=>{e.cleanup=null,e.effect=null,e.dependencies=null}),e.hooks.state.byCursor.forEach(e=>{e.value=null,e.nextValue=null,e.setter=null}),e.hooks.memos.byCursor.forEach(e=>{e.dependencies=null}),e.hooks=null,e.$element=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(e)}(e.componentInstance):e.target&&(Object(a.b)(e.target),e.target=null),e.children.forEach(E))}function S(e){return j(e),e.isMounted=!0,e.$element}function M(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;j(e),e.$element!==t&&e.onUpdate()}function A(e){return m(e)?A(e.children[0]):e.target}function k(e,t){m(e)?k(e.children[0],t):e.target=t}function T(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=Object(u.h)(()=>function e(t){t.isMounted&&(t.hooks.state.byCursor.forEach(e=>{e.value=e.nextValue}),t.prepareForFrame=Object(u.h)(()=>e(t)),t.forceUpdate=Object(u.i)(()=>M(t)))}(d)),d.forceUpdate=Object(u.i)(()=>M(d))),d.prepareForFrame(),d.forceUpdate(),r.r&&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 N(e,t,n){const{cursor:r,byCursor:u}=f.hooks.effects,d=f,o=()=>{if(!d.isMounted)return;const{cleanup:e}=u[r];if("function"==typeof e)try{e()}catch(e){Object(c.a)(e)}u[r].cleanup=t()};void 0!==u[r]&&n&&u[r].dependencies?n.some((e,t)=>e!==u[r].dependencies[t])&&e(o):e(o),u[r]={effect:t,dependencies:n,cleanup:u[r]?u[r].cleanup:void 0},f.hooks.effects.cursor++}function P(e,t){return N(u.b,e,t)}function D(e,t){return N(u.d,e,t)}function F(e,t){const{cursor:n,byCursor:r}=f.hooks.memos;let{current:u}=r[n]||{};return(void 0===r[n]||t.some((e,t)=>e!==r[n].dependencies[t]))&&(u=e()),r[n]={current:u,dependencies:t},f.hooks.memos.cursor++,u}function L(e,t){return F(()=>e,t)}function B(e){return F(()=>({current:e}),[])}function x(e,t=o.a,n=!1){return function(u){const d=B(u),c=B();return(!c.current||d.current&&!t(d.current,u))&&(r.p&&n&&console.log(`[Teact.memo] ${e.name}: Update is caused by:`,Object(o.b)(d.current,u).join(", ")),d.current=u,c.current=g(e,u)),c.current}}document.addEventListener("dblclick",()=>{console.log("COMPONENTS",Object(d.k)(Object.values(I),"renderCount","desc"))}),t.a={createElement:g,Fragment:s}},function(e,t,n){"use strict";n.d(t,"eb",(function(){return r})),n.d(t,"D",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"g",(function(){return o})),n.d(t,"p",(function(){return c})),n.d(t,"r",(function(){return a})),n.d(t,"E",(function(){return i})),n.d(t,"q",(function(){return s})),n.d(t,"nb",(function(){return f})),n.d(t,"H",(function(){return l})),n.d(t,"A",(function(){return b})),n.d(t,"B",(function(){return h})),n.d(t,"z",(function(){return m})),n.d(t,"C",(function(){return p})),n.d(t,"M",(function(){return g})),n.d(t,"N",(function(){return y})),n.d(t,"O",(function(){return v})),n.d(t,"P",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"F",(function(){return I})),n.d(t,"Y",(function(){return C})),n.d(t,"U",(function(){return E})),n.d(t,"V",(function(){return S})),n.d(t,"W",(function(){return M})),n.d(t,"i",(function(){return A})),n.d(t,"k",(function(){return k})),n.d(t,"j",(function(){return T})),n.d(t,"ob",(function(){return N})),n.d(t,"X",(function(){return P})),n.d(t,"y",(function(){return D})),n.d(t,"R",(function(){return F})),n.d(t,"Q",(function(){return L})),n.d(t,"fb",(function(){return B})),n.d(t,"Db",(function(){return x})),n.d(t,"a",(function(){return R})),n.d(t,"e",(function(){return U})),n.d(t,"d",(function(){return _})),n.d(t,"s",(function(){return G})),n.d(t,"u",(function(){return $})),n.d(t,"v",(function(){return W})),n.d(t,"w",(function(){return H})),n.d(t,"kb",(function(){return K})),n.d(t,"jb",(function(){return z})),n.d(t,"ab",(function(){return V})),n.d(t,"Z",(function(){return q})),n.d(t,"db",(function(){return J})),n.d(t,"cb",(function(){return Y})),n.d(t,"bb",(function(){return Q})),n.d(t,"J",(function(){return Z})),n.d(t,"c",(function(){return X})),n.d(t,"vb",(function(){return ee})),n.d(t,"wb",(function(){return te})),n.d(t,"qb",(function(){return ne})),n.d(t,"rb",(function(){return re})),n.d(t,"yb",(function(){return ue})),n.d(t,"ub",(function(){return de})),n.d(t,"zb",(function(){return oe})),n.d(t,"Ab",(function(){return ce})),n.d(t,"xb",(function(){return ae})),n.d(t,"Bb",(function(){return ie})),n.d(t,"sb",(function(){return se})),n.d(t,"tb",(function(){return fe})),n.d(t,"S",(function(){return le})),n.d(t,"T",(function(){return be})),n.d(t,"pb",(function(){return he})),n.d(t,"l",(function(){return me})),n.d(t,"gb",(function(){return pe})),n.d(t,"ib",(function(){return ge})),n.d(t,"hb",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"b",(function(){return we})),n.d(t,"h",(function(){return Oe})),n.d(t,"L",(function(){return Ie})),n.d(t,"K",(function(){return je})),n.d(t,"lb",(function(){return Ce})),n.d(t,"G",(function(){return Ee})),n.d(t,"Cb",(function(){return Se})),n.d(t,"x",(function(){return Me})),n.d(t,"I",(function(){return Ae})),n.d(t,"n",(function(){return ke})),n.d(t,"o",(function(){return Te})),n.d(t,"t",(function(){return Ne}));const r="Telegram",u=" [Inactive]",d="Telegram WebZ",o="1.0.7",c=!1,a=!1,i=!1,s="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",f="user_auth",l="GramJs:sessionId",b=!1,h="tt-global-state",m=30,p=5e3,g=!1,y="tt-media",v="tt-media-avatars",w="tt-media-progressive",O="tt-custom-bg",I="tt-lang-packs-v4",j=(new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),"undefined"!=typeof window&&window.innerHeight>=900),C=1,E=500,S=j?60:40,M=2*S,A=72,k=j?30:25,T=100,N=42,P=42,D=20,F=30,L=200,B=500,x=20,R=!1,U=2,_=U,G=16,$=1e4,W="editable-message-text",H="editable-message-text-modal",K=1440,z=1150,V=1275,q=925,J=600,Y=950,Q=450,Z=1e9,X=100,ee=13,te=11,ne=160,re=120,ue=64,de=48,oe=32,ce=64,ae=64,ie=160,se=140,fe=80,le="MEMOJI_STICKER",be=200,he=450,me="image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime",pe="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",ge=/^(?:https?:\/\/)?(?:t\.me\/)([\d\w_]+)(?:\/([\d]+))?$/gm,ye=/^(?:https?:\/\/)?(?:t\.me\/joinchat\/)([\d\w_]+)?$/gm,ve=777e3,we=0,Oe=1,Ie=10,je=5,Ce=2147483646,Ee=["android","ios","tdesktop","macos"],Se="TelegramTips",Me="https://bugs.telegram.org/?tag_ids=41&sort=time",Ae="#A2AF8E",ke="#0F0F0F",Te="#0a0a0a8c",Ne="rgba(90, 110, 70, 0.6)"},function(e,t,n){"use strict";n.d(t,"g",(function(){return y})),n.d(t,"e",(function(){return v})),n.d(t,"d",(function(){return w})),n.d(t,"b",(function(){return O})),n.d(t,"a",(function(){return I})),n.d(t,"f",(function(){return j})),n.d(t,"h",(function(){return C}));var r=n(0),u=n(1),d=n(26),o=n(28),c=n(9),a=n(24),i=n(3),s=n(22);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],m={},p=new Map;const g=Object(c.i)((function(){h.forEach(e=>e(l))}));function y(e){"object"==typeof e&&e!==l&&(l=e,g())}function v(){return l}function w(){return m}function O(e,t){b[e]||(b[e]=[],m[e]=t=>{!function(e,t){b[e]&&b[e].forEach(e=>{const n=e(l,m,t);n&&y(n)})}(e,t)}),b[e].push(t)}function I(e){h.push(e)}function j(e){const t=h.indexOf(e);-1!==t&&h.splice(t,1)}function C(e=(()=>({})),t=(()=>({}))){return n=>function u(c){u.DEBUG_contentComponentName=n.name;const[i]=Object(r.r)(Object(o.a)(p)),b=Object(d.a)();Object(r.n)(()=>()=>{p.delete(i)},[i]);let h=p.get(i);if(h||(h={mapStateToProps:e,mapReducersToProps:t,ownProps:c,areMappedPropsChanged:!1,forceUpdate:b,DEBUG_updates:0,DEBUG_componentName:n.name},p.set(i,h)),h.areMappedPropsChanged&&(h.areMappedPropsChanged=!1),!h.mappedProps||!Object(a.a)(h.ownProps,c)){h.ownProps=c;try{h.mappedProps={...e(l,c),...t(y,m)}}catch(e){Object(s.a)(e)}}return r.a.createElement(n,f({},h.mappedProps,c))}}u.p&&(window.getGlobal=v,document.addEventListener("dblclick",()=>{console.log("GLOBAL CONTAINERS",Object(i.k)(Object.values(p),"DEBUG_updates","desc"))}))},function(e,t,n){"use strict";function r(e,t){return e.reduce((e,n)=>(e[n[t]]=n,e),{})}function u(e,t){return Object.keys(e).reduce((n,r,u)=>(n[r]=t(e[r],r,u,e),n),{})}function d(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}function o(e,t){return t.reduce((t,n)=>(e[n]&&(t[n]=e[n]),t),{})}function c(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter(e=>!n.has(e)))}function a(e,t,n="asc"){return e.sort((e,r)=>{if(Array.isArray(t)){const[u,d]=Array.isArray(n)?n:[n,n],[o,c]=t;let a,i;if("function"==typeof o?(a=o(e)||0,i=o(r)||0):"string"==typeof o&&(a=e[o]||0,i=r[o]||0),a!==i)return"asc"===u?a-i:i-a;{let t,n;return"function"==typeof c?(t=c(e)||0,n=c(r)||0):"string"==typeof c&&(t=e[c]||0,n=r[c]||0),"asc"===d?t-n:n-t}}let u,d;return"function"==typeof t?(u=t(e)||0,d=t(r)||0):"string"==typeof t&&(u=e[t]||0,d=r[t]||0),"asc"===n?u-d:d-u})}function i(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e),[])}function s(e){return Array.from(new Set(e))}function f(e){return e.filter(Boolean)}function l(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function b(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function h(e,t){return e.filter(e=>t.has(e))}function m(e,t){const n=[];for(let r=0;r(t[n]=p(e[n]),t),{})}function g(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,"c",(function(){return r})),n.d(t,"i",(function(){return u})),n.d(t,"l",(function(){return d})),n.d(t,"m",(function(){return o})),n.d(t,"j",(function(){return c})),n.d(t,"k",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"o",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"a",(function(){return l})),n.d(t,"b",(function(){return b})),n.d(t,"f",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"d",(function(){return p})),n.d(t,"g",(function(){return g}))},function(e,t,n){"use strict";n.d(t,"Y",(function(){return r.b})),n.d(t,"Z",(function(){return r.c})),n.d(t,"ab",(function(){return r.d})),n.d(t,"xb",(function(){return r.g})),n.d(t,"pb",(function(){return r.e})),n.d(t,"wb",(function(){return r.f})),n.d(t,"Eb",(function(){return r.h})),n.d(t,"X",(function(){return r.a})),n.d(t,"lb",(function(){return u.w})),n.d(t,"kb",(function(){return u.v})),n.d(t,"ib",(function(){return u.t})),n.d(t,"nb",(function(){return u.y})),n.d(t,"jb",(function(){return u.u})),n.d(t,"ob",(function(){return u.z})),n.d(t,"m",(function(){return u.j})),n.d(t,"U",(function(){return u.p})),n.d(t,"l",(function(){return u.i})),n.d(t,"g",(function(){return u.e})),n.d(t,"h",(function(){return u.f})),n.d(t,"f",(function(){return u.d})),n.d(t,"mb",(function(){return u.x})),n.d(t,"gb",(function(){return u.r})),n.d(t,"q",(function(){return u.m})),n.d(t,"yb",(function(){return u.A})),n.d(t,"e",(function(){return u.c})),n.d(t,"c",(function(){return u.a})),n.d(t,"K",(function(){return u.o})),n.d(t,"k",(function(){return u.h})),n.d(t,"j",(function(){return u.g})),n.d(t,"hb",(function(){return u.s})),n.d(t,"Cb",(function(){return u.D})),n.d(t,"d",(function(){return u.b})),n.d(t,"Bb",(function(){return u.C})),n.d(t,"Ab",(function(){return u.B})),n.d(t,"p",(function(){return u.l})),n.d(t,"o",(function(){return u.k})),n.d(t,"fb",(function(){return u.q})),n.d(t,"J",(function(){return u.n})),n.d(t,"Db",(function(){return u.E})),n.d(t,"A",(function(){return i})),n.d(t,"zb",(function(){return s})),n.d(t,"F",(function(){return f})),n.d(t,"N",(function(){return l})),n.d(t,"O",(function(){return b})),n.d(t,"x",(function(){return h})),n.d(t,"L",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"tb",(function(){return g})),n.d(t,"ub",(function(){return y})),n.d(t,"qb",(function(){return v})),n.d(t,"db",(function(){return w})),n.d(t,"vb",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"V",(function(){return j})),n.d(t,"W",(function(){return C})),n.d(t,"sb",(function(){return E})),n.d(t,"rb",(function(){return S})),n.d(t,"v",(function(){return k})),n.d(t,"cb",(function(){return T})),n.d(t,"G",(function(){return N})),n.d(t,"P",(function(){return P})),n.d(t,"I",(function(){return D})),n.d(t,"t",(function(){return F})),n.d(t,"u",(function(){return L})),n.d(t,"M",(function(){return B})),n.d(t,"y",(function(){return x})),n.d(t,"H",(function(){return R})),n.d(t,"z",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"R",(function(){return G})),n.d(t,"E",(function(){return $})),n.d(t,"D",(function(){return W})),n.d(t,"C",(function(){return K})),n.d(t,"B",(function(){return z})),n.d(t,"b",(function(){return q})),n.d(t,"i",(function(){return J})),n.d(t,"S",(function(){return Y})),n.d(t,"T",(function(){return Q})),n.d(t,"bb",(function(){return Z})),n.d(t,"s",(function(){return X})),n.d(t,"w",(function(){return ee})),n.d(t,"r",(function(){return te})),n.d(t,"a",(function(){return ne}));var r=n(30),u=n(31),d=n(5),o=n(1),c=n(64);const a=new RegExp(o.gb,"i");function i(e){const{chatId:t,id:n}=e;return`msg${t}-${n}`}function s(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:Number(t[1]),messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function l(e,t,n=!1){const{text:r,photo:u,video:d,audio:o,voice:c,document:a,sticker:i,contact:s,poll:f,invoice:l}=t.content;if(t.groupedId)return`${n?"":"🖼 "}${r?r.text:e("lng_in_dlg_album")}`;if(u)return`${n?"":"🖼 "}${r?r.text:e("AttachPhoto")}`;if(d)return`${n?"":"📹 "}${r?r.text:e(d.isGif?"AttachGif":"AttachVideo")}`;if(i)return`${i.emoji} ${e("AttachSticker")} `;if(o){return`${n?"":"🎧 "}${[o.title,o.performer].filter(Boolean).join(" — ")||r&&r.text||e("AttachMusic")}`}return c?`${n?"":"🎤 "}${r?r.text:e("AttachAudio")}`:a?`${n?"":"📎 "}${r?r.text:a.fileName}`:s?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:l?"Invoice":r?r.text:"The message is not supported on this version of Telegram"}function b(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:c,poll:a,webPage:i,contact:s,invoice:f}=e.content;return t?t.text:n||r||u||d||o||c||s||a||i||f?void 0:"The message is not supported on this version of Telegram"}function h(e){const{text:t,sticker:n,photo:r,video:u,audio:d,voice:o,document:a,poll:i,webPage:s,contact:f}=e.content;return!!(n||u&&u.isRound)||!(!t||r||u||d||o||a||i||s||f)&&(Object(c.a)(t.text)||!1)}function m(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===h(e))return t.text}function p(e){const{text:t}=e.content;let n;if(t&&t.entities){let e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.TextUrl);if(e&&(n=e.url.match(a)),!n&&(e=t.entities.find(e=>e.type===d.ApiMessageEntityTypes.Url),e)){const{offset:r,length:u}=e;n=t.text.substring(r,r+u).match(a)}}if(!n&&t&&(n=t.text.match(a)),n)return{url:n[0],domain:n[3]}}function g(e){return e.isOutgoing}function y(e){return Boolean(e.replyToMessageId)}function v(e){return Boolean(e.forwardInfo)}function w(e){return!!e.content.action}function O(e){return e.chatId===o.mb&&E(e)}function I(e){return Boolean(e.senderId)&&e.senderId<0&&g(e)}function j(e,t){return t.id>0?Object(r.c)(t):Object(u.i)(e,t)}function C(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function E(e){return e.id>=o.J}function S(e){return e.content.action&&"historyClear"===e.content.action.type}var M=n(7),A=n(59);function k(e){return e.content}function T(e){return Boolean(N(e)||P(e)||x(e)||B(e)||function(e){return e.content.contact}(e)||R(e)||F(e)||L(e)||function(e){return e.content.voice}(e))}function N(e){return e.content.photo}function P(e){return e.content.video}function D(e){const{video:t}=e.content;return t&&t.isRound?t:void 0}function F(e){return e.content.action}function L(e){return e.content.audio}function B(e){return e.content.sticker}function x(e){return e.content.document}function R(e){return e.content.poll}function U(e){return e.content.invoice}function _(e){return e.content.webPage}function G(e){const t=_(e);return t?t.photo:void 0}function $(e){const t=function(e){const t=N(e)||P(e)||x(e)||B(e)||G(e);if(t)return t.thumbnail}(e);return t?t.dataUri:void 0}function W(e,t){const{photo:n,video:r,sticker:u,audio:d,voice:o,document:c}=e.content,a=G(e);if(!(n||r||u||a||d||o||c))return;const s=i(e);if(n||a)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return s+"?size=x";case"viewerPreview":return s+"?size=x";case"viewerFull":return s+"?size=z"}if(r)switch(t){case"micro":case"pictogram":return s+"?size=m";case"inline":if(V(e))return;return q(r)?H(r,s):s+"?size=z";case"viewerPreview":return s+"?size=m";case"viewerFull":return H(r,s);case"download":return s+"?download"}if(c)switch(t){case"micro":case"pictogram":case"inline":if(!Object(A.c)(c)||V(e))return;return s+"?size=m";default:return s}if(u)switch(t){case"micro":return;case"pictogram":return s+"?size=m";default:return s}if(d)switch(t){case"micro":case"pictogram":return;default:return H(d,s)}if(o)switch(t){case"micro":case"pictogram":return;default:return s}}function H(e,t){return M.i&&M.j?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function K(e,t){const{sticker:n,video:r,audio:u,voice:o}=e.content;return n&&"inline"===t&&n.isAnimated?d.ApiMediaFormat.Lottie:r&&M.i&&("viewerFull"===t||"inline"===t&&q(r))?d.ApiMediaFormat.Progressive:u||o?o&&!M.h?d.ApiMediaFormat.BlobUrl:d.ApiMediaFormat.Progressive:d.ApiMediaFormat.BlobUrl}function z(e){const{photo:t,video:n,webPage:r}=e.content;return t||r&&r.photo?`photo${e.date}.jpeg`:n?n.fileName:void 0}function V(e){const{photo:t,video:n,document:r}=e.content;return t&&t.blobUrl||n&&n.blobUrl||r&&r.previewBlobUrl}function q(e){return e.isGif||e.isRound||e.size<=10485760}function J(e,t,n=!1){const r=ee(e,t,"media");return n?r.reverse():r}function Y(e){return e.sizes.find(e=>"z"===e.type)||e.sizes.find(e=>"y"===e.type)||Q(e)}function Q(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 Z(e){if(e.width&&e.height)return e}function X(e,t,n=!1){const r=E(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ee(e,t,n){let r;switch(n){case"media":r=e=>{const t=P(e);return N(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=x;break;case"links":r=e=>_(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(a);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=L;break;default:return[]}return t.reduce((t,n)=>(e[n]&&r(e[n])&&t.push(n),t),[])}function te(e){const{audio:t,voice:n,video:r}=k(e),u=t||n||r;if(u)return u.duration}function ne(e,t){return`${e}_${t}`}n(60)},function(e,t,n){"use strict";var r=n(68);n.o(r,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return r.ApiMediaFormat})),n.o(r,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return r.ApiMessageEntityTypes})),n.o(r,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return r.MAIN_THREAD_ID})),n.o(r,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return r.MESSAGE_DELETED}));var u=n(69);n.o(u,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return u.ApiMediaFormat})),n.o(u,"ApiMessageEntityTypes")&&n.d(t,"ApiMessageEntityTypes",(function(){return u.ApiMessageEntityTypes})),n.o(u,"MAIN_THREAD_ID")&&n.d(t,"MAIN_THREAD_ID",(function(){return u.MAIN_THREAD_ID})),n.o(u,"MESSAGE_DELETED")&&n.d(t,"MESSAGE_DELETED",(function(){return u.MESSAGE_DELETED}));var d=n(70);n.d(t,"ApiMessageEntityTypes",(function(){return d.a})),n.d(t,"MAIN_THREAD_ID",(function(){return d.b})),n.d(t,"MESSAGE_DELETED",(function(){return d.c}));var o=n(71);n.o(o,"ApiMediaFormat")&&n.d(t,"ApiMediaFormat",(function(){return o.ApiMediaFormat}));var c=n(72);n.d(t,"ApiMediaFormat",(function(){return c.a}));n(73),n(74),n(75)},function(e,t,n){"use strict";n.d(t,"T",(function(){return Fe})),n.d(t,"nb",(function(){return Le})),n.d(t,"W",(function(){return Be})),n.d(t,"Gb",(function(){return a})),n.d(t,"f",(function(){return f})),n.d(t,"o",(function(){return l})),n.d(t,"P",(function(){return b})),n.d(t,"O",(function(){return h})),n.d(t,"Ab",(function(){return m})),n.d(t,"n",(function(){return p})),n.d(t,"g",(function(){return g})),n.d(t,"L",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"M",(function(){return w})),n.d(t,"j",(function(){return O})),n.d(t,"i",(function(){return I})),n.d(t,"N",(function(){return j})),n.d(t,"h",(function(){return C})),n.d(t,"q",(function(){return E})),n.d(t,"y",(function(){return D})),n.d(t,"r",(function(){return F})),n.d(t,"m",(function(){return L})),n.d(t,"qb",(function(){return B})),n.d(t,"Y",(function(){return R})),n.d(t,"gb",(function(){return U})),n.d(t,"x",(function(){return _})),n.d(t,"Hb",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"ob",(function(){return W})),n.d(t,"rb",(function(){return H})),n.d(t,"mb",(function(){return K})),n.d(t,"C",(function(){return z})),n.d(t,"E",(function(){return V})),n.d(t,"B",(function(){return q})),n.d(t,"cb",(function(){return J})),n.d(t,"Cb",(function(){return Y})),n.d(t,"G",(function(){return Q})),n.d(t,"Db",(function(){return Z})),n.d(t,"Eb",(function(){return X})),n.d(t,"Bb",(function(){return ee})),n.d(t,"a",(function(){return te})),n.d(t,"X",(function(){return ne})),n.d(t,"k",(function(){return re})),n.d(t,"pb",(function(){return ue})),n.d(t,"D",(function(){return de})),n.d(t,"l",(function(){return oe})),n.d(t,"I",(function(){return ce})),n.d(t,"U",(function(){return ae})),n.d(t,"fb",(function(){return ie})),n.d(t,"tb",(function(){return se})),n.d(t,"K",(function(){return fe})),n.d(t,"b",(function(){return le})),n.d(t,"e",(function(){return be})),n.d(t,"Fb",(function(){return he})),n.d(t,"lb",(function(){return me})),n.d(t,"H",(function(){return pe})),n.d(t,"R",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"S",(function(){return ve})),n.d(t,"V",(function(){return we})),n.d(t,"J",(function(){return Oe})),n.d(t,"ab",(function(){return Ie})),n.d(t,"Q",(function(){return je})),n.d(t,"sb",(function(){return Ce})),n.d(t,"bb",(function(){return Ee})),n.d(t,"ub",(function(){return Se})),n.d(t,"vb",(function(){return Me})),n.d(t,"wb",(function(){return Ae})),n.d(t,"t",(function(){return xe})),n.d(t,"A",(function(){return ke})),n.d(t,"w",(function(){return Te})),n.d(t,"v",(function(){return Ne})),n.d(t,"Z",(function(){return Pe})),n.d(t,"u",(function(){return De})),n.d(t,"z",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"xb",(function(){return k})),n.d(t,"yb",(function(){return T})),n.d(t,"c",(function(){return N})),n.d(t,"F",(function(){return P})),n.d(t,"hb",(function(){return Re})),n.d(t,"ib",(function(){return Ue})),n.d(t,"kb",(function(){return _e})),n.d(t,"zb",(function(){return Ge})),n.d(t,"eb",(function(){return i})),n.d(t,"db",(function(){return s}));var r=n(20),u=n(7),d=n(5),o=n(1),c=n(4);function a(e,t){return e.users.byId[t]}function i(e){return e.settings.byKey}function s(e){return e.settings.notifyExceptions}function f(e,t){return e.chats.byId[t]}function l(e,t){const n=Object(c.U)(t);return!!n&&a(e,n)}function b(e,t){return t===e.currentUserId}function h(e,t){const n=l(e,t);return n&&Object(c.wb)(n)}function m(e){return Object.values(e.chats.byId).find(({isSupport:e})=>e)}function p(e,t){if(!Object(c.lb)(t.id)&&!Object(c.jb)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==o.Q?t.fullInfo.members.reduce((t,{userId:n})=>e.users.byId[n]&&Object(c.xb)(e.users.byId[n])&&n!==e.currentUserId?t+1:t,0):t.fullInfo.onlineCount}function g(e,t){const n=f(e,t),r=n&&Object(c.U)(n),u=r&&a(e,r);if(u&&Object(c.wb)(u))return u}function y(e,t){const n=f(e,t),r=g(e,t);if(!n||!r)return!1;if(n.lastMessage&&Object(c.rb)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:o}=u.threadsById[d.MAIN_THREAD_ID]||{};return o&&!o.length}function v(e){return Boolean(e.chats.listIds.active)}function w(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 O(e,t){const n=f(e,t);if(n&&w(e,t))return n.folderId===o.h?"archived":"active"}function I(e,t){return e.chatFolders.byId[t]}function j(e,t,n=o.b){const{active:r,archived:u}=e.chats.orderedPinnedIds;if(n===o.b)return!!r&&r.includes(t);if(n===o.h)return!!u&&u.includes(t);const{byId:d}=e.chatFolders,{pinnedChatIds:c}=d[n]||{};return!!c&&c.includes(t)}function C(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find(e=>e.username&&e.username.toLowerCase()===n)}function E(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId;return t.reduce((t,r)=>{const u=n[r];return u&&u.unreadCount&&!Object(c.Cb)(u,i(e),s(e))?t+u.unreadCount:t},0)}var S=n(3);function M(e){return e.stickers.search}function A(e){return e.gifs.search}function k(e,t){return e.stickers.setsById[t]}function T(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach(({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))}),r}function N(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=t.replace("️","");return n.stickers.find(e=>e.emoji===t||e.emoji===r)}function P(e,t){return e.emojiKeywords[t]&&void 0!==e.emojiKeywords[t]?e.emojiKeywords[t]:void 0}function D(e){const{messageLists:t}=e.messages;if(t&&t.length)return t[t.length-1]}function F(e){const{chatId:t}=D(e)||{};return t?f(e,t):void 0}function L(e,t){const n=e.messages.byChatId[t];return n?n.byId:void 0}function B(e,t){const n=e.scheduledMessages.byChatId[t];return n?n.byId:void 0}function x(e,t,n,r){const u=e.messages.byChatId[t];if(!u)return;const d=u.threadsById[n];return d?d[r]:void 0}function R(e,t,n){return x(e,t,n,"listedIds")}function U(e,t,n){return x(e,t,n,"outlyingIds")}function _(e,t,n,r){switch(r){case"thread":return G(e,t,n);case"pinned":return $(e,t);case"scheduled":return W(e,t)}}function G(e,t,n){return x(e,t,n,"viewportIds")}function $(e,t){return x(e,t,d.MAIN_THREAD_ID,"pinnedIds")}function W(e,t){return x(e,t,d.MAIN_THREAD_ID,"scheduledIds")}function H(e,t,n){return x(e,t,n,"scrollOffset")}function K(e,t,n){return x(e,t,n,"replyingToId")}function z(e,t,n){return x(e,t,n,"editingId")}function V(e,t){return x(e,t,d.MAIN_THREAD_ID,"editingScheduledId")}function q(e,t,n){return x(e,t,n,"draft")}function J(e,t,n){return x(e,t,n,"noWebPage")}function Y(e,t,n){return x(e,t,n,"threadInfo")}function Q(e,t,n){return x(e,t,n,"firstMessageId")}function Z(e,t,n){if(n===d.MAIN_THREAD_ID)return f(e,t);const r=Y(e,t,n);return r?f(e,r.originChannelId||t):void 0}function X(e,t,n){if(n===d.MAIN_THREAD_ID)return;const r=Y(e,t,n);return r?r.topMessageId:void 0}function ee(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:u,replyToTopMessageId:d}=n;return u||d?Object.values(r.threadsById).find(e=>e.threadInfo&&(u&&u===e.threadInfo.topMessageId||d&&d===e.threadInfo.topMessageId)):void 0}function te(e,t,n){const r=D(e);if(!r)return!1;const{threadInfo:u}=ee(e,t,n)||{};return t===r.chatId&&(r.threadId===d.MAIN_THREAD_ID||u&&r.threadId===u.threadId)}function ne(e,t,n){const r=G(e,t,n);if(!r||!r.length)return!0;let u;if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n||!n.lastMessage)return!0;u=n.lastMessage.id}else{const r=Y(e,t,n);if(!r||!r.lastMessageId)return;u=r.lastMessageId}return u>=o.J&&!re(e,t,u)||r[r.length-1]>=u}function re(e,t,n){const r=L(e,t);return r?r[n]:void 0}function ue(e,t,n){const r=B(e,t);return r?r[n]:void 0}function de(e,t,n,r){if("scheduled"===r){const n=V(e,t);return n?ue(e,t,n):void 0}{const r=z(e,t,n);return r?re(e,t,r):void 0}}function oe(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 ce(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function ae(e,t){const n=ce(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function ie(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=f(e,t.chatId)||{};return Object(c.sb)(t)||!n||n0?a(e,n):f(e,n)}function fe(e,t){const{forwardInfo:n}=t;if(n)return n.isChannelPost&&n.fromChatId?f(e,n.fromChatId):n.senderUserId?a(e,n.senderUserId):void 0}function le(e,t,n){const r=f(e,t.chatId);if(!r||r.isRestricted)return{};const u=Object(c.lb)(r.id),d=b(e,t.chatId),o=Object(c.ib)(r),a=Object(c.nb)(r),i=Object(c.jb)(r),s=Object(c.vb)(t),l=Object(c.tb)(t),h=Object(c.db)(t),{content:m}=t,p=(d||Date.now()-1e3*t.date<1728e5)&&!(m.sticker||m.contact||m.poll||m.action||m.audio||m.video&&m.video.isRound)&&!Object(c.qb)(t)&&!t.viaBotId,g=Object(c.e)(r,n)&&!s,y=u||r.isCreator||!i&&!Object(c.yb)(r,"pinMessages")||Object(c.q)(r,"pinMessages");let v=!h&&y,w=!1;const O=$(e,r.id);v&&(w=Boolean(O&&O.includes(t.id)),v=!w);const I=u||l||o||r.isCreator||Object(c.q)(r,"deleteMessages"),j=I&&!s&&(u&&!d||o&&(l||Object(c.q)(r,"deleteMessages"))),C=!h&&p&&(l||i&&(r.isCreator||Object(c.q)(r,"editMessages"))),E=!h&&!s,S=Boolean(t.content.sticker),M=S&&function(e,t){const{stickers:n}=e.stickers.favorite;return n&&n.some(({id:e})=>e===t.id)}(e,t.content.sticker),A=!h&&S&&!M,k=!h&&M,T=!h,N=!h&&(i||a),P=!h;return{noOptions:[g,C,v,w,I,j,E,A,k,T,N,P].every(e=>!e),canReply:g,canEdit:C,canPin:v,canUnpin:w,canDelete:I,canDeleteForAll:j,canForward:E,canFaveSticker:A,canUnfaveSticker:k,canCopy:T,canCopyLink:N,canSelect:P}}function be(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=D(e)||{},u=n&&L(e,n);if(!u||!t||!r)return{};const d=t.map(t=>u[t]&&le(e,u[t],r)).filter(Boolean);return{canDelete:d.every(e=>e.canDelete),canDeleteForAll:d.every(e=>e.canDeleteForAll)}}function he(e,t){const n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id];return n?n.progress:void 0}function me(e,t,n){if(n===d.MAIN_THREAD_ID){const n=f(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?Object(c.sb)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=Y(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function pe(e,t,n){const r=f(e,t);if(n===d.MAIN_THREAD_ID){if(!r)return}else{const r=Y(e,t,n);if(!r||r.lastMessageId===r.lastReadInboxMessageId)return}const u=U(e,t,n),o=R(e,t,n),c=L(e,t);if(!c||!u&&!o)return;const a=me(e,t,n);if(a||!r||!r.isNotJoined){if(u){const e=a?u.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):u[0];if(e)return e}if(o){const e=a?o.find(e=>e>a&&c[e]&&(!c[e].isOutgoing||c[e].isFromScheduled)):o[0];if(e)return e}}}function ge(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ye(e,t){const n=Object.values(e.chats.byId).find(e=>Object(c.ob)(e)&&e.lastMessage&&e.lastMessage.id===t);if(n)return n.id;const{byChatId:r}=e.messages;return Number(Object.keys(r).find(n=>{const u=f(e,Number(n));return u&&Object(c.ob)(u)&&r[u.id].byId[t]}))}function ve(e){const{selectedMessages:t}=e;return Boolean(t)}function we(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function Oe(e,t,n){const r=L(e,t);if(r)return Object.values(r).filter(e=>e.groupedId===n&&e.forwardInfo).map(({forwardInfo:e})=>e.fromMessageId)}function Ie(e,t,n){const r=L(e,t);if(r)return Object.keys(r).map(Number).filter(e=>r[e].groupedId===n)}function je(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const u=Ie(e,t,n);return u&&u.every(e=>r.includes(e))}function Ce(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Ee(e,t){const n=f(e,t);if(!n)return;if(!h(e,n))return;const r=L(e,t),u=G(e,t,d.MAIN_THREAD_ID);if(!r||!u)return;const o=Object(S.g)(u,e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons)),c=Object(S.g)(u,e=>Boolean(r[e].shouldHideKeyboardButtons));return o&&c&&c>o?void 0:o?r[o]:void 0}function Se(e,t,n,r){const{shouldAutoDownloadMediaFromContacts:u,shouldAutoDownloadMediaInPrivateChats:d,shouldAutoDownloadMediaInGroups:o,shouldAutoDownloadMediaInChannels:a}=e.settings.byKey;return Boolean(d&&Object(c.lb)(n.id)||o&&Object(c.kb)(n)||a&&Object(c.jb)(n)||u&&r&&(r.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,r)))}function Me(e,t){const n=Object(c.P)(t);if(!n)return;const{shouldAutoPlayVideos:r,shouldAutoPlayGifs:u}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||u&&d}function Ae(e){return e.settings.byKey.shouldLoopStickers}function ke(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=Object(c.a)(t,n),u=e.localTextSearch.byChatThreadKey[r];return u&&u.isActive?u:void 0}function Te(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=D(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ne(e){const t=Te(e);if(t)return e.localMediaSearch.byChatId[t]}function Pe(e,t){return e.management.byChatId[t]}function De(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;if(Object(c.lb)(t))return"user";const r=f(e,t);return r?Object(c.kb)(r)?"group":"channel":void 0}function Fe(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Le(e){const{users:t,isChatInfoShown:n}=e,d=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),o=Boolean(!u.g&&ke(e)),c=function(e){const{chatId:t,threadId:n}=D(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),a=void 0!==M(e).query,i=void 0!==A(e).query,{chatId:s}=D(e)||{},f=t.selectedId,l=v(e),b=Boolean(f&&l),h=Boolean(s&&l)&&n;return d?r.l.PollResults:o?r.l.Search:c?r.l.Management:a?r.l.StickerSearch:i?r.l.GifSearch:b?r.l.UserInfo:h?r.l.ChatInfo:void 0}function Be(e){return void 0!==Le(e)}function xe(e){return e.globalSearch.query}function Re(e){return e.payment.messageId}function Ue(e){return e.payment.formId}function _e(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function Ge(e){return e.payment.stripeCredentials}},function(e,t,n){"use strict";n.d(t,"o",(function(){return u})),n.d(t,"f",(function(){return d})),n.d(t,"e",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"j",(function(){return a})),n.d(t,"l",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"m",(function(){return f})),n.d(t,"d",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"h",(function(){return m})),n.d(t,"c",(function(){return p})),n.d(t,"a",(function(){return g})),n.d(t,"n",(function(){return y})),n.d(t,"p",(function(){return w}));var r=n(1);const u=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="Mac OS":-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}(),d="Mac OS"===u,o="iOS"===u,c="Android"===u,a=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=window.matchMedia("(pointer: coarse)").matches,s=window.innerWidth<=r.db||window.innerWidth<=r.cb&&window.innerHeight<=r.bb,f=navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext),l=(document.documentElement.style,u&&(d||o)),b="serviceWorker"in navigator,h=b,m=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),p=!r.E&&"filter"in(document.createElement("canvas").getContext("2d")||{}),g=window.devicePixelRatio||1,y=!0;let v;function w(){return Boolean(v)}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=>{v=e})},function(e,t,n){"use strict";t.a=(...e)=>e.filter(Boolean).join(" ")},function(e,t,n){"use strict";function r(e,t,n=!0,r=!0){let u;return(...d)=>{u?(clearTimeout(u),u=void 0):n&&e(...d),u=self.setTimeout(()=>{r&&e(...d),u=void 0},t)}}function u(e,t,n=!0){let r,u,d;return(...o)=>{u=!0,d=o,r||(n&&(u=!1,e(...d)),r=self.setInterval(()=>{if(!u)return self.clearInterval(r),void(r=void 0);u=!1,e(...d)},t))}}function d(e){return c(h,e)}function o(e){return c(m,e)}function c(e,t){let n,r=!1;return(...u)=>{n=u,r||(r=!0,e(()=>{r=!1,t(...n)}))}}function a(e){Promise.resolve().then(e)}function i(e){self.requestIdleCallback?self.requestIdleCallback(e):a(e)}n.d(t,"a",(function(){return r})),n.d(t,"g",(function(){return u})),n.d(t,"i",(function(){return d})),n.d(t,"h",(function(){return o})),n.d(t,"d",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"e",(function(){return s})),n.d(t,"f",(function(){return f})),n.d(t,"b",(function(){return h}));const s=e=>new Promise(t=>{setTimeout(()=>t(),e)});function f(){return new Promise(e=>{h(e)})}let l,b;function h(e,t=!1){l?t?b.push(e):l.push(e):(l=t?[]:[e],b=t?[e]:[],requestAnimationFrame(()=>{const e=l,t=b;l=void 0,b=void 0,t.forEach(e=>e()),e.forEach(e=>e())}))}function m(e){h(e,!0)}},function(e,t,n){"use strict";n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"b",(function(){return l}));var r=n(80),u=n.n(r),d=n(1),o=n(28);let c;const a=new Map,i=new Map;function s(e,t){return c||(d.p&&console.log(">>> START LOAD WORKER"),c=new u.a,function(e){c.addEventListener("message",({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){const e=a.get(t.messageId);e&&e.callback&&e.callback(...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error})}(e)),b({type:"initApi",args:[t]})}function f(e,...t){if(c)return b({type:"callMethod",name:e,args:t});d.p&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=i.get(e)||{};t&&c.postMessage({type:"cancelProgress",messageId:t})}function b(e){const t=Object(o.a)(a),n={messageId:t,...e},r={messageId:t},u=new Promise((e,t)=>{Object.assign(r,{resolve:e,reject:t})});if("function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,i.set(e,r)}return a.set(t,r),u.catch(()=>{}).finally(()=>{a.delete(t),r.callback&&i.delete(r.callback)}),c.postMessage(n),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"b",(function(){return s}));var r=n(1);let u;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(u||(u={}));const d={},o={};async function c(e,t){if(!d[e]){switch(e){case u.Auth:d[u.Auth]=n.e(5).then(n.bind(null,105));break;case u.Main:r.p&&console.log(">>> START LOAD MAIN BUNDLE"),d[u.Main]=Promise.all([n.e(0),n.e(4)]).then(n.bind(null,104));break;case u.Extra:d[u.Extra]=Promise.all([n.e(0),n.e(3)]).then(n.bind(null,103))}d[e].then(f)}const c=await d[e];return o[e]||(o[e]=c),a(e,t)}function a(e,t){const n=o[e];if(n)return n[t]}const i=[];function s(e){i.includes(e)||i.push(e)}function f(){i.forEach(e=>{e()})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"c",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"b",(function(){return c}));const r=self.caches;let u;async function d(e,t,n){if(r)try{const d=new Request(t),o=await r.open(e),c=await o.match(d);if(!c)return;switch(n){case u.Text:return await c.text();case u.Blob:{const e=await c.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=c.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case u.Json:return await c.json();default:return}}catch(e){return void console.warn(e)}}async function o(e,t,n){if(r)try{const u="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t),o=new Response(u),c=await r.open(e);return await c.put(d,o)}catch(e){return void console.warn(e)}}async function c(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"}(u||(u={}))},function(e,t,n){"use strict";n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return c})),n.d(t,"g",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l}));var r=n(9);function u(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,...r}=n;super(e,{type:t}),u(this,"name",void 0),Object.assign(this,r)}else super(e),u(this,"name",void 0);this.name=t}});function d(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let u=r.length;const d=new Uint8Array(u);for(;u--;)d[u]=r.charCodeAt(u);return new Blob([d],{type:n})}function o(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 c(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function a(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e})}function i(e){return new Promise((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e})}async function s(e){const t=await i(e);return Promise.race([Object(r.e)(2e3),new Promise((e,n)=>{t.onseeked=()=>{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 f(e){return(await fetch(e)).blob()}function l(e){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;return t.getContext("2d").drawImage(e,0,0),t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return v})),n.d(t,"b",(function(){return j})),n.d(t,"c",(function(){return C}));var r=n(1),u=n(12),d=n(10);var o=n(3),c=n.p+"en-extra.e73049da90714ecdae3233e8ffa74d39.json",a=n.p+"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json",i=n.p+"it-extra.78e5568451a888818c7e2209e05a9602.json",s=n.p+"pl-extra.38fd67a6c26e58f5c912568332c7c074.json",f=n.p+"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json",l=n(49),b=n(2);const h={en:c,es:a,it:i,pl:s,ru:f},m=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],p={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},g=new Map;let y;const{addCallback:v,removeCallback:w,runCallbacks:O}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach(e=>{e(...t)})},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let I;const j=(e,t,n)=>{if(void 0!==t){const r=g.get(`${e}_${t}_${n}`);if(r)return r}if(!y)return e;const r=y[e];if(!r)return e;const u=r["number"==typeof t?function(e){const t=I&&p[I]?p[I](e):0;return m[t]}(t):"value"];if(!u||!u.trim()){const t=e.split(".");return t[t.length-1]}if(void 0!==t){const r=function(e,t){return e.replace(/%\d?\$?[sdf@]/,String(t))}(u,"i"===n?Object(l.a)(t):t);return g.set(`${e}_${t}_${n}`,r),r}return u};async function C(e,t){if(y&&e===I)return void(t&&t());const n=await async function(e){const t=await u.c(r.F,e,u.a.Json);if(t)return t;const n=await Object(d.a)("fetchLangPack",{sourceLangPacks:r.G,langCode:e});if(n)return await u.d(r.F,e,n.langPack),n.langPack;return}(e);if(!n)return;if(h[e])try{const t=await fetch(h[e]),r=await t.json(),u=Object(o.i)(r,(e,t)=>({key:t,value:e}));Object.assign(n,u)}catch(e){r.p&&console.error(e)}g.clear(),I=e,y=n,document.documentElement.lang=e;const{languages:c}=Object(b.e)().settings.byKey,a=c?c.find(t=>t.langCode===e):void 0;j.isRtl=Boolean(a&&a.rtl),t&&t(),O(y)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d}));const r=/\uFE0F/g,u=String.fromCharCode(8205);function d(e){return e.indexOf(u)<0?e.replace(r,""):e}t.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},function(e,t,n){"use strict";var r=n(0),u=n(21);n(94);t.a=Object(r.h)(({color:e="blue"})=>r.a.createElement("div",{className:"Loading"},r.a.createElement(u.a,{color:e,withBackground:"white"===e})))},function(e,t,n){"use strict";var r=n(0),u=n(11),d=n(26);t.a=(e,t,n=!1,o=!1)=>{const c=Object(u.c)(e,t),a=Object(d.a)();return o&&Object(u.b)(a),Object(r.n)(()=>{n||c||Object(u.d)(e,t).then(a)},[e,a,c,t,n]),c}},function(e,t,n){"use strict";n.d(t,"d",(function(){return o})),n.d(t,"e",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"a",(function(){return d}));const r={},u=/(\d{1,3})(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,3})?/;var d="AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234".split("\n").map(e=>({id:e.substr(0,2),flag:e.substr(2,4),code:"+"+e.match(/\d+/)[0],name:e.split(/\d+/)[1],phoneFormat:function(e){if(!e)return u;const t=e[0];let n;if(!r[t]){const e=t.split("").map(Number);n=e.reduce((e,t,n)=>`${e}(\\d{1,${t}})${n>0?"?":""}`,""),r[t]=new RegExp(`${n}${"()?".repeat(5-e.length)}`)}return r[t]}(e.match(/\d+$/))}));function o(e){return d.find(t=>t.id===e)}function c(e){let t=e.replace(/[^\d+]+/g,"");t.startsWith("+")||(t="+"+t);const n=d.filter(e=>t.startsWith(e.code)).sort((e,t)=>e.code.length-t.code.length);return n[n.length-1]}function a(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.code.length-1);else if(e.startsWith("+"))return e;return n=n.replace(function(e){return e?e.phoneFormat:u}(t),(e,n,r,u,d,o)=>{const c=t&&"GB"===t.id?" ":"-";let a="";return n&&(a=""+n),r&&(a+=" "+r),u&&(a+=`${c}${u}`),d&&(a+=`${c}${d}`),o&&(a+=`${c}${o}`),a}),n}function i(e){const t=e.startsWith("+")?e:"+"+e,n=c(t);return n?`${n.code} ${a(t,n)}`:t}},function(e,t,n){"use strict";(function(e){n.d(t,"f",(function(){return c})),n.d(t,"b",(function(){return a})),n.d(t,"e",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"a",(function(){return f})),n.d(t,"d",(function(){return l}));var r=n(41),u=n(1),d=n(12);const o=[1,2,3,4,5];function c(e,t){const{mainDcId:n,keys:r,hashes:d}=e;localStorage.setItem(u.nb,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]))}),Object.keys(d).map(Number).forEach(e=>{localStorage.setItem(`dc${e}_hash`,JSON.stringify(d[e]))})}function a(){[u.nb,"dc",...o.map(e=>`dc${e}_auth_key`),...o.map(e=>`dc${e}_hash`)].forEach(e=>{localStorage.removeItem(e)})}function i(){const e=localStorage.getItem(u.nb);if(!e)return;let t;const n={},r={};try{const n=JSON.parse(e);t=Number(n.dcID)}catch(e){}return t&&(o.forEach(e=>{try{const t=localStorage.getItem(`dc${e}_auth_key`);t&&(n[e]=JSON.parse(t));const u=localStorage.getItem(`dc${e}_hash`);u&&(r[e]=JSON.parse(u))}catch(e){u.p&&console.warn("Failed to load stored session",e)}}),Object.keys(n).length)?{mainDcId:t,keys:n,hashes:r}:void 0}async function s(){const e=localStorage.getItem(u.H);if(!e)return;const t=await r.b("GramJs:"+e);try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load legacy session",e)}}async function f(){localStorage.removeItem(u.H);const e=await r.c();await Promise.all([d.b("GramJs"),...e.filter(e=>"string"==typeof e&&e.startsWith("GramJs:GramJs-session-")).map(e=>r.a(e))])}function l(){const t=e.env.TEST_SESSION;try{c(JSON.parse(t))}catch(e){u.p&&console.warn("Failed to load test session",e)}}}).call(this,n(86))},function(e,t,n){"use strict";let r,u,d,o,c,a,i,s,f,l,b,h;n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"m",(function(){return d})),n.d(t,"d",(function(){return o})),n.d(t,"c",(function(){return c})),n.d(t,"l",(function(){return a})),n.d(t,"h",(function(){return i})),n.d(t,"a",(function(){return s})),n.d(t,"j",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"k",(function(){return b})),n.d(t,"i",(function(){return h})),n.d(t,"n",(function(){return m})),n.d(t,"g",(function(){return p})),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"}(u||(u={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.Language=3]="Language",e[e.General=4]="General",e[e.GeneralChatBackground=5]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=6]="GeneralChatBackgroundColor",e[e.Privacy=7]="Privacy",e[e.PrivacyPhoneNumber=8]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=9]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=10]="PrivacyProfilePhoto",e[e.PrivacyForwarding=11]="PrivacyForwarding",e[e.PrivacyGroupChats=12]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=13]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=14]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=15]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=16]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=17]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=18]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=19]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=20]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=21]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=22]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=23]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=24]="PrivacyBlockedUsers",e[e.Folders=25]="Folders",e[e.FoldersCreateFolder=26]="FoldersCreateFolder",e[e.FoldersEditFolder=27]="FoldersEditFolder",e[e.FoldersIncludedChats=28]="FoldersIncludedChats",e[e.FoldersExcludedChats=29]="FoldersExcludedChats",e[e.TwoFaDisabled=30]="TwoFaDisabled",e[e.TwoFaNewPassword=31]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=32]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=33]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=34]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=35]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=36]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=37]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=38]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=39]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=40]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=41]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=42]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=43]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=44]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=45]="TwoFaCongratulations"}(d||(d={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(o||(o={})),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"}(c||(c={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults"}(a||(a={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.MiddleHeaderAvatar=4]="MiddleHeaderAvatar",e[e.Album=5]="Album",e[e.ScheduledAlbum=6]="ScheduledAlbum",e[e.SearchResult=7]="SearchResult"}(i||(i={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(s||(s={})),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"}(l||(l={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(b||(b={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(h||(h={}));const m="UPLOADING_WALLPAPER_SLUG";let p;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(p||(p={}))},function(e,t,n){"use strict";var r=n(0),u=n(8);n(90);t.a=({color:e="blue",withBackground:t})=>r.a.createElement("div",{className:Object(u.a)("Spinner",e,t&&"with-background")},r.a.createElement("div",null))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(1),u=n(9);window.addEventListener("error",c),window.addEventListener("unhandledrejection",c);const d=Date.now();let o=!1;function c(e){e.preventDefault(),a(e instanceof ErrorEvent?e.error:e.reason)}Object(u.g)(window.alert,1e3);function a(e){if(console.error(e),!o)return Date.now()-d<=5e3&&localStorage.getItem(r.B)?(localStorage.removeItem(r.B),o=!0,void window.location.reload()):void 0}},function(e,t,n){"use strict";n.d(t,"a",(function(){return b}));var r=n(0),u=n(15),d=n(1),o=n(7),c=n(65),a=n(8),i=n(76),s=n(57);const f=/^[\d\wа-яё]$/i,l=/(\*\*|__).+?\1/g;function b(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML]),[])}(e);case"hq_emoji":return u.a.lastIndex=0,h(e,"big","jsx");case"emoji":return u.a.lastIndex=0,h(e,"small","jsx");case"emoji_html":return u.a.lastIndex=0,h(e,"small","html");case"br":return m(e,"jsx");case"br_html":return m(e,"html");case"highlight":return d=e,o=n.highlight,d.reduce((e,t)=>{if("string"!=typeof t||!o)return[...e,t];const n=t.toLowerCase(),u=n.indexOf(o.toLowerCase()),d=n[u+o.length];if(u<0||d&&d.match(f))return[...e,t];const c=[];return c.push(t.substring(0,u)),c.push(r.a.createElement("span",{className:"matching-text-highlight"},t.substring(u,u+o.length))),c.push(t.substring(u+o.length)),[...e,...c]},[]);case"links":return function(e){return e.reduce((e,t)=>{if("string"!=typeof t)return[...e,t];const n=[...t.match(p)||[],...t.match(g)||[]];if(!n.length)return[...e,t];const u=[];let d=n.shift(),o=0;for(;d;){const e=t.indexOf(d,o);u.push(t.substring(o,e)),d.startsWith("@")?u.push(r.a.createElement(i.a,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),u.push(r.a.createElement(s.a,{text:d,url:d}))),o=e+d.length,d=n.shift()}return u.push(t.substring(o)),[...e,...u]},[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var d,o;return e},[e])}function h(e,t,n){return e.reduce((e,d)=>{if("string"!=typeof d)return[...e,d];const i=d.split(u.a),s=d.match(u.a)||[];return e.push(i[0]),s.reduce((e,d,s)=>{const f=Object(c.a)(Object(u.b)(d)),l=Object(a.a)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(o.d?r.a.createElement("span",{className:"font-emoji"},d):r.a.createElement("img",{className:l,src:`./img-apple-${"big"===t?"160":"64"}/${f}.png`,alt:d})),"html"===n&&e.push(o.d?d:`${d}`);const b=2*s+2;return i[b]&&e.push(i[b]),e},e)},[])}function m(e,t){return e.reduce((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce((e,n,u,d)=>{const o=n.trimLeft(),c=n.length-o.length;return e.push(String.fromCharCode(160).repeat(c)+o),u!==d.length-1&&e.push("jsx"===t?r.a.createElement("br",null):"
"),e},[])],[])}const p=new RegExp(d.gb,"ig"),g=/@[\w\d_-]+/gi;function y(e,t){return e.reduce((e,n)=>{if("string"!=typeof n)return[...e,n];const u=n.split(l),d=n.match(l)||[];return e.push(u[0]),d.reduce((e,n,d)=>{"jsx"===t?e.push(n.startsWith("**")?r.a.createElement("b",null,n.replace(/\*\*/g,"")):r.a.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const o=2*d+2;return u[o]&&e.push(u[o]),e},e)},[])}},function(e,t,n){"use strict";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 u=0;ue[n]!==t[n])}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u}))},function(e,t,n){"use strict";var r=n(14),u=n(26),d=n(51);t.a=()=>{const e=Object(u.a)();return Object(d.a)(()=>r.a(e),[e]),r.b}},function(e,t,n){"use strict";var r=n(0);t.a=()=>{const[,e]=Object(r.r)(!1);return Object(r.m)(()=>{e(e=>!e)},[])}},function(e,t,n){"use strict";var r=n(0),u=n(8);n(88);t.a=({children:e,className:t,isRtl:n,onClick:d})=>{const o=Object(r.m)(e=>{e.preventDefault(),d(e)},[d]);return r.a.createElement("a",{href:"#",className:Object(u.a)("Link",t),dir:n?"rtl":"auto",onClick:d?o:void 0},e)}},function(e,t,n){"use strict";t.a=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},function(e,t,n){"use strict";n.d(t,"d",(function(){return p})),n.d(t,"c",(function(){return g})),n.d(t,"b",(function(){return y})),n.d(t,"a",(function(){return v}));var r=n(10),u=n(67),d=n(1),o=n(2),c=n(4),a=n(14),i=n(37),s=n(6),f=n(7);function l(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function b(){return!!f.k&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(d.p&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(d.p&&console.warn("[PUSH] Push messaging isn't supported."),!1):(d.p&&console.warn("[PUSH] Push notifications aren't supported."),!1))}async function h(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function m(e){const t=Object(o.e)(),n=Object(o.d)();if(e)try{const t=l(e);return await Object(r.a)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){d.p&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await Object(r.a)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function p(){if(!b())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await m(t)}async function g(){if(async function(){const[e]=await Promise.all([Object(r.a)("fetchNotificationSettings"),Object(r.a)("fetchNotificationExceptions")]);e&&Object(o.g)(Object(i.v)(Object(o.e)(),e))}(),!b())return void await h();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=Object(o.e)();return!t.push||!e||(l(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5)}(t)){await m(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=l(t);d.p&&console.log("[PUSH] Received push subscription: ",n),await Object(r.a)("registerDevice",n),Object(o.d)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?d.p&&console.warn("[PUSH] The user has blocked push notifications."):d.p&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await h())}}}function y({chat:e,message:t,isActiveChat:n}){if(!("Notification"in window?"denied"!==Notification.permission||(d.p&&console.warn("[PUSH] The user has blocked push notifications."),0):(d.p&&console.warn("[PUSH] This browser does not support desktop notification"),0)))return;if(!t.id)return;if(!function(e,t){const n=Object(o.e)();if(Object(c.Cb)(e,Object(s.eb)(n),Object(s.db)(n))||e.isNotJoined)return!1;if(t&&document.hasFocus())return!1;switch(e.type){case"chatTypePrivate":case"chatTypeSecret":return Boolean(n.settings.byKey.hasPrivateChatsNotifications);case"chatTypeBasicGroup":case"chatTypeSuperGroup":return Boolean(n.settings.byKey.hasGroupNotifications);case"chatTypeChannel":return Boolean(n.settings.byKey.hasBroadcastNotifications)}return!1}(e,n))return;const{title:r,body:i}=function(e,t){const n=Object(o.e)(),{senderId:r,replyToMessageId:d}=t,i=r?Object(s.Gb)(n,r):void 0,f=Object(c.t)(t),l=f&&d?Object(s.k)(n,e.id,d):void 0,{targetUserId:b,targetChatId:h}=f||{},m=b?Object(s.Gb)(n,b):void 0,p=Object(c.U)(e),g=p?Object(s.Gb)(n,p):void 0;let y;if(Object(c.db)(t)){const n=e&&(Object(c.jb)(e)||t.senderId===t.chatId)?e:i;y=Object(u.a)(a.b,t,n,m,l,h,{asPlain:!0})}else{const n=Object(c.J)(a.b,e.id,i),r=Object(c.N)(a.b,t);y=n?`${n}: ${r}`:r}return{title:Object(c.l)(a.b,e,g),body:y}}(e,t);if(b())navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"newMessageNotification",payload:{title:r,body:i,chatId:e.id,messageId:t.id}});else{const n=Object(o.d)(),u={body:i,icon:"icon-192x192.png",badge:"icon-192x192.png",tag:t.id.toString()};"vibrate"in navigator&&(u.vibrate=[200,100,200]);const d=new Notification(r,u);d.onclick=()=>{d.close(),n.focusMessage({chatId:e.id,messageId:t.id}),window.focus&&window.focus()}}}function v(){navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return c})),n.d(t,"c",(function(){return a})),n.d(t,"d",(function(){return i})),n.d(t,"g",(function(){return s})),n.d(t,"e",(function(){return f})),n.d(t,"f",(function(){return l})),n.d(t,"h",(function(){return b})),n.d(t,"a",(function(){return h}));var r=n(1),u=n(36),d=n(3);const o=[1,8,5,2,7,4,6];function c(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function a(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function i(e,t){if(t.id===r.mb)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!t.status)return"";switch(t.status.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:n}=t.status;if(!n)return e("LastSeen.Offline");const r=new Date,d=new Date(1e3*n);if(d>=r)return e("LastSeen.JustNow");const o=new Date(r.getTime()-d.getTime());if(o.getTime()/1e3<60)return e("LastSeen.JustNow");if(o.getTime()/1e3<3600){return e("LastSeen.MinutesAgo",Math.floor(o.getTime()/1e3/60))}const c=new Date;if(c.setHours(0,0,0,0),d>c){if(o.getTime()/1e3<21600){return e("LastSeen.HoursAgo",Math.floor(o.getTime()/1e3/60/60))}return e("LastSeen.TodayAt",Object(u.h)(d))}const a=new Date;return a.setDate(r.getDate()-1),c.setHours(0,0,0,0),d>a?e("LastSeen.YesterdayAt",Object(u.h)(d)):e("LastSeen.AtDate",Object(u.b)(e,d))}case"userStatusOnline":return e("Online");case"userStatusRecently":return e("Lately");default:return}}function s(e){const{id:t,status:n,type:u}=e;return!!n&&(t!==r.mb&&("userStatusOnline"===n.type&&"userTypeBot"!==u))}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.mb)&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function l(e){return"userTypeBot"===e.type}function b(e,t,n){return Object(d.k)(e,e=>{const r=Date.now()/1e3;if(n&&n.includes(e))return r+172800-(n.length-n.indexOf(e));const u=t[e];if(!u||!u.status)return 0;if("userStatusOnline"===u.status.type)return u.status.expires;if("userStatusOffline"===u.status.type&&u.status.wasOnline)return u.status.wasOnline;switch(u.status.type){case"userStatusRecently":return r-86400;case"userStatusLastWeek":return r-604800;case"userStatusLastMonth":return r-18144e3;default:return 0}},"desc")}function h(e){const t=e?Math.abs(e.id)%7:0;return o[t]}},function(e,t,n){"use strict";n.d(t,"w",(function(){return c})),n.d(t,"v",(function(){return a})),n.d(t,"t",(function(){return i})),n.d(t,"y",(function(){return s})),n.d(t,"u",(function(){return f})),n.d(t,"z",(function(){return l})),n.d(t,"j",(function(){return b})),n.d(t,"p",(function(){return h})),n.d(t,"i",(function(){return m})),n.d(t,"e",(function(){return p})),n.d(t,"f",(function(){return g})),n.d(t,"d",(function(){return y})),n.d(t,"x",(function(){return v})),n.d(t,"r",(function(){return w})),n.d(t,"m",(function(){return O})),n.d(t,"A",(function(){return I})),n.d(t,"c",(function(){return j})),n.d(t,"a",(function(){return C})),n.d(t,"o",(function(){return E})),n.d(t,"h",(function(){return S})),n.d(t,"g",(function(){return M})),n.d(t,"s",(function(){return A})),n.d(t,"D",(function(){return k})),n.d(t,"b",(function(){return T})),n.d(t,"C",(function(){return N})),n.d(t,"B",(function(){return P})),n.d(t,"l",(function(){return D})),n.d(t,"k",(function(){return F})),n.d(t,"q",(function(){return L})),n.d(t,"n",(function(){return B})),n.d(t,"E",(function(){return x}));var r=n(5),u=n(1),d=n(3),o=n(30);function c(e){return e>0}function a(e){return i(e)||s(e)}function i(e){return"chatTypeBasicGroup"===e.type}function s(e){return"chatTypeSuperGroup"===e.type}function f(e){return"chatTypeChannel"===e.type}function l(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function b(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function h(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function m(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function p(e){if(e.fullInfo)return e.fullInfo.about}function g(e){const{username:t}=e,{inviteLink:n}=e.fullInfo||{};return n&&n.length?n:t?"t.me/"+t:""}function y(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function v(e){return!e.lastMessage}function w(e){return Boolean(e.adminRights)}function O(e,t){return!!e.adminRights&&e.adminRights[t]}function I(e,t){return Boolean(e.currentUserBannedRights&&e.currentUserBannedRights[t]||e.defaultBannedRights&&e.defaultBannedRights[t])}function j(e,t){return t!==r.MAIN_THREAD_ID||!(e.isRestricted||e.migratedTo||e.isNotJoined)&&(!!e.isCreator||(!!c(e.id)||(f(e)?O(e,"postMessages"):w(e)||!I(e,"sendMessages"))))}function C(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=w(e);return{canAttachMedia:n||!I(e,"sendMedia"),canAttachPolls:(n||!I(e,"sendPolls"))&&(!c(e.id)||t),canSendStickers:n||!I(e,"sendStickers"),canSendGifs:n||!I(e,"sendGifs"),canAttachEmbedLinks:n||!I(e,"embedLinks")}}function E(e){return e.currentUserBannedRights&&e.currentUserBannedRights.sendMessages?"You are not allowed to send messages in this chat.":e.defaultBannedRights&&e.defaultBannedRights.sendMessages?"Sending messages is not allowed in this chat.":void 0}function S(e){if(e&&e.fullInfo)return e.fullInfo.slowMode}function M(e){return Math.max(e.joinDate||0,e.lastMessage?e.lastMessage.date:0)}function A(e){return e.folderId===u.h}function k(e,t,n){return!(n&&n[e.id]&&!n[e.id].isMuted)&&(e.isMuted||c(e.id)&&!t.hasPrivateChatsNotifications||f(e)&&!t.hasBroadcastNotifications||a(e)&&!t.hasGroupNotifications)}function T(e){return i(e)||(s(e)||f(e))&&e.isCreator}function N(e,t,n,r,u,d){const o=n.excludedChatIds?new Set(n.excludedChatIds):void 0,i=n.excludedChatIds?new Set(n.includedChatIds):void 0,s=n.excludedChatIds?new Set(n.pinnedChatIds):void 0;return[(d||Object.keys(e).map(Number)).filter(d=>function(e,t,n,r,u,d,o,i){if(d&&d.has(e.id))return!1;if(o&&o.has(e.id))return!0;if(i&&i.has(e.id))return!0;if(A(e)&&t.excludeArchived)return!1;if(t.excludeMuted&&!e.unreadMentionsCount&&k(e,r,u))return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(c(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(a(e))return!!t.groups;if(f(e))return!!t.channels}return!1}(e[d],n,t,r,u,o,i,s)),n.pinnedChatIds]}function P(e,t,n,r="all"){function u(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(A(e))return!1;break;case"archived":if(!A(e))return!1}return!e.isRestricted&&!e.isNotJoined}const o=t.map(t=>e[t]).filter(u),c=new Set(t);return{pinnedChats:n?n.map(t=>e[t]).filter(u).filter(e=>c.has(e.id)):[],otherChats:Object(d.k)(n?o.filter(e=>!n.includes(e.id)):o,M,"desc")}}function D(e,t,n,r,u,d){const[o]=N(e,t,n,u,d,r),c=o.map(t=>e[t]).filter(e=>e&&e.lastMessage&&!e.isRestricted&&!e.isNotJoined);return{unreadDialogsCount:c.reduce((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e,0),hasActiveDialogs:c.some(e=>e.unreadMentionsCount||!k(e,u,d)&&(e.unreadCount||e.hasUnreadMark))}}function F(e,t,n,r,u,d,o){const{id:c,title:a,emoticon:i,description:s,pinnedChatIds:f,excludedChatIds:l,includedChatIds:b,excludeArchived:h,excludeMuted:m,excludeRead:p,...g}=r;if(Object.values(g).filter(Boolean).length>1||l&&l.length||b&&b.length){return e("Chats",function(e,t,n,r,u,d){const[o,c]=N(e,t,n,u,d,r),{pinnedChats:a,otherChats:i}=P(e,o,c,"folder");return a.length+i.length}(t,n,r,u,d,o))}return g.bots?e("FilterBots"):g.groups?e("FilterGroups"):g.channels?e("FilterChannels"):g.contacts?e("FilterContacts"):g.nonContacts?e("FilterNonContacts"):void 0}function L(e){return!!e&&e.id<0}function B(e,t,n){if(n&&!c(t))return n.isSelf?e("FromYou"):Object(o.b)(n)}function x(e,t,n=!1,r){return Object(d.k)(e,e=>{const u=t[e];if(!u)return 0;let d=0;return u.lastMessage&&(d+=u.lastMessage.date),n&&u.isVerified&&(d+=3e9),r&&r.includes(e)&&(d+=Date.now()+(r.length-r.indexOf(e))),d},"desc")}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(21),o=n(43);n(92);t.a=({ref:e,type:t="button",onClick:n,onContextMenu:c,onMouseDown:a,onMouseEnter:i,onMouseLeave:s,onFocus:f,children:l,size:b="default",color:h="primary",className:m,round:p,pill:g,fluid:y,isText:v,isLoading:w,ariaLabel:O,href:I,download:j,disabled:C,ripple:E,faded:S,tabIndex:M,isRtl:A})=>{let k=Object(r.q)(null);e&&(k=e);const[T,N]=Object(r.r)(!1),P=Object(u.a)("Button",m,b,h,p&&"round",g&&"pill",y&&"fluid",C&&"disabled",v&&"text",w&&"loading",E&&"has-ripple",S&&"faded",T&&"clicked"),D=Object(r.m)(e=>{!C&&n&&n(e),N(!0),setTimeout(()=>{N(!1)},400)},[C,n]),F=Object(r.m)(e=>{e.preventDefault(),!C&&a&&a(e)},[a,C]);return I?r.a.createElement("a",{ref:k,className:P,href:I,title:O,download:j,tabIndex:M,dir:A?"rtl":void 0},l,!C&&E&&r.a.createElement(o.a,null)):r.a.createElement("button",{ref:k,type:t,className:P,onClick:D,onContextMenu:c,onMouseDown:F,onMouseEnter:i&&!C?i:void 0,onMouseLeave:s&&!C?s:void 0,onFocus:f&&!C?f:void 0,"aria-label":O,title:O,tabIndex:M,dir:A?"rtl":void 0},w?r.a.createElement("div",null,r.a.createElement("span",{dir:A?"auto":void 0},"Please wait.."),r.a.createElement(d.a,{color:v?"blue":"white"})):l,!C&&E&&r.a.createElement(o.a,null))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"c",(function(){return i})),n.d(t,"b",(function(){return b}));var r=n(1);const u=new Set(["scroll","mouseenter","mouseleave"]),d={},o=new Map,c={};function a(e,t,n){const r=s(t,e);f(r,e)?function(e,t,n){c[e]||(c[e]=0,document.addEventListener(e,h));(function(e){d[e]||(d[e]=new Map);return d[e]})(e).set(t,n),function(e){const t=o.get(e);if(t)return t;const n=new Set;return o.set(e,n),n}(t).add(e),c[e]++}(r,e,n):e.addEventListener(r,n)}function i(e,t,n){const r=s(t,e);f(r,e)?l(r,e):e.removeEventListener(r,n)}function s(e,t){const n=e.replace(/^on/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function f(e,t){return!u.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function l(e,t){c[e]--,c[e]||document.removeEventListener(e,h),d[e].delete(t),o.get(t).delete(e)}function b(e){const t=o.get(e);t&&(t.forEach(t=>l(t,e)),o.delete(e))}function h(e){const t=d[e.type];if(t){let n=!1,r=e.target;const u=()=>{n=!0},d=()=>{e.preventDefault()},o=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?u:"preventDefault"===t?d:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(o),n))return;r=r.parentNode}}}r.p&&document.addEventListener("dblclick",()=>{console.log("DELEGATED EVENTS",{delegationRegistry:d,delegatedEventsByElement:o,documentEventCounters:c})})},function(e,t,n){"use strict";var r=n(0);t.a=(e=!1)=>{const[t,n]=Object(r.r)(e);return[t,Object(r.m)(()=>{n(!0)},[]),Object(r.m)(()=>{n(!1)},[])]}},function(e,t,n){"use strict";var r=n(0),u=n(8);t.a=(e=!1,t,n=!1,d="fast",o=!1)=>{const[c,a]=Object(r.r)(!e),i=Object(r.q)(),[s,f]=Object(r.r)(e&&n);e?(a(!1),f(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(f(!1),c||i.current||(i.current=window.setTimeout(()=>{a(!0),t&&t(),i.current=void 0},o?0:350)));const l=Boolean(i.current),b=e||l;return{shouldRender:b,transitionClassNames:Object(u.a)(d&&"opacity-transition",d,s&&"open",b&&"shown",l&&"closing")}}},function(e,t,n){"use strict";n.d(t,"j",(function(){return o})),n.d(t,"k",(function(){return c})),n.d(t,"n",(function(){return a})),n.d(t,"h",(function(){return s})),n.d(t,"g",(function(){return f})),n.d(t,"b",(function(){return l})),n.d(t,"f",(function(){return b})),n.d(t,"c",(function(){return h})),n.d(t,"d",(function(){return p})),n.d(t,"e",(function(){return g})),n.d(t,"i",(function(){return y})),n.d(t,"a",(function(){return v})),n.d(t,"l",(function(){return O})),n.d(t,"m",(function(){return I}));const r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],u=["January","February","March","April","May","June","July","August","September","October","November","December"],d=u.map(e=>e.toLowerCase());function o(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function c(e){return o(e).getTime()}function a(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function i(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function s(e){const t="number"==typeof e?new Date(e):e;return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function f(e,t){const n="number"==typeof t?new Date(t):t,u=o(new Date);if(n>=u)return s(n);const d=new Date(u);if(d.setDate(u.getDate()-7),n>=d)return e("Weekday.Short"+r[n.getDay()]);const c=n.getFullYear()!==u.getFullYear(),a=e(c?"formatDateScheduleYear":"formatDateSchedule")||(c?"d MMM yyyy":"d MMM");return m(e,n,a)}function l(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return m(e,n,r)}function b(e,t,n=!1){const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return m(e,t,r)}function h(e,t,n=!1,u=!1){const d="number"==typeof t?new Date(t):t,c=o(new Date);if(!u){if(i(d)===i(c))return(n?j:C)(e("Weekday.Today"));const t=new Date(c);if(t.setDate(c.getDate()-1),i(d)===i(t))return(n?j:C)(e("Weekday.Yesterday"));const u=new Date(c),o=new Date(c);if(u.setDate(c.getDate()-7),o.setDate(c.getDate()+7),d>=u&&d<=o){const t=r[d.getDay()];return n?j(e("Weekday.Short"+t)):C(e("Weekday."+t))}}const a=d.getFullYear()!==c.getFullYear(),s=e(n?a?"formatDateScheduleYear":"formatDateSchedule":a?"chatFullDate":"chatDate")||"d MMMM yyyy";return(n?j:C)(m(e,d,s))}function m(e,t,n){const r=t.getDate(),d=t.getMonth();return n.replace("LLLL",e(u[d])).replace("MMMM",e("Month.Gen"+u[d])).replace("MMM",e("Month.Short"+u[d])).replace("MM",String(d+1).padStart(2,"0")).replace("dd",String(r).padStart(2,"0")).replace("d",String(r)).replace("yyyy",String(t.getFullYear()))}function p(e,t){const n="number"==typeof t?new Date(t):t;return`${h(e,n,!0)}, ${s(n)}`}function g(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%3600%60);let u="";return t>0?(u+=String(t).padStart(2,"0")+":",u+=String(n).padStart(2,"0")+":"):u+=String(n)+":",u+=String(r).padStart(2,"0"),u}function y(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 u=(e=Math.floor(e/60))%60;e-=u;const d=(e=Math.floor(e/60))%60;return d>0&&t.push(String(d).padStart(2,"0")),t.push(String(u).padStart(d>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function v(e){return e.toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function O(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?r+"-":""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const u=e.split(" "),o=t?u[0]:u[1],c=(t?u[1]:u[0]).toLowerCase(),a=d.findIndex(e=>e.startsWith(c));return-1!==a&&w(Number(o),a)?`${String(a+1).padStart(2,"0")}-${String(o).padStart(2,"0")}`:void 0}function I(e){return e+86400}function j(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function C(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},function(e,t,n){"use strict";n.d(t,"r",(function(){return d})),n.d(t,"I",(function(){return o})),n.d(t,"s",(function(){return c})),n.d(t,"H",(function(){return a})),n.d(t,"M",(function(){return i})),n.d(t,"c",(function(){return s})),n.d(t,"K",(function(){return f})),n.d(t,"J",(function(){return l})),n.d(t,"N",(function(){return m})),n.d(t,"x",(function(){return y})),n.d(t,"d",(function(){return v})),n.d(t,"b",(function(){return w})),n.d(t,"L",(function(){return O})),n.d(t,"eb",(function(){return I})),n.d(t,"j",(function(){return j})),n.d(t,"k",(function(){return C})),n.d(t,"V",(function(){return E})),n.d(t,"db",(function(){return S})),n.d(t,"g",(function(){return A})),n.d(t,"z",(function(){return k})),n.d(t,"kb",(function(){return T})),n.d(t,"lb",(function(){return N})),n.d(t,"u",(function(){return P})),n.d(t,"P",(function(){return D})),n.d(t,"O",(function(){return F})),n.d(t,"m",(function(){return L})),n.d(t,"G",(function(){return B})),n.d(t,"n",(function(){return x})),n.d(t,"ib",(function(){return R})),n.d(t,"hb",(function(){return U})),n.d(t,"Q",(function(){return _})),n.d(t,"q",(function(){return G})),n.d(t,"jb",(function(){return $})),n.d(t,"o",(function(){return W})),n.d(t,"y",(function(){return K})),n.d(t,"nb",(function(){return z})),n.d(t,"ob",(function(){return V})),n.d(t,"f",(function(){return q})),n.d(t,"fb",(function(){return J})),n.d(t,"l",(function(){return Y})),n.d(t,"R",(function(){return Z})),n.d(t,"S",(function(){return X})),n.d(t,"U",(function(){return ee})),n.d(t,"T",(function(){return te})),n.d(t,"Y",(function(){return ue})),n.d(t,"t",(function(){return de})),n.d(t,"Z",(function(){return oe})),n.d(t,"X",(function(){return ae})),n.d(t,"W",(function(){return ie})),n.d(t,"bb",(function(){return fe})),n.d(t,"ab",(function(){return le})),n.d(t,"v",(function(){return be})),n.d(t,"w",(function(){return he})),n.d(t,"e",(function(){return me})),n.d(t,"cb",(function(){return pe})),n.d(t,"a",(function(){return ge})),n.d(t,"p",(function(){return ye})),n.d(t,"mb",(function(){return ve})),n.d(t,"gb",(function(){return we})),n.d(t,"E",(function(){return Oe})),n.d(t,"C",(function(){return Ie})),n.d(t,"A",(function(){return je})),n.d(t,"F",(function(){return Ce})),n.d(t,"B",(function(){return Ee})),n.d(t,"D",(function(){return Se})),n.d(t,"h",(function(){return Me})),n.d(t,"i",(function(){return Ae}));var r=n(1),u=n(3);function d(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function o(e,t,n){const{[t]:r}=e.chats.listIds,u=r&&r.length?n.filter(e=>!r.includes(e)):n;return r&&!u.length?e:d(e,t,[...r||[],...u])}function c(e,t){return{...e,chats:{...e.chats,byId:t}}}function a(e,t,n,r){const{byId:d}=e.chats,o=d[t],a=n.isMin&&o&&!o.isMin,i={...o,...a?Object(u.j)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...o.photos||[]]}};return i.id&&i.type?c(e,{...d,[t]:i}):e}function i(e,t){return Object.keys(t).forEach(n=>{e=a(e,Number(n),t[Number(n)])}),e}function s(e,t){const{byId:n}=e.chats;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=a(e,r,t[r]))}),e}function f(e,t,n){const u=n===r.h?"archived":"active";let d=e.chats.listIds;return Object.keys(d).forEach(e=>{const n=d[e]||[];e!==u||n.includes(t)?e!==u&&n.includes(t)&&(d={...d,[e]:n.filter(e=>e!==t)}):d={...d,[e]:[...n,t]}}),e=a(e={...e,chats:{...e.chats,listIds:d}},t,{folderId:n||void 0})}function l(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}}}}var b=n(5),h=n(6);function m(e,t,n=b.MAIN_THREAD_ID,r="thread"){return{...e,messages:{...e.messages,messageLists:t?[{chatId:t,threadId:n,type:r}]:void 0}}}function p(e,t,n){return g(e,t,{byId:n})}function g(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function y(e,t,n,r,u){return function(e,t,n,r){const u=e.messages.byChatId[t];return g(e,t,{threadsById:{...u&&u.threadsById,[n]:{...u&&u.threadsById[n],...r}}})}(e,t,n,{[r]:u})}function v(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).map(Number).forEach(t=>{e=w(e,t,n[t])}),e}function w(e,t,n){const r=Object(h.m)(e,t);return r&&Object.keys(n).every(e=>Boolean(r[Number(e)]))?e:p(e,t,{...n,...r})}function O(e,t,n,r){const u=Object(h.m)(e,t)||{},d={...u[n],...r};return d.id?p(e,t,{...u,[n]:d}):e}function I(e,t,n,r){const u=Object(h.qb)(e,t)||{},d={...u[n],...r};return d.id?P(e,t,{...u,[n]:d},void 0):e}function j(e,t,n){const r=Object(h.m)(e,t);if(!r)return e;const d=Object(u.j)(r,n),o=Object.values(Object(u.m)(r,n)).filter(({forwardInfo:e})=>e&&e.isLinkedChannelPost);if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach(r=>{let u=Object(h.Y)(e,t,r),d=Object(h.gb)(e,t,r),o=Object(h.Hb)(e,t,r),c=Object(h.jb)(e,t);n.forEach(e=>{u&&u.includes(e)&&(u=u.filter(t=>t!==e)),d&&d.includes(e)&&(d=d.filter(t=>t!==e)),o&&o.includes(e)&&(o=o.filter(t=>t!==e)),c&&c.includes(e)&&(c=c.filter(t=>t!==e))}),e=y(e,t,r,"listedIds",u),e=y(e,t,r,"outlyingIds",d),e=y(e,t,r,"viewportIds",o),e=y(e,t,r,"pinnedIds",c)}),o.length){const n=Object(h.y)(e),r=n&&n.chatId===t&&"thread"===n.type,u=n&&n.threadId;o.forEach(n=>{const{fromChatId:d,fromMessageId:o}=n.forwardInfo,c=Object(h.k)(e,d,o);r&&u===o&&(e=m(e,t)),c&&(e=O(e,d,o,{threadInfo:void 0}))})}return e=p(e,t,d)}function C(e,t,n){const r=Object(h.qb)(e,t);if(!r)return e;const d=Object(u.j)(r,n);let o=Object(h.ob)(e,t);return o&&(n.forEach(e=>{o.includes(e)&&(o=o.filter(t=>t!==e))}),e=y(e,t,b.MAIN_THREAD_ID,"scheduledIds",o)),e=P(e,t,d,void 0)}function E(e,t,n,r){const u=Object(h.Y)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"listedIds",M([...u||[],...d]))}function S(e,t,n,r){const u=Object(h.gb)(e,t,n),d=u&&u.length?r.filter(e=>!u.includes(e)):r;return u&&!d.length?e:y(e,t,n,"outlyingIds",M([...u||[],...d]))}function M(e){return e.sort((e,t)=>e-t)}function A(e,t,n,u){const d=Object(h.Hb)(e,t,n)||[];if(d.includes(u))return e;return y(e,t,n,"viewportIds",M([...d.length{e=T(e,t.chatId,t.threadId,t)}),e}function P(e,t,n,r){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,hash:r})}function D(e,t,n,r=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r}}}function F(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function L(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function B(e,t,n,r,d,o,c,a=!1){const{selectedMessages:i}=e;o&&(c=Object(h.ab)(e,t,o));const s=c||[d];if(!i)return L(e,t,s);const{messageIds:f}=i;let l;const b=s.filter(e=>!f.includes(e));if(b&&!b.length)l=f.filter(e=>!s.includes(e));else if(a&&f.length){const o=Object(h.x)(e,t,n,r),c=o.indexOf(f[f.length-1]),a=o.indexOf(d),i=Math.min(c,a),s=Math.max(c,a),b=o.slice(i,s+1);l=Object(u.o)([...f,...b])}else l=[...f,...b];return l.length?{...e,selectedMessages:{...i,messageIds:l}}:x(e)}function x(e){return{...e,selectedMessages:void 0}}function R(e,t,n,r,d){const o=r.map(t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t});return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...Object(u.c)(o,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:d}:{setIds:r.map(({id:e})=>e)}}}}}function U(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function _(e,t,n,r){const{results:u}=e.gifs.search;let d;if(t||!u)d=n;else{const e=new Set(u.map(e=>e.id));d=[...u,...n.filter(t=>!e.has(t.id))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:d}}}}function G(e,t){return{...e,animatedEmojis:t}}function $(e,t,n,r){const d=[...Object(h.yb)(e,t),...n||[]],o=Object(u.o)(d.map(({id:e})=>e)),c=Object(u.c)(d,"id"),a=o.map(e=>c[e]);return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:a,hash:r}}}}function W(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?$(e,t,n,r):e}var H=n(50);function K(e,t){return{...e,users:{...e.users,byId:t}}}function z(e,t,n){const{byId:r}=e.users,{hash:d,userIds:o}=e.contactList||{},c=r[t],a=n.isMin&&c&&!c.isMin,i={...c,...a?Object(u.j)(n,["isMin","accessHash"]):n};return i.id&&i.type?(i.isContact&&o&&!o.includes(t)&&(e={...e,contactList:{hash:d||0,userIds:[t,...o]}}),K(e,{...r,[t]:i})):e}function V(e,t){return Object.keys(t).map(Number).forEach(n=>{e=z(e,n,t[n])}),e}function q(e,t){const{byId:n}=e.users;return Object.keys(t).map(Number).forEach(r=>{(!n[r]||n[r].isMin&&!t[r].isMin)&&(e=z(e,r,t[r]))}),e}function J(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function Y(e,t){const{byId:n}=e.users,{hash:r,userIds:u}=e.contactList||{};return delete n[t],K(e={...e,contactList:{hash:r||0,userIds:u?u.filter(e=>e!==t):H.a}},n)}const Q=e=>`${e.chatId}_${e.id}`;function Z(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function X(e,t){return Z(e,{currentContent:t})}function ee(e,t,n,r,d){const{resultsByType:o}=e.globalSearch||{},c=t.reduce((e,t)=>(e[Q(t)]=t,e),{}),a=o&&o[r]?o[r].foundIds:void 0;if(void 0!==a&&Object.keys(c).every(e=>a.includes(Q(c[e]))))return te(e,{messages:!1});const i=a||[],s=t.map(e=>Q(e)),f=Array.prototype.concat(i,s),l=Object(u.a)(i,f)?i:f;return Z(e=te(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:d,foundIds:l}}})}function te(e,t){return Z(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ne=n(4);function re(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,u){const d=Object(ne.a)(t,n);return re(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:u})}function de(e,t,n,r,u,d){const o=Object(ne.a)(t,n);return re(e,o,{...e.localTextSearch.byChatThreadKey[o],results:{foundIds:r,totalCount:u,nextOffsetId:d}})}function oe(e,t,n,r,d,o){const c=Object(ne.a)(t,n),{results:a}=e.localTextSearch.byChatThreadKey[c]||{},i=a&&a.foundIds||[],s=se(Object(u.o)(Array.prototype.concat(i,r)));return de(e,t,n,Object(u.a)(i,s)?i:s,d,o)}function ce(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ae(e,t,n){return ce(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ie(e,t,n,r,d,o){const{resultsByType:c}=e.localMediaSearch.byChatId[t]||{},a=c&&c[n]?c[n].foundIds:[],i=se(Object(u.o)(Array.prototype.concat(a,r)));return function(e,t,n,r,u,d){return ce(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:u,nextOffsetId:d}}})}(e,t,n,Object(u.a)(a,i)?a:i,d,o)}function se(e){return e.sort((e,t)=>e-t)}function fe(e,t){return{...e,management:{...e.management,progress:t}}}function le(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function be(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function he(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function me(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function pe(e,t,n,r){switch(t){case"contact":return be(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return be(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return be(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function ge(e,t){return{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function ye(e,t){return{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter(e=>e!==t),totalCount:e.blocked.totalCount-1}}}function ve(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function we(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Oe(e,t){return{...e,payment:{...e.payment,formId:t}}}function Ie(e,t){return{...e,payment:{...e.payment,step:t}}}function je(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,description:u,photoUrl:d}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,description:u,photoUrl:d}}}}function Ce(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function Ee(e,t){return{...e,payment:{...e.payment,...t}}}function Se(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:u,text:d,title:o}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:u,text:d,title:o}}}}function Me(e){return{...e,payment:{}}}function Ae(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},function(e,t,n){"use strict";var r=n(0);t.a=function(e,t){const n=Object(r.q)(),{current:u}=n;return t&&void 0===e||(n.current=e),u}},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));function r(e,t=30){return!e||e.length<=t?e:e.substr(0,t)+"..."}},function(e){e.exports=JSON.parse('{"--color-primary":["#50A2E9","#8378DB"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#121212"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFEDF","#8378DB"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d4fcae","#7b71c6"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#4C90E6","#8378DB"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-borders":["#DADCE0","#100F10"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-links":["#52A1EF","#868DF6"],"--color-links-hover":["#2d8dec","#6b5fcc"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#1010109c"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#4DCD5E","#8378DB"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#DBF4CE","#6458bc"],"--color-reply-own-active":["#C8EBBC","#4F4A9F"],"--color-accent-own":["#4FAE4E","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#52A1EF","#FFFFFF"],"--color-code-own":["#3C7940","#FFFFFF"]}')},function(e,t,n){"use strict";function r(e){return new Promise((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)})}let u;function d(){return u||(u=function(e,t){const n=indexedDB.open(e);n.onupgradeneeded=()=>n.result.createObjectStore(t);const u=r(n);return(e,n)=>u.then(r=>n(r.transaction(t,e).objectStore(t)))}("keyval-store","keyval")),u}function o(e,t=d()){return t("readonly",t=>r(t.get(e)))}function c(e,t=d()){return t("readwrite",t=>(t.delete(e),r(t.transaction)))}function a(e,t){return e("readonly",e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction)))}function i(e=d()){const t=[];return a(e,e=>t.push(e.key)).then(()=>t)}n.d(t,"a",(function(){return c})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return i}))},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);n(97);t.a=e=>{const{icon:t,className:n,children:o,onClick:c,href:a,download:i,disabled:s,destructive:f,ariaLabel:l}=e,b=Object(d.a)(),h=Object(r.m)(e=>{if(s||!c)return e.stopPropagation(),void e.preventDefault();c(e)},[s,c]),m=Object(r.m)(e=>{if(13===e.keyCode||32===e.keyCode)return s||!c?(e.stopPropagation(),void e.preventDefault()):void c(e)},[s,c]),p=Object(u.a)("MenuItem",n,s&&"disabled",f&&"destructive"),g=r.a.createElement(r.a.Fragment,null,t&&r.a.createElement("i",{className:"icon-"+t,"data-char":t.startsWith("char-")?t.replace("char-",""):void 0}),o);return a?r.a.createElement("a",{tabIndex:0,className:p,href:a,download:i,"aria-label":l,title:l,target:a.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:b.isRtl?"rtl":void 0,onClick:c},g):r.a.createElement("div",{role:"button",tabIndex:0,className:p,onClick:h,onKeyDown:m,"aria-label":l,title:l,dir:b.isRtl?"rtl":void 0},g)}},function(e,t,n){"use strict";var r=n(0),u=n(9);n(91);t.a=Object(r.h)(()=>{const[e,t]=Object(r.r)([]),n=Object(r.p)(()=>Object(u.a)(()=>{t([])},700,!1),[]),d=Object(r.m)(r=>{if(0!==r.button)return;const u=r.currentTarget,d=u.getBoundingClientRect(),o=u.offsetWidth/2;t([...e,{x:r.clientX-d.x-o/2,y:r.clientY-d.y-o/2,size:o}]),requestAnimationFrame(()=>{n()})},[e,n]);return r.a.createElement("div",{className:"ripple-container",onMouseDown:d},e.map(({x:e,y:t,size:n})=>r.a.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`})))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return f})),n.d(t,"c",(function(){return l}));var r=n(83),u=n.n(r),d=n(7),o=n(13),c=n(9);let a,i;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function f(e,t){for(b();!i.wasmReady;)await Object(c.e)(2e3);const{result:n,width:r,height:u}=await function(e,t){return new Promise(n=>{i.requests=i.requests||new Map,i.requests.set(e,n),i.postMessage({id:e,blob:t})})}(e,t);if(r&&u)return function({result:e,width:t,height:n}){a||(a=document.createElement("canvas"));return new Promise(r=>{const u=new ImageData(e,t,n);a.width=t,a.height=n;a.getContext("2d").putImageData(u,0,0),a.toBlob(e=>{r(null!=e?e:void 0)},"image/png",1)})}({result:n,width:r,height:u})}async function l(e,t){if(Object(d.p)()||"data:image/webp"!==t.substr(0,15))return t;b();const n=await f(e,Object(o.d)(t));if(!n)throw new Error("Can't convert webp to png. Url: "+t);return Object(o.a)(n)}function b(){i||(i=new u.a,i.wasmReady=!1,i.onmessage=h)}function h(e){const{id:t}=e.data;switch(e.data.type){case"initialized":i.wasmReady=!0;break;case"result":if(i.requests.has(t)){const n=i.requests.get(t);i.requests.delete(t),n(e.data)}}}},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25);t.a=Object(r.h)(({ref:e,id:t,className:n,value:o,label:c,error:a,success:i,disabled:s,readOnly:f,placeholder:l,autoComplete:b,inputMode:h,maxLength:m,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w})=>{const O=Object(d.a)(),I=a||i||c,j=Object(u.a)("input-group",o&&"touched",a?"error":i&&"success",s&&"disabled",f&&"disabled",I&&"with-label",n);return r.a.createElement("div",{className:j,dir:O.isRtl?"rtl":void 0},r.a.createElement("input",{ref:e,className:"form-control",type:"text",id:t,dir:"auto",value:o||"",placeholder:l,maxLength:m,autoComplete:b,inputMode:h,disabled:s,readOnly:f,onChange:p,onInput:g,onKeyPress:y,onKeyDown:v,onBlur:w}),I&&r.a.createElement("label",{htmlFor:t},I))})},function(e,t,n){"use strict";var r=n(0),u=n(8),d=n(25),o=n(21);n(93);t.a=Object(r.h)(({id:e,name:t,value:n,label:c,subLabel:a,checked:i,disabled:s,round:f,blocking:l,isLoading:b,onChange:h,onCheck:m})=>{const p=Object(d.a)(),g=Object(r.m)(e=>{h&&h(e),m&&m(e.currentTarget.checked)},[h,m]),y=Object(u.a)("Checkbox",s&&"disabled",f&&"round",b&&"loading",l&&"blocking");return r.a.createElement("label",{className:y,dir:p.isRtl?"rtl":void 0},r.a.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:i,disabled:s,onChange:g}),r.a.createElement("div",{className:"Checkbox-main"},r.a.createElement("span",{className:"label",dir:"auto"},c),a&&r.a.createElement("span",{className:"subLabel",dir:"auto"},a)),b&&r.a.createElement(o.a,null))})},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(55);function u(e){return Object(r.a)({onEsc:e})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return o}));var r=n(0);let u,d=!1;const o=e=>{document.dispatchEvent(new Event("tt-event-heavy-animation-start")),d=!0,u&&(clearTimeout(u),u=void 0),u=window.setTimeout(()=>{d=!1,document.dispatchEvent(new Event("tt-event-heavy-animation-end")),u=void 0},e)};t.a=(e,t)=>{Object(r.n)(()=>(d&&e(),document.addEventListener("tt-event-heavy-animation-start",e),document.addEventListener("tt-event-heavy-animation-end",t),()=>{document.removeEventListener("tt-event-heavy-animation-end",t),document.removeEventListener("tt-event-heavy-animation-start",e)}),[t,e])}},function(e,t,n){"use strict";function r(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function d(e){return e<1e3?e:e<1e6?u(e/1e3)+"K":u(e/1e6)+"M"}function o(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map(e=>e.length&&e.match(/./u)[0].toUpperCase()).join("")}n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return d})),n.d(t,"c",(function(){return o}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));const r=[]},function(e,t,n){"use strict";var r=n(38);t.a=(e,t)=>{const n=Object(r.a)(t);n&&!t.some((e,t)=>e!==n[t])||e(n||[])}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));const r=/[^\wа-яё]+/;function u(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every(e=>n.some(t=>t.startsWith(e)))}},function(e,t,n){"use strict";var r=n(0),u=n(35),d=n(63),o=n(79),c=n(58),a=n(47),i=n(8),s=n(48);n(95);t.a=({ref:e,containerRef:t,isOpen:n,className:f,style:l,children:b,positionX:h="left",positionY:m="top",autoClose:p=!1,footer:g,noCloseOnBackdrop:y=!1,onCloseAnimationEnd:v,onClose:w,onMouseEnter:O,onMouseLeave:I})=>{let j=Object(r.q)(null);e&&(j=e);const C=t||j,{transitionClassNames:E}=Object(u.a)(n,v);Object(r.n)(()=>n&&w?Object(a.a)(w):void 0,[n,w]),Object(c.a)(([e])=>{void 0!==e&&Object(s.b)(200)},[n]);const S=Object(d.a)(j,n,p?w:void 0,void 0,!0);Object(o.a)(n,C,y?void 0:w);const M=Object(i.a)("bubble menu-container custom-scroll",m,h,g&&"with-footer",E);return r.a.createElement("div",{className:Object(i.a)("Menu no-selection",f),onKeyDown:n?S:void 0,onMouseEnter:O,onMouseLeave:n?I:void 0,style:l},n&&r.a.createElement("div",{className:"backdrop"}),r.a.createElement("div",{ref:j,className:M,style:`transform-origin: ${m} ${h}`,onClick:p?w:void 0},b,g&&r.a.createElement("div",{className:"footer"},g)))}},function(e,t,n){"use strict";n.d(t,"b",(function(){return y})),n.d(t,"c",(function(){return v})),n.d(t,"a",(function(){return w}));var r=n(5),u=n(1),d=n(10),o=n(12),c=n(13),a=n(7),i=n(81),s=n.n(i),f=n(82),l=n.n(f);async function b(e){const t=await new Response(e).arrayBuffer();return new Promise(e=>{const n=new Uint8Array(t);let r=new s.a,u=new l.a;r.onmessage=e=>{null===e.data?u.postMessage({command:"done"}):u.postMessage({command:"encode",buffers:e.data},e.data.map(({buffer:e})=>e))},u.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),r.terminate(),r=void 0,u.terminate(),u=void 0)},u.postMessage({command:"init",wavBitDepth:16,wavSampleRate:48e3}),r.postMessage({command:"init",decoderSampleRate:48e3,outputBufferSampleRate:48e3}),r.postMessage({command:"decode",pages:n},[n.buffer])})}var h=n(44);const m={[r.ApiMediaFormat.DataUri]:o.a.Text,[r.ApiMediaFormat.BlobUrl]:o.a.Blob,[r.ApiMediaFormat.Lottie]:o.a.Json,[r.ApiMediaFormat.Progressive]:void 0,[r.ApiMediaFormat.Stream]:void 0},p=new Map,g=new Map;function y(e,t,n){if(t===r.ApiMediaFormat.Progressive)return a.i?function(e){const t="./progressive/"+e;return p.set(e,t),Promise.resolve(t)}(e):y(e,r.ApiMediaFormat.BlobUrl,n);if(!g.has(e)){const i=async function(e,t,n){if(!u.M){const n=e.startsWith("avatar")?u.O:u.N,r=await o.c(n,e,m[t]);if(r){let t=r;if("audio/ogg"!==r.type||a.h||(t=await b(t)),"image/webp"===r.type&&!Object(a.p)()&&t){const n=await Object(h.b)(e,t);n&&(t=n)}const n=O(t);return p.set(e,n),n}}if(t===r.ApiMediaFormat.Stream){const r=new MediaSource,u=URL.createObjectURL(r);let o=!1;return r.addEventListener("sourceopen",()=>{if(o)return;o=!0;const u=r.addSourceBuffer("audio/mpeg");Object(d.a)("downloadMedia",{url:e,mediaFormat:t},(e,t)=>{n&&n(e),1===e&&r.endOfStream(),t&&u.appendBuffer(t)})}),p.set(e,u),u}const i=await Object(d.a)("downloadMedia",{url:e,mediaFormat:t},n);if(!i)throw new Error("Failed to fetch media");let{prepared:s,mimeType:f}=i;if("audio/ogg"===f&&!a.h){const e=await Object(c.e)(s);URL.revokeObjectURL(s);const t=await b(e);s=O(t),f=e.type}if("image/webp"===f&&!Object(a.p)()){const t=await Object(c.e)(s);URL.revokeObjectURL(s);const n=await Object(h.b)(e,t);n&&(s=O(n))}return p.set(e,s),s}(e,t,n).catch(e=>{u.p&&console.warn(e)}).finally(()=>{g.delete(e)});g.set(e,i)}return g.get(e)}function v(e){return p.get(e)}function w(e){Object(d.b)(e)}function O(e){return e instanceof Blob?URL.createObjectURL(e):e}a.i&&navigator.serviceWorker.addEventListener("message",async e=>{const{type:t,messageId:n,params:u}=e.data;if("requestPart"!==t)return;const o=await Object(d.a)("downloadMedia",{mediaFormat:r.ApiMediaFormat.Progressive,...u});if(!o)return;const{arrayBuffer:c,mimeType:a,fullSize:i}=o;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:c,mimeType:a,fullSize:i}},[c])})},function(e,t,n){"use strict";n.d(t,"a",(function(){return d}));const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",ArrowLeft:"onLeft",ArrowRight:"onRight",Tab:"onTab"},u={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onLeft:[],onRight:[],onTab:[]};function d(e){return o()||document.addEventListener("keydown",c,!0),Object.keys(e).forEach(t=>{const n=e[t];if(!n)return;const r=u[t];r&&r.push(n)}),()=>{!function(e){Object.keys(e).forEach(t=>{const n=e[t],r=u[t];if(r){const e=r.findIndex(e=>e===n);-1!==e&&r.splice(e,1)}}),o()||document.removeEventListener("keydown",c,!1)}(e)}}function o(){return Object.values(u).some(e=>Boolean(e.length))}function c(e){const t=r[e.key];if(!t)return;const{length:n}=u[t];if(!n)return;e.stopPropagation();(0,u[t][n-1])(e)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i}));var r=n(9),u=n(1),d=n(7);const o=d.g&&s();let c=i();const a=Object(r.g)(()=>{c=i(),((c.width<=u.db||c.width<=u.cb&&c.height<=u.bb)!==d.g||d.g&&o!==s())&&window.location.reload()},250,!0);function i(){const e=.01*window.innerHeight;return document.documentElement.style.setProperty("--vh",e+"px"),{width:window.innerWidth,height:window.innerHeight}}function s(){return d.e?window.matchMedia("(orientation: landscape)").matches:window.matchMedia("screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)").matches}window.addEventListener("resize",a),window.addEventListener("orientationchange",a),t.a={get:()=>c}},function(e,t,n){"use strict";var r=n(0),u=n(2);const d=e=>{const t=[];let n=0;const r=e.length;let u;for(;n65535&&(u-=65536,t.push(String.fromCharCode(u>>>10&1023|55296)),u=56320|1023&u),t.push(String.fromCharCode(u))}return t.join("")};function o(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=36)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function c(e,t){const n=[],r=[],u=e.length;let c,a,i,s,f,l,b,h,m,p,g,y,v;for(c=128,i=0,s=72,f=e.lastIndexOf("-"),f<0&&(f=0),l=0;l=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(l))}for(b=f>0?f+1:0;b=u)throw RangeError("punycode_bad_input(1)");if(g=(w=e.charCodeAt(b++))-48<10?w-22:w-65<26?w-65:w-97<26?w-97:36,g>=36)throw RangeError("punycode_bad_input(2)");if(g>Math.floor((2147483647-i)/m))throw RangeError("punycode_overflow(1)");if(i+=g*m,y=p<=s?1:p>=s+26?26:p-s,gMath.floor(2147483647/(36-y)))throw RangeError("punycode_overflow(2)");m*=36-y}if(a=n.length+1,s=o(i-h,a,0===h),Math.floor(i/a)>2147483647-c)throw RangeError("punycode_overflow(3)");c+=Math.floor(i/a),i%=a,t&&r.splice(i,0,e.charCodeAt(b-1)-65<26),n.splice(i,0,c),i++}var w;if(t)for(i=0,v=n.length;iObject(s.l)(t,["toggleSafeLinkModal","openTelegramLink"]))(({url:e,text:t,className:n,children:u,isRtl:d,toggleSafeLinkModal:o,openTelegramLink:c})=>{const a=u||t,s=e!==a,h=Object(r.m)(t=>t.ctrlKey||t.altKey||t.shiftKey||t.metaKey||!e||!e.match(i.ib)&&!e.match(i.hb)?!s||(o({url:e}),t.preventDefault(),!1):(t.preventDefault(),c({url:e}),!1),[s,c,o,e]);if(!e)return;const m=Object(f.a)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.a.createElement("a",{href:l(e),title:b(e),target:"_blank",rel:"noopener noreferrer",className:m,onClick:h,dir:d?"rtl":"auto"},a)}))},function(e,t,n){"use strict";var r=n(0),u=n(38);t.a=(e,t)=>{const n=Object(u.a)(t);return Object(r.n)(()=>e(n||[]),t)}},function(e,t,n){"use strict";n.d(t,"e",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"d",(function(){return d})),n.d(t,"a",(function(){return o})),n.d(t,"c",(function(){return c}));function r(e){return e>536870912?(e/1073741824).toFixed(1)+" GB":e>524288?(e/1048576).toFixed(1)+" MB":(e/1024).toFixed(1)+" KB"}function u(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 o(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 c(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return o}));const r={missing_payment_information:{field:"cardNumber",fieldError:"Incorrect card number"},invalid_number:{field:"cardNumber",fieldError:"Incorrect card number"},number:{field:"cardNumber",fieldError:"Incorrect card number"},exp_year:{field:"expiry",fieldError:"Incorrect year"},exp_month:{field:"expiry",fieldError:"Incorrect month"},invalid_expiry_year:{field:"expiry",fieldError:"Incorrect year"},invalid_expiry_month:{field:"expiry",fieldError:"Incorrect month"},cvc:{field:"cvv",fieldError:"Incorrect CVV"},invalid_cvc:{field:"cvv",fieldError:"Incorrect CVV"}};function u(e){const{message:t,code:n,param:u}=e,{field:d,fieldError:o,description:c}=u?r[u]:r[n];return{field:d,fieldError:o,description:c||t}}const d={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",fieldError:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",fieldError:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",fieldError:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",fieldError:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",fieldError:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",fieldError:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",fieldError:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",fieldError:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",fieldError:"Incorrect email"}};function o(e){return Object.values(e).reduce((e,t)=>{const n=d[t.message];return n&&(e={...e,[n.field]:n.fieldError}),e},{})}},function(e,t,n){"use strict";n.d(t,"b",(function(){return d})),n.d(t,"a",(function(){return o}));var r=n(9);let u;function d(e,t){t||(u&&!u.isCancelled&&(u.isCancelled=!0),u=t={isCancelled:!1}),Object(r.b)(()=>{!t.isCancelled&&e()&&d(e,t)})}function o(e){Object(r.b)(()=>{e()&&o(e)})}},function(e,t,n){"use strict";var r=n(0),u=n(53);n(96);t.a=({trigger:e,className:t,children:n,positionX:d="left",positionY:o="top",footer:c})=>{const a=Object(r.q)(null),i=Object(r.q)(null),[s,f]=Object(r.r)(!1);return r.a.createElement("div",{ref:i,className:"DropdownMenu "+(t||""),onKeyDown:e=>{const t=a.current;if(!s||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{f(!s)},isOpen:s}),r.a.createElement(u.a,{ref:a,containerRef:i,isOpen:s,className:t||"",positionX:d,positionY:o,footer:c,autoClose:!0,onClose:()=>{f(!1)}},n))}},function(e,t,n){"use strict";var r=n(0);t.a=(e,t,n,u,d)=>{const[o,c]=Object(r.r)(-1);Object(r.n)(()=>{c(-1);const n=e.current;t&&n&&!d&&(n.tabIndex=-1,n.focus())},[e,t,d]);return Object(r.m)(t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n(o);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,a=Array.from(u?r.querySelectorAll(u):r.children);let i=d&&a.indexOf(d)||o;if(38===t.keyCode&&i>0)i--;else if(40===t.keyCode&&i{if(e.length>24)return!1;if(!Boolean(e.match(u)))return!1;let t=0;for(;r.a.exec(e);)if(t++,t>3)return r.a.lastIndex=0,!1;return t}},function(e,t,n){"use strict";n.d(t,"a",(function(){return d})),n.d(t,"b",(function(){return o}));const r=["female_sign","male_sign","medical_symbol"];function u(e){const t=e.split("-").map(e=>parseInt(e,16));return String.fromCodePoint(...t)}function d(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 o(e){const t={categories:[],emojis:{}};for(let n=0;n{void 0!==e.props[r]&&void 0===t.props[r]&&g(n,r,e.props[r])}),u.forEach(r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?p(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(g(e,t,n),p(e,t,r))}(n,r,e.props[r],t.props[r]))})}(t,n,Object(r.b)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const u=new Set(t.children.map(e=>{const t="props"in e&&e.props.key;return d.p&&Object(r.f)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t}));let o=0;const c=e.children.reduce((e,r,d)=>{let c="props"in r?r.props.key:void 0;if(c&&!u.has(c))return f(n,r,void 0,t,-1),e;if(!c){const u=t.children[d],o=u&&"props"in u?u.props.key:void 0;if(!u||o)return f(n,r,void 0,t,-1),e;c="__indexKey#"+d}return e[c]={$element:r,index:o++,order:"props"in r?r.props.teactOrderKey:void 0},e},{});let a,i,s=[],l=0;t.children.forEach((e,r)=>{const u="props"in e?e.props.key:"__indexKey#"+r,d=c[u];if(!d)return a||(a=[],i=r),void a.push(e);a&&(s=s.concat(m(a,i,n,t)),i=void 0,a=void 0);const o="props"in e?e.props.teactOrderKey:void 0,b=d.index!==l&&d.order!==o,h=b&&l>d.index;b&&!h||l++,s.push(f(n,d.$element,e,t,r,{forceIndex:!0,...b&&{moveDirection:h?"down":"up"}}))}),a&&(s=s.concat(m(a,i,n,t)));return s}(e,t,n);const u=Math.max(e.children.length,t.children.length),o=[],c=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:c}:void 0);u&&o.push(u)}c&&n.appendChild(c);return o}(t,n,u?e:Object(r.b)(t))}}return n}function l(e,t,n,u){if(!Object(r.d)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){b(e=Object(r.i)(d),t,n,u);const o=e.children[0];Object(r.d)(o)&&(e.children=[l(o,e,0,u)]),d.isMounted=!0}return e}function b(e,t,n,r){const{componentInstance:u}=e;u.onUpdate=()=>{t.children[n]=f(r,t.children[n],u.$element,t,n,{skipComponentUpdate:!0})}}function h(e){if(Object(r.e)(e))return document.createTextNode("");if(Object(r.g)(e))return document.createTextNode(e.value);if(Object(r.d)(e))return h(e.children[0]);const{tag:t,props:n,children:u=[]}=e,d=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=d),Object.keys(n).forEach(e=>{p(d,e,n[e])}),e.children=u.map((t,n)=>f(d,void 0,t,e,n)),d}function m(e,t,n,r){if(1===e.length)return[f(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const u=document.createDocumentFragment(),d=e.map(e=>f(n,void 0,e,r,t,{fragment:u}));return n.childNodes[t]?n.insertBefore(u,n.childNodes[t]):n.appendChild(u),d}throw new Error("Unexpected input")}function p(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?Object(o.a)(e,t,n):t.startsWith("data-")||a.has(t)?e.setAttribute(t,n):c.has(t)||(e[i[t]||t]=n))}function g(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?Object(o.c)(e,t,n):t.startsWith("data-")||a.has(t)?e.removeAttribute(t):c.has(t)||delete e[i[t]||t]}t.a={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=Object(u.a)(s),s[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=s[n];r.children=[f(t,r.children[0],e,r,0)]}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return h}));var r=n(0),u=n(4),d=n(39),o=n(23),c=n(2),a=n(3),i=n(8),s=n(27);var f=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openUserInfo"]))(({className:e,sender:t,openUserInfo:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t.id})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("UserLink",e),onClick:d},u):u});var l=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["focusMessage"]))(({className:e,message:t,children:n,focusMessage:u})=>{const d=Object(r.m)(()=>{t&&u({chatId:t.chatId,messageId:t.id})},[u,t]);return t?r.a.createElement(s.a,{className:Object(i.a)("MessageLink",e),onClick:d},n):n});var b=Object(c.h)(void 0,(e,t)=>Object(a.l)(t,["openChat"]))(({className:e,chatId:t,openChat:n,children:u})=>{const d=Object(r.m)(()=>{t&&n({id:t})},[t,n]);return t?r.a.createElement(s.a,{className:Object(i.a)("ChatLink",e),onClick:d},u):u});function h(e,t,n,c,a,i,s={}){if(!t.content.action)return[];const{text:f}=t.content.action,h=[],g={...s,maxTextLength:16};let y,v=p(f,"%action_origin%",n?!s.isEmbedded&&function(e,t,n){return Object(u.fb)(t)?function(e,t,n){const c=Object(d.a)(Object(u.l)(e,t));if(n)return c;return r.a.createElement(b,{className:"action-link",chatId:t.id},t&&Object(o.a)(c))}(e,t,n):m(t,n)}(e,n,s.asPlain)||" ":"User");return y=v.pop(),h.push(...v),v=p(y,"%target_user%",c?m(c,s.asPlain):"User"),y=v.pop(),h.push(...v),v=p(y,"%message%",a?function(e,t,n={}){const c=Object(u.N)(e,t),{photo:a,video:i,document:s,sticker:f}=Object(u.v)(t),b=c&&!a&&!i&&!s&&!f;let h=Object(d.a)(c,n.maxTextLength);a?h="a photo":i?h=i.isGif?"a GIF":"a video":s?h="a document":f&&(h=`«${c}»`);if(n.asPlain)return b?`«${h}»`:h;if(b)return r.a.createElement("span",null,"«",r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h)),"»");return r.a.createElement(l,{className:"action-link",message:t},Object(o.a)(h))}(e,a,g):"a message"),y=v.pop(),h.push(...v),v=p(y,"%product%",a?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(a):"a product"),y=v.pop(),h.push(...v),v=p(y,"%target_chat%",i?function(e,t){if(t)return"another chat";return r.a.createElement(b,{className:"action-link",chatId:e},"another chat")}(i,s.asPlain):"another chat"),h.push(...v),s.asPlain?h.join("").trim():h}function m(e,t){const n=Object(d.a)(Object(u.Z)(e));return t?n:r.a.createElement(f,{className:"action-link",sender:e},e&&Object(o.a)(n))}function p(e,t,n){const r=e.indexOf(t);if(r<0||!n)return[e];const u=[];return u.push(e.substring(0,r)),u.push(n),u.push(e.substring(r+t.length)),u}},function(e,t){},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),n.d(t,"b",(function(){return u})),n.d(t,"c",(function(){return d})),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const u=-1,d="MESSAGE_DELETED"},function(e,t){},function(e,t,n){"use strict";let r;n.d(t,"a",(function(){return r})),function(e){e[e.DataUri=0]="DataUri",e[e.BlobUrl=1]="BlobUrl",e[e.Lottie=2]="Lottie",e[e.Progressive=3]="Progressive",e[e.Stream=4]="Stream"}(r||(r={}))},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){"use strict";var r=n(0),u=n(2),d=n(3),o=n(6);t.a=Object(u.h)((e,{userId:t})=>({userOrChat:t?Object(o.Gb)(e,t):void 0}),(e,t)=>Object(d.l)(t,["openChat","openChatByUsername"]))(({username:e,userOrChat:t,children:n,openChat:u,openChatByUsername:d})=>r.a.createElement("a",{onClick:()=>{t?u({id:t.id}):e&&d({username:e.substring(1)})},className:"text-entity-link",dir:"auto"},n))},function(e,t,n){"use strict";var r=n(61),u=n(40);let d=!1;const o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,c=(e,t,n)=>(1-n)*e+n*t,a=Object.keys(u).map(e=>({property:e,colors:[i(u[e][0]),i(u[e][1])]}));function i(e){const t=o.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 s(e,t,n=1){a.forEach(({property:r,colors:u})=>{const d=Math.round(c(u[e].r,u[t].r,n)),o=Math.round(c(u[e].g,u[t].g,n)),a=Math.round(c(u[e].b,u[t].b,n)),i=void 0!==u[e].a?Math.round(c(u[e].a,u[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==i?`rgba(${d},${o},${a},${i/255})`:`rgb(${d},${o},${a})`)})}t.a=(e,t)=>{const n="dark"===e,u=d&&t,o=n?0:1,c=n?1:0,a=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),d&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add("theme-"+e),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout(()=>{document.documentElement.classList.remove("no-animations")},500),d=!0,u?Object(r.b)(()=>{const e=Math.min((Date.now()-a)/200,1);return s(o,c,function(e){return 1-(1-e)**3.5}(e)),e<1}):s(o,c)}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(1);function u(e){"function"==typeof window.navigator.setAppBadge&&window.navigator.setAppBadge(e).catch(e=>{r.p&&console.error(e)})}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(0);function u(e,t,n){Object(r.n)(()=>{const r=e=>{const r=t.current,u=e.target;r&&u&&(r.contains(e.target)&&!u.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}},[e,t,n])}},function(e,t,n){e.exports=function(){return new Worker(n.p+"8ede9bdfe3390ee397af.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"01705582fc3eca0e007b.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"0dbbe0a906f6c2adf071.worker.js")}},function(e,t,n){e.exports=function(){return new Worker(n.p+"a66075669d8d0ac2d740.worker.js")}},function(e,t,n){"use strict";var r=n(2),u=n(7),d=n(14),o=n(77);Object(r.b)("init",e=>{const{theme:t,animationLevel:n,messageTextSize:r,language:c}=e.settings.byKey;Object(d.c)(c),document.documentElement.style.setProperty("--message-text-size",r+"px"),document.body.classList.add("initial"),document.body.classList.add("animation-level-"+n),document.body.classList.add(u.l?"is-touch-env":"is-pointer-env"),Object(o.a)(t,n>0),u.j&&document.body.classList.add("is-safari"),u.e?document.body.classList.add("is-ios"):u.b&&document.body.classList.add("is-android")}),Object(r.b)("setIsUiReady",(e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}}),Object(r.b)("setAuthRememberMe",(e,t,n)=>({...e,authRememberMe:Boolean(n)})),Object(r.b)("clearAuthError",e=>({...e,authError:void 0}))},function(e,t,n){"use strict";var r=n(2),u=n(1),d=n(10),o=n(29),c=n(12),a=n(78),i=n(19);Object(r.b)("initApi",(e,t)=>{(async()=>{u.E?Object(i.d)():(await Object(i.c)(),Object(i.a)()),Object(d.c)(t.apiUpdate,Object(i.e)())})()}),Object(r.b)("setAuthPhoneNumber",(e,t,n)=>{const{phoneNumber:r}=n;return Object(d.a)("provideAuthPhoneNumber",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthCode",(e,t,n)=>{const{code:r}=n;return Object(d.a)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("setAuthPassword",(e,t,n)=>{const{password:r}=n;return Object(d.a)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("uploadProfilePhoto",(e,t,n)=>{const{file:r}=n;Object(d.a)("uploadProfilePhoto",r)}),Object(r.b)("signUp",(e,t,n)=>{const{firstName:r,lastName:u}=n;return Object(d.a)("provideAuthRegistration",{firstName:r,lastName:u}),{...e,authIsLoading:!0,authError:void 0}}),Object(r.b)("returnToAuthPhoneNumber",e=>(Object(d.a)("restartAuth"),{...e,authError:void 0})),Object(r.b)("gotToAuthQrCode",e=>(Object(d.a)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0})),Object(r.b)("saveSession",(e,t,n)=>{const{sessionData:r}=n;r?Object(i.f)(n.sessionData,e.currentUserId):Object(i.b)()}),Object(r.b)("signOut",()=>{(async()=>{await Object(o.d)(),await Object(d.a)("destroy"),Object(r.d)().reset()})()}),Object(r.b)("reset",()=>{Object(i.b)(),c.b(u.N),c.b(u.O),c.b(u.P),c.b(u.m);const e=u.F.replace(/\d+$/,""),t=(u.F.match(/\d+$/)||[0])[0];for(let n=0;n{(async()=>{await Object(d.a)("disconnect")})()}),Object(r.b)("loadNearestCountry",e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await Object(d.a)("fetchNearestCountry");Object(r.g)({...Object(r.e)(),authNearestCountry:e})})()}),Object(r.b)("setDeviceToken",(e,t,n)=>{Object(r.g)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})}),Object(r.b)("deleteDeviceToken",e=>{const t={...e};delete t.push,Object(r.g)(t)})},function(e,t){var n,r,u=e.exports={};function d(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function c(e){if(n===setTimeout)return setTimeout(e,0);if((n===d||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:d}catch(e){n=d}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,i=[],s=!1,f=-1;function l(){s&&a&&(s=!1,a.length?i=a.concat(i):f=-1,i.length&&b())}function b(){if(!s){var e=c(l);s=!0;for(var t=i.length;t;){for(a=i,i=[];++f1)for(var n=1;n{switch(u.p&&"updateUserStatus"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){Object(d.c)(),Object(c.c)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=Object(r.e)();const n="authorizationStateReady"===t.authState,u=e.authorizationState;switch(Object(r.g)({...t,authState:u,authIsLoading:!1}),t=Object(r.e)(),u){case"authorizationStateLoggingOut":Object(r.g)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":Object(r.g)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":Object(r.g)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":Object(r.g)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":if(n)break;Object(r.g)({...t,isLoggingOut:!1,lastSyncTime:Date.now()})}}(n);break;case"updateAuthorizationError":!function(e){Object(r.g)({...Object(r.e)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=Object(r.e)();Object(r.g)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?Object(r.d)().sync():"connectionStateBroken"===t&&Object(r.d)().signOut()}(n);break;case"updateSession":!function(e){if(!Object(r.e)().authRememberMe)return;const{sessionData:t}=e;Object(r.d)().saveSession({sessionData:t})}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;Object(r.g)({...Object(o.nb)(Object(r.e)(),t.id,t),currentUserId:t.id}),function(e){const t=localStorage.getItem(u.nb);if(!t)return;const n=JSON.parse(t);n.id=e,localStorage.setItem(u.nb,JSON.stringify(n))}(t.id)}(n);break;case"error":"SESSION_REVOKED"===n.error.message&&t.signOut(),t.showError({error:n.error})}})},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){},function(e,t,n){"use strict";n.r(t);n(22),function(){function e(){var t=Error.call(this,"ServiceWorker is not supported.");return Object.setPrototypeOf(t,e.prototype),t}e.prototype=Object.create(Error.prototype)}();var r=n.p+"serviceWorker.js";var u=n(1),d=n(2),o=n(7),c=n(29);function a(e){const t=e.data;if(!t.type)return;const n=Object(d.d)();switch(t.type){case"focusMessage":n.focusMessage(t.payload)}}function i(){navigator.serviceWorker.removeEventListener("message",a),navigator.serviceWorker.addEventListener("message",a),Object(c.a)()}o.k&&(window.addEventListener("load",async()=>{try{await navigator.serviceWorker.register(r),u.p&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(u.p&&console.log("[SW] ServiceWorker ready"),i()):(u.p&&console.error("[SW] ServiceWorker not available"),Object(d.d)().showError({error:{message:"SERVICE_WORKER_DISABLED"}}))}catch(e){u.p&&console.error("[SW] ServiceWorker registration failed: ",e)}}),window.addEventListener("focus",async()=>{await navigator.serviceWorker.ready,i()}));var s=n(66);const f={isLeftColumnShown:!0,isChatInfoShown:!1,uiReadyState:0,authRememberMe:!0,blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{}},scheduledMessages:{byChatId:{}},chatFolders:{byId:{},activeChatFolder:0},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},emojiKeywords:{},gifs:{saved:{},search:{}},globalSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},mediaViewer:{},audioPlayer:{},forwardMessages:{},pollResults:{},payment:{},notifications:[],errors:[],activeSessions:[],settings:{byKey:{messageTextSize:u.s,animationLevel:u.d,messageSendKeyCombo:"enter",theme:"light",shouldAutoDownloadMediaFromContacts:!0,shouldAutoDownloadMediaInPrivateChats:!0,shouldAutoDownloadMediaInGroups:!0,shouldAutoDownloadMediaInChannels:!0,shouldAutoPlayGifs:!0,shouldAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en"},themes:{light:{isBlurred:!0,patternColor:u.t},dark:{isBlurred:!0,patternColor:u.o}},privacy:{},notifyExceptions:{}},twoFaSettings:{}};var l=n(5),b=n(9),h=n(3),m=n(6);const p=Object(b.g)((function(){Object(b.c)(()=>{if(!g)return;const e=Object(d.e)();if(e.isLoggingOut)return;const t={...f,...Object(h.l)(e,["authState","authPhoneNumber","authRememberMe","authNearestCountry","currentUserId","contactList","chatFolders","topPeers","recentEmojis","emojiKeywords","push"]),isChatInfoShown:v(e),users:w(e),chats:O(e),messages:I(e),globalSearch:{recentlyFoundChatIds:e.globalSearch.recentlyFoundChatIds},settings:j(e)},n=JSON.stringify(t);localStorage.setItem(u.B,n)})}),1e3,!1);let g=!1;function y(e){if(!u.A){if(localStorage.getItem(u.nb)||localStorage.getItem(u.H))return g=!0,Object(d.a)(p),function(e){u.p&&console.time("global-state-cache-read");const t=localStorage.getItem(u.B),n=t?JSON.parse(t):void 0;u.p&&console.timeEnd("global-state-cache-read");n&&(n.settings.byKey={...e.settings.byKey,...n.settings.byKey},n.settings.themes={...e.settings.themes,...n.settings.themes},n.chatFolders={...e.chatFolders,...n.chatFolders});return{...e,...n}}(e);g=!1}}function v(e){return window.innerWidth>u.ab&&e.isChatInfoShown}function w(e){const{users:{byId:t,selectedId:n}}=e,r=[...(e.chats.listIds.active||[]).slice(0,u.z).filter(e=>e>0),...Object.keys(t)].slice(0,u.C);return{byId:Object(h.l)(t,r),selectedId:window.innerWidth>u.ab?n:void 0}}function O(e){const t=[...(e.chats.listIds.active||[]).slice(0,u.z)],{chatId:n}=Object(m.y)(e)||{};return{...e.chats,byId:Object(h.l)(e.chats.byId,n?[...t,n]:t),listIds:{active:t},isFullyLoaded:{},orderedPinnedIds:{active:e.chats.orderedPinnedIds.active}}}function I(e){const t={},{chatId:n}=Object(m.y)(e)||{};[...(e.chats.listIds.active||[]).slice(0,u.z),...n?[n]:[]].forEach(n=>{const r=e.messages.byChatId[n];if(!r)return;const u=r.threadsById[l.MAIN_THREAD_ID];u&&u.viewportIds&&(t[n]={byId:Object(h.l)(r.byId,u.viewportIds),threadsById:{[l.MAIN_THREAD_ID]:u}})});const r=Object(m.y)(e);return{byChatId:t,messageLists:!r||o.g?void 0:[{...r,threadId:l.MAIN_THREAD_ID,type:"thread"}]}}function j(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}u.A||(Object(d.b)("saveSession",()=>{g=!0,Object(d.a)(p)}),Object(d.b)("reset",()=>{g=!1,Object(d.f)(p),localStorage.removeItem(u.B)})),Object(d.b)("init",()=>{const e=Object(h.d)(f),t=y(e)||e,n=Object(m.y)(t)||{};return window.history.replaceState(n,""),t});var C=n(0),E=n(56);const S=String(Date.now()+Math.random());let M;localStorage.setItem("tt-active-tab",S);const A=window.setInterval(()=>{M&&localStorage.getItem("tt-active-tab")!==S&&(M(),clearInterval(A))},2e3);var k=n(34),T=(n(84),n(85),n(87),n(31)),N=n(35),P=n(13);const D=["400 1em Roboto","500 1em Roboto"];function F(){if("fonts"in document)return Promise.all(D.map(e=>document.fonts.load(e)))}var L=n(54),B=n(11),x=n(8),R=(n(89),n.p+"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg"),U=n.p+"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg";function _(){const{listIds:e,byId:t}=Object(d.e)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map(e=>{const n=t[e];if(!n)return;const r=Object(T.d)(n);return r?L.b(r,l.ApiMediaFormat.DataUri):void 0}))}const G={main:()=>Promise.all([Object(B.d)(B.a.Main,"Main").then(F),_()]),authPhoneNumber:()=>Promise.all([F(),Object(P.g)(R)]),authCode:()=>Object(P.g)(U),authPassword:()=>Object(P.g)(U),authQrCode:F};var $=Object(d.h)(e=>{const{theme:t}=e.settings.byKey,{background:n,backgroundColor:r}=e.settings.themes[t]||{};return{uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(n),hasCustomBackgroundColor:Boolean(r),isRightColumnShown:Object(m.W)(e)}},(e,t)=>Object(h.l)(t,["setIsUiReady"]))(({page:e,children:t,hasCustomBackground:n,hasCustomBackgroundColor:r,isRightColumnShown:u,setIsUiReady:d})=>{const[o,c]=Object(k.a)(),{shouldRender:a,transitionClassNames:i}=Object(N.a)(!o,void 0,!0);return Object(C.n)(()=>{let t;return Promise.race([Object(b.e)(700),(async()=>{try{await G[e]()}catch(e){}})()]).then(()=>{c(),d({uiReadyState:1}),t=window.setTimeout(()=>{d({uiReadyState:2})},1e3)}),()=>{t&&(clearTimeout(t),t=void 0),d({uiReadyState:0})}},[]),C.a.createElement("div",{id:"UiLoader"},t,a&&C.a.createElement("div",{className:Object(x.a)("mask",i)},"main"===e?C.a.createElement(C.a.Fragment,null,C.a.createElement("div",{className:"left"}),C.a.createElement("div",{className:Object(x.a)("middle",n&&"custom-bg-image",r&&"custom-bg-color",u&&"with-right-column")}),u&&C.a.createElement("div",{className:"right"})):C.a.createElement("div",{className:"blank"})))}),W=n(18),H=n(32),K=n(46),z=n(45),V=n(16),q=n(52),J=n(23),Y=n(62),Q=n(42),Z=n(21);n(98);const X=200+u.c;var ee=Object(C.h)(({id:e,value:t,isLoading:n,onChange:r})=>{const u=Object(C.q)(null),[d,o]=Object(C.r)(),[c,a]=Object(C.r)(W.a);function i(e){o(e),a(function(e=""){return e.length?W.a.filter(t=>Object(q.a)(t.name,e)):W.a}(e))}const s=Object(C.m)(e=>{const{countryId:t}=e.currentTarget.firstElementChild.dataset,n=W.a.find(e=>e.id===t);n&&r(n),setTimeout(()=>i(void 0),X)},[r]),f=Object(C.m)(e=>{i(e.currentTarget.value)},[]),l=Object(C.m)(e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===d&&(n.value=""),i(n.value)},[d,t]);return C.a.createElement(Y.a,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:o})=>{const c=()=>{if(o)return;setTimeout(()=>{u.current.select()},50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},a=void 0!==d?d:t&&t.name||"";return C.a.createElement("div",{className:Object(x.a)("input-group",t&&"touched")},C.a.createElement("input",{ref:u,className:Object(x.a)("form-control",o&&"focus"),type:"text",id:e,value:a,autoComplete:"off",onClick:c,onFocus:c,onInput:f,onKeyDown:l}),C.a.createElement("label",null,"Country"),n?C.a.createElement(Z.a,{color:"black"}):C.a.createElement("i",{onClick:c,className:Object(x.a)("css-icon-down",o&&"open")}))}},c.map(e=>C.a.createElement(Q.a,{key:e.id,className:t&&e.id===t.id?"selected":"",onClick:s},C.a.createElement("span",{"data-country-id":e.id}),C.a.createElement("span",{className:"country-flag"},Object(J.a)(e.flag,["hq_emoji"])),C.a.createElement("span",{className:"country-name"},e.name),C.a.createElement("span",{className:"country-code"},e.code))),!c.length&&C.a.createElement(Q.a,{key:"no-results",className:"no-results",disabled:!0},C.a.createElement("span",null,"No countries matched your filter.")))});let te=!1;var ne=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),(e,t)=>Object(h.l)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","gotToAuthQrCode"]))(({connectionState:e,authState:t,authPhoneNumber:n,authIsLoading:r,authIsLoadingQrCode:u,authError:d,authRememberMe:c,authNearestCountry:a,setAuthPhoneNumber:i,setAuthRememberMe:s,loadNearestCountry:f,clearAuthError:l,gotToAuthQrCode:b})=>{const h=Object(C.q)(null),[m,p]=Object(C.r)(),[g,y]=Object(C.r)(),[v,w]=Object(C.r)(!1),[O,I]=Object(C.r)(),j=m?`${m.code} ${g||""}`:g,E=j&&j.replace(/[^\d]+/g,"").length>=7;Object(C.n)(()=>{o.l||h.current.focus()},[m]),Object(C.n)(()=>{"connectionStateReady"!==e||a||f()},[e,a,f]),Object(C.n)(()=>{!a||m||v||p(Object(W.d)(a))},[m,a,v]);const S=Object(C.m)(e=>{const t=Object(W.e)(e),n=!m||t&&t.id!==m.id?t:m;e.length?(!m||n&&n.code!==m.code)&&p(n):p(void 0),y(Object(W.b)(e,n))},[m]);Object(C.n)(()=>{void 0===g&&n&&S(n)},[n,g,S]),Object(C.o)(()=>{h.current&&O&&h.current.setSelectionRange(...O)},[O]);const M=Object(C.m)(e=>{d&&l(),te||(te=!0,F(),Object(P.g)(U));const{value:t,selectionStart:n,selectionEnd:r}=e.target;I(n&&r&&r{s(e.target.checked)},[s]);const k="authorizationStateWaitPhoneNumber"===t;return C.a.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},C.a.createElement("div",{className:"auth-form"},C.a.createElement("div",{id:"logo"}),C.a.createElement("h2",null,"Sign in to Telegram"),C.a.createElement("p",{className:"note"},"Please confirm your country and",C.a.createElement("br",null),"enter your phone number."),C.a.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),r||E&&i({phoneNumber:j})}},C.a.createElement(ee,{id:"sign-in-phone-code",value:m,isLoading:!a&&!m,onChange:p}),C.a.createElement(z.a,{ref:h,id:"sign-in-phone-number",label:"Phone Number",value:j,error:d,inputMode:"tel",onChange:M}),C.a.createElement(K.a,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(c),onChange:A}),E&&(k?C.a.createElement(H.a,{type:"submit",ripple:!0,isLoading:r},"Next"):C.a.createElement(V.a,null)),k&&C.a.createElement(H.a,{isText:!0,ripple:!0,isLoading:u,onClick:b},"Log in by QR code"))))})),re=n(17);var ue=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthCode");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});var de=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthPassword");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});var oe=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthRegister");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});var ce=Object(C.h)(()=>{const e=Object(re.a)(B.a.Auth,"AuthQrCode");return e?C.a.createElement(e,null):C.a.createElement(V.a,null)});n(99);var ae=Object(C.h)(Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["reset","initApi"]))(({authState:e,reset:t,initApi:n})=>{switch(Object(C.n)(()=>{t(),n()},[t,n]),Object(C.n)(()=>{},[]),e){case"authorizationStateWaitCode":return C.a.createElement($,{page:"authCode",key:"authCode"},C.a.createElement(ue,null));case"authorizationStateWaitPassword":return C.a.createElement($,{page:"authPassword",key:"authPassword"},C.a.createElement(de,null));case"authorizationStateWaitRegistration":return C.a.createElement(oe,null);case"authorizationStateWaitQrCode":return C.a.createElement($,{page:"authQrCode",key:"authQrCode"},C.a.createElement(ce,null));case"authorizationStateWaitPhoneNumber":default:return C.a.createElement($,{page:"authPhoneNumber",key:"authPhoneNumber"},C.a.createElement(ne,null))}}));var ie=Object(C.h)(()=>{const e=Object(re.a)(B.a.Main,"Main");return e?C.a.createElement(e,null):void 0}),se=n.p+"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png";n(100);var fe=()=>C.a.createElement("div",{id:"AppInactive"},C.a.createElement("div",{className:"content"},C.a.createElement("img",{src:se,alt:""}),C.a.createElement("h3",{className:"title"},"Such error, many tabs"),C.a.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",C.a.createElement("br",null),"Please reload this page to continue using this tab or close it."),C.a.createElement("div",{className:"actions"},C.a.createElement(H.a,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function le(){return d.c.createElement($,{page:"main",key:"main"},d.c.createElement(ie,null))}var be=Object(d.h)(e=>Object(h.l)(e,["authState"]),(e,t)=>Object(h.l)(t,["disconnect"]))(({authState:e,disconnect:t})=>{const[n,r]=Object(k.a)(!1);if(Object(C.n)(()=>{Object(E.b)(),M=()=>{t(),document.title=`${u.eb}${u.D}`,r()}},[t,r]),n)return d.c.createElement(fe,null);if(e)switch(e){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return d.c.createElement(ae,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return le()}return localStorage.getItem(u.nb)||localStorage.getItem(u.H)?le():d.c.createElement(ae,null)});n(101);u.p&&console.log(">>> INIT"),Object(d.d)().init(),u.p&&console.log(">>> START INITIAL RENDER"),s.a.render(d.c.createElement(be,null),document.getElementById("root")),u.p&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",()=>{console.log("GLOBAL STATE",Object(d.e)())})}]); +//# sourceMappingURL=main.8fc50c5cddc24213b18b.js.map \ No newline at end of file diff --git a/dist/main.7c95ea3f46a28615bf1a.js.map b/dist/main.8fc50c5cddc24213b18b.js.map similarity index 99% rename from dist/main.7c95ea3f46a28615bf1a.js.map rename to dist/main.8fc50c5cddc24213b18b.js.map index 4d191514..dcf4a551 100644 --- a/dist/main.7c95ea3f46a28615bf1a.js.map +++ b/dist/main.8fc50c5cddc24213b18b.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/config.ts","webpack:///./src/lib/teact/teactn.tsx","webpack:///./src/util/iteratees.ts","webpack:///./src/modules/helpers/messages.ts","webpack:///./src/modules/helpers/messageMedia.ts","webpack:///./src/modules/helpers/localSearch.ts","webpack:///./src/api/types/index.ts","webpack:///./src/modules/selectors/users.ts","webpack:///./src/modules/selectors/settings.ts","webpack:///./src/modules/selectors/chats.ts","webpack:///./src/modules/selectors/symbols.ts","webpack:///./src/modules/selectors/messages.ts","webpack:///./src/modules/selectors/localSearch.ts","webpack:///./src/modules/selectors/management.ts","webpack:///./src/modules/selectors/ui.ts","webpack:///./src/modules/selectors/globalSearch.ts","webpack:///./src/modules/selectors/payments.ts","webpack:///./src/util/environment.ts","webpack:///./src/util/buildClassName.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/util/files.ts","webpack:///./src/assets/lang/en-extra.json","webpack:///./src/assets/lang/es-extra.json","webpack:///./src/assets/lang/it-extra.json","webpack:///./src/assets/lang/pl-extra.json","webpack:///./src/assets/lang/ru-extra.json","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/modules/actions/api/sessions.ts","webpack:///./src/types/index.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/util/arePropsShallowEqual.ts","webpack:///./src/hooks/useLang.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/util/generateIdFor.ts","webpack:///./src/util/notifications.ts","webpack:///./src/modules/helpers/users.ts","webpack:///./src/modules/helpers/chats.ts","webpack:///./src/components/ui/Button.tsx","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/modules/reducers/chats.ts","webpack:///./src/modules/reducers/messages.ts","webpack:///./src/modules/reducers/symbols.ts","webpack:///./src/modules/reducers/users.ts","webpack:///./src/modules/reducers/globalSearch.ts","webpack:///./src/modules/reducers/localSearch.ts","webpack:///./src/modules/reducers/management.ts","webpack:///./src/modules/reducers/settings.ts","webpack:///./src/modules/reducers/twoFaSettings.ts","webpack:///./src/modules/reducers/payments.ts","webpack:///./src/hooks/usePrevious.ts","webpack:///./src/util/trimText.ts","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/components/ui/MenuItem.tsx","webpack:///./src/components/ui/RippleEffect.tsx","webpack:///./src/util/webpToPng.ts","webpack:///./src/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/hooks/useEffectWithPrevDeps.ts","webpack:///./src/components/common/helpers/documentInfo.ts","webpack:///./src/modules/helpers/payments.ts","webpack:///./src/util/animation.ts","webpack:///./src/components/ui/DropdownMenu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.ts","webpack:///./src/util/emoji.ts","webpack:///./src/lib/teact/teact-dom.ts","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/components/middle/message/MentionLink.tsx","webpack:///./src/util/switchTheme.ts","webpack:///./src/util/appBadge.ts","webpack:///./src/hooks/useVirtualBackdrop.ts","webpack:///./src/api/gramjs/worker/worker.ts","webpack:///./node_modules/opus-recorder/dist/decoderWorker.min.js","webpack:///./node_modules/opus-recorder/dist/waveWorker.min.js","webpack:///./src/lib/webp/webp_wasm.worker.js","webpack:///./src/modules/actions/ui/initial.ts","webpack:///./src/modules/actions/api/initial.ts","webpack:///./node_modules/process/browser.js","webpack:///./src/modules/actions/apiUpdaters/initial.ts","webpack:///./src/serviceWorker.ts","webpack:///./src/util/setupServiceWorker.ts","webpack:///./src/global/initial.ts","webpack:///./src/global/cache.ts","webpack:///./src/global/index.ts","webpack:///./src/util/activeTabMonitor.ts","webpack:///./src/util/fonts.ts","webpack:///./src/assets/telegram-logo.svg","webpack:///./src/assets/monkey.svg","webpack:///./src/components/common/UiLoader.tsx","webpack:///./src/components/auth/CountryCodeInput.tsx","webpack:///./src/components/auth/AuthPhoneNumber.tsx","webpack:///./src/components/auth/AuthCode.async.tsx","webpack:///./src/components/auth/AuthPassword.async.tsx","webpack:///./src/components/auth/AuthRegister.async.tsx","webpack:///./src/components/auth/AuthQrCode.async.tsx","webpack:///./src/components/auth/Auth.tsx","webpack:///./src/components/main/Main.async.tsx","webpack:///./src/assets/app-inactive.png","webpack:///./src/components/main/AppInactive.tsx","webpack:///./src/App.tsx","webpack:///./src/index.tsx"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","installedModules","installedCssChunks","2","__webpack_require__","exports","module","l","e","promises","Promise","resolve","reject","href","fullhref","p","existingLinkTags","document","getElementsByTagName","dataHref","tag","getAttribute","rel","existingStyleTags","linkTag","createElement","type","onload","onerror","event","request","target","src","err","Error","code","parentNode","removeChild","appendChild","then","installedChunkData","promise","onScriptComplete","script","charset","timeout","nc","setAttribute","jsonpScriptSrc","error","clearTimeout","chunk","errorType","realSrc","message","name","undefined","setTimeout","head","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","console","jsonpArray","window","oldJsonpFunction","slice","s","VirtualElementTypesEnum","Fragment","renderingInstance","isEmptyElement","$element","Empty","isTextElement","Text","isTagElement","Tag","isComponentElement","Component","isRealElement","source","props","children","flatten","parsedChildren","componentInstance","isMounted","hooks","state","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","map","buildChildElement","buildTagElement","isEmptyPlaceholder","child","String","DEBUG_components","renderComponent","newRenderedValue","DEBUG_startAt","DEBUG","componentName","renderCount","renderTimes","DEBUG_MORE","log","performance","now","renderTime","warn","Math","round","handleError","renderedValue","newChild","hasElementChanged","$old","$new","unmountTree","forEach","hook","current","cleanup","effect","dependencies","nextValue","setter","forceUpdate","onUpdate","helpGc","unmountComponent","removeAllDelegatedListeners","mountComponent","forceUpdateComponent","currentElement","getTarget","setTarget","useState","initial","newValue","prepareForFrame","throttleWithPrimaryRaf","prepareComponentForFrame","throttleWithRaf","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","exec","some","dependency","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","withDebug","propsRef","renderedRef","getUnequalProps","join","addEventListener","orderBy","values","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","APP_VERSION","process","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","isBigScreen","Set","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","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","MEMOJI_STICKER_ID","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_TEMPLATE","RE_TME_LINK","RE_TME_INVITE_LINK","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","LANG_PACKS","TIPS_USERNAME","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacksThrottled","cb","newGlobal","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","TeactNContainer","id","generateIdFor","useForceUpdate","delete","set","buildCollectionByKey","collection","reduce","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","filter","has","orderKey","sort","a","b","Array","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","from","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","lang","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","groupedId","isGif","emoji","title","performer","fileName","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","entities","link","find","entity","ApiMessageEntityTypes","TextUrl","url","Url","offset","substring","domain","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","action","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","sender","getUserFullName","getChatTitle","getSendingState","sendingState","isHistoryClearMessage","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","base","hasMessageLocalBlobUrl","canMessagePlayVideoInline","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageMediaFilename","date","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","reverseOrder","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","selectUser","global","userId","users","byId","selectNotifySettings","settings","selectNotifyExceptions","notifyExceptions","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","user","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","fullInfo","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","includes","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","selectIsChatMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","cleanedEmoji","replace","selectEmojiKeywords","language","emojiKeywords","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","selectThreadOriginChat","threadInfo","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","currentMessageList","selectIsViewportNewest","viewportIds","lastMessageId","selectChatMessage","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","focusedMessage","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","fromChatId","senderUserId","selectAllowedMessageActions","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","getHasAdminRight","canPin","canUnpin","pinnedMessageIds","canDelete","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","Infinity","selectFirstUnreadId","outlyingIds","lastReadId","isNotJoined","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","isCommonBoxChat","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","fromMessageId","selectMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","isChatGroup","userOrChat","contactList","userIds","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","chatThreadKey","currentSearch","localTextSearch","byChatThreadKey","isActive","selectCurrentMediaSearchPeerId","localMediaSearch","currentProfileUserId","selectedId","selectCurrentMediaSearch","peerId","selectManagement","management","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_MOBILE_SCREEN","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","UserInfo","ChatInfo","selectIsRightColumnShown","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_TOUCH_ENV","matchMedia","matches","innerWidth","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","parts","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","args","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","waiting","onIdle","requestIdleCallback","pause","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","isPrimary","requestAnimationFrame","currentCallbacks","currentPrimaryCallbacks","worker","requestStates","requestStatesByCallback","initApi","sessionData","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","Bundles","LOAD_PROMISES","MEMORY_CACHE","async","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","cacheApi","caches","Type","fetch","cacheName","Request","cache","open","Blob","blob","substr","headers","Json","json","save","cacheData","JSON","stringify","Response","put","clear","File","constructor","fileBits","options","rest","super","this","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","canvas","videoWidth","videoHeight","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","EXTRA_PACK_PATHS","en","enExtraJson","es","esExtraJson","it","itExtraJson","pl","plExtraJson","ru","ruExtraJson","PLURAL_OPTIONS","PLURAL_RULES","ar","ca","de","fa","fr","ko","nl","pt_BR","tr","uk","uz","langPack","runCallbacks","createCallbackManager","currentLangCode","getTranslation","format","cached","langString","template","amount","optionIndex","getPluralOption","trim","processTemplate","formatInteger","setLanguage","langCode","newLangPack","remote","sourceLangPacks","fetchFromCacheOrRemote","pairs","extraLangPack","languages","langInfo","isRtl","rtl","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","noLoad","autoUpdate","formatsCache","defaultPhoneNumberFormat","parsed","str","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","repeat","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","startsWith","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","DC_IDS","storeSession","mainDcId","hashes","localStorage","setItem","dcID","dcId","clearStoredSession","removeItem","loadStoredSession","userAuthJson","getItem","userAuth","parse","hash","importLegacySession","sessionId","sessionJson","idb","clearLegacySessions","idbKeys","k","importTestSession","env","TEST_SESSION","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","Spinner","buildClassName","handleErrorEvent","startedAt","isReloading","preventDefault","ErrorEvent","reason","alert","location","reload","APP_ENV","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","renderText","part","filters","params","textParts","divEl","innerText","innerHTML","escapeHtml","EMOJI_REGEX","lastIndex","replaceEmojis","addLineBreaks","highlight","lowerCaseText","queryPosition","nextSymbol","newParts","links","RE_MENTION","nextLink","endsWith","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","entityResult","currentProps","newProps","currentKeys","currentKeysLength","prop","useOnChange","langProvider","setTrigger","trigger","Link","onClick","handleClick","dir","store","random","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","requestPermission","unsubscribeFromPush","dispatch","deviceToken","unsubscribe","deleteDeviceToken","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","subscribe","replaceSettings","loadNotificationSettings","subscribedAt","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","showNewMessageNotification","isActiveChat","hasFocus","hasPrivateChatsNotifications","hasGroupNotifications","hasBroadcastNotifications","checkIfShouldNotify","body","messageSender","messageAction","actionTargetMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","actionTargetUser","privateChatUserId","privateChatUser","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","getNotificationContent","controller","icon","badge","toString","vibrate","notification","onclick","close","focusMessage","focus","notifyClientReady","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","getTime","floor","today","setHours","formatTime","yesterday","setDate","getDate","formatFullDate","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","getChatSlowModeOptions","slowMode","getChatOrder","max","joinDate","isChatArchived","notifySettings","isMuted","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","isChat","chatOrUser","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","Button","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","handleMouseDown","aria-label","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeEventListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","setValue","isOpen","onCloseTransitionEnd","noOpenTransition","noCloseTransition","isClosed","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","isClosing","shouldRender","transitionClassNames","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChats","updatedById","addChats","addedById","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","canDeleteCurrentThread","currentThreadId","originalPost","deleteChatScheduledMessages","scheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","updateScheduledMessages","updateFocusedMessage","noHighlight","updateFocusDirection","direction","enterMessageSelectMode","toggleMessageSelection","childMessageIds","withShift","oldSelectedMessages","newMessageIds","newSelectedMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateUser","userUpdate","contactUserIds","updatedUser","updateUsers","addUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","getComplexKey","updateGlobalSearch","searchStatePartial","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","newState","fetchingStatus","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","newSettings","replaceThemeSettings","theme","themes","addNotifyException","notifyException","updateNotifySettings","peerType","isSilent","shouldShowPreviews","hasPrivateChatsMessagePreview","hasGroupMessagePreview","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","usePrevious","next","shouldSkipUndefined","trimText","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","createStore","customStore","del","eachCursor","openCursor","continue","items","MenuItem","destructive","useLang","handleKeyDown","keyCode","data-char","origin","role","onKeyDown","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","webpToPng","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","onmessage","handleLibWebpMessage","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","labelText","htmlFor","subLabel","checked","blocking","onCheck","handleChange","captureEscKeyListener","captureKeyboardListener","onEsc","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","prevDeps","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","getFromMemory","cancelProgress","mediaData","fullSize","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","IS_LANDSCAPE","isLandscape","windowSize","updateSizes","handleResize","vh","setProperty","utf16","len","RangeError","adapt","delta","numpoints","firsttime","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","ensureProtocol","getDomain","decodedHref","decodeURI","convertPunycode","toggleSafeLinkModal","openTelegramLink","isNotSafe","ctrlKey","altKey","shiftKey","metaKey","classNames","getFileSizeString","bytes","ONE_GIGABYTE","ONE_MEGABYTE","getDocumentExtension","getFileExtension","getColorFromExtension","extension","STRIPE_ERRORS","missing_payment_information","field","fieldError","invalid_number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","SHIPPING_ERRORS","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","getShippingError","errors","cur","currentInstance","animateSingle","tick","instance","isCancelled","animate","DropdownMenu","dropdownRef","setIsOpen","menu","focusedElement","activeElement","elementChildren","onTrigger","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","querySelectorAll","newIndex","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","updateComponent","setupComponentUpdateListener","initComponent","node","createNode","childNodes","insertBefore","replaceChild","areComponents","nextSibling","newKeys","removeAttribute","addAttribute","oldValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","createDocumentFragment","renderChildren","$firstChild","createTextNode","$child","$fragmentChild","cssText","render","headId","$head","openUserInfo","handleMessageClick","openChat","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","renderChatContent","renderUserContent","renderOriginContent","showQuotes","messageText","renderMessageContent","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","MESSAGE_DELETED","openChatByUsername","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","transition","updateAppBadge","setAppBadge","contains","animationLevel","messageTextSize","switchTheme","uiReadyState","authPhoneNumber","authRememberMe","authError","apiUpdate","authIsLoading","password","file","authIsLoadingQrCode","reset","langCachePrefix","langCacheVersion","init","connectionState","authNearestCountry","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","arguments","apply","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","binding","cwd","chdir","umask","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","saveSession","onUpdateSession","currentUser","sessionUserAuth","updateSessionUserId","onUpdateCurrentUser","showError","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","activeChatFolder","recentEmojis","added","recent","featured","saved","topPeers","audioPlayer","notifications","activeSessions","messageSendKeyCombo","shouldSuggestStickers","light","isBlurred","patternColor","dark","privacy","updateCacheThrottled","isAllowed","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","loadCache","initialState","time","timeEnd","readCache","idsToSave","cid","chatIdsToSave","mainThread","history","replaceState","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","mediaLoader","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","data-country-id","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","gotToAuthQrCode","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","setSelectionRange","handlePhoneNumberChange","selectionStart","selectionEnd","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","AuthQrCode","AppInactive","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GAKAK,EAAI,EAAGC,EAAW,GACpCD,EAAIF,EAASI,OAAQF,IACzBH,EAAUC,EAASE,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBV,IAAYU,EAAgBV,IACpFI,EAASO,KAAKD,EAAgBV,GAAS,IAExCU,EAAgBV,GAAW,EAE5B,IAAID,KAAYG,EACZI,OAAOC,UAAUC,eAAeC,KAAKP,EAAaH,KACpDa,EAAQb,GAAYG,EAAYH,IAKlC,IAFGc,GAAqBA,EAAoBf,GAEtCM,EAASC,QACdD,EAASU,OAATV,GAOF,IAAIW,EAAmB,GAGnBC,EAAqB,CACxBC,EAAG,GAMAP,EAAkB,CACrBO,EAAG,GAWJ,SAASC,EAAoBnB,GAG5B,GAAGgB,EAAiBhB,GACnB,OAAOgB,EAAiBhB,GAAUoB,QAGnC,IAAIC,EAASL,EAAiBhB,GAAY,CACzCI,EAAGJ,EACHsB,GAAG,EACHF,QAAS,IAUV,OANAP,EAAQb,GAAUU,KAAKW,EAAOD,QAAS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nB7hC,OAAO6+B,SAASC,WAcV,iBCuCV,SAASinC,KACP,OACE,kBAAC,EAAD,CAAUve,KAAK,OAAOhoD,IAAI,QACxB,kBAAC,GAAD,OAKSgP,mBACZkM,GAAuBnL,YAAKmL,EAAQ,CAAC,cACtC,CAAC1N,EAAWC,IAA2BsC,YAAKtC,EAAS,CAAC,eAFzCuB,CAhD6B,EAAGkuD,YAAWsJ,iBACxD,MAAOC,EAAYC,GAAgBhE,aAAQ,GAc3C,GAZAr8D,YAAU,KACRylD,cfTFj8C,EeU6B,KACzB22D,IACApqE,SAAS8X,MAAS,GAAEzM,OAAaC,MAEjCg/D,MAED,CAACF,EAAYE,IAIZD,EACF,OAAO,kBAAC,GAAD,MAGT,GAAIvJ,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,kBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAOqJ,KAMb,OAFmB9pC,aAAaQ,QAAQj1B,OAAqBy0B,aAAaQ,QAAQh1B,KAE9Ds+D,KAAe,kBAAC,GAAD,Q,OC7CjCpjE,KAEF7C,QAAQkD,IAAI,YAGd8K,cAAcksD,OAEVr3D,KAEF7C,QAAQkD,IAAI,4BAGdmjE,IAASvQ,OACP,kBAAC,GAAD,MACAh6D,SAASynE,eAAe,SAGtB1gE,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAASkL,iBAAiB,WAAY,KAEpChH,QAAQkD,IAAI,eAAgB6K","file":"main.7c95ea3f46a28615bf1a.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t};\n\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded CSS chunks\n \tvar installedCssChunks = {\n \t\t2: 0\n \t}\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"c42f873e780469e6d6db\",\"1\":\"fb539fa72ec126e2a2cc\",\"3\":\"048f19f68ad10b65610e\",\"4\":\"92917cccdb4999ea7d20\",\"5\":\"c1959eb66d878675dbb0\",\"6\":\"63a48d34eed627347217\",\"7\":\"5f1b33007c02b15c2a4e\",\"8\":\"75df16efec295d79dd82\",\"9\":\"600e8c07ee8b577efa8f\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// mini-css-extract-plugin CSS loading\n \t\tvar cssChunks = {\"0\":1,\"3\":1,\"4\":1,\"5\":1,\"6\":1};\n \t\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n \t\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n \t\t\tpromises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {\n \t\t\t\tvar href = \"\" + ({}[chunkId]||chunkId) + \".\" + {\"0\":\"c42f873e780469e6d6db\",\"1\":\"fb539fa72ec126e2a2cc\",\"3\":\"048f19f68ad10b65610e\",\"4\":\"92917cccdb4999ea7d20\",\"5\":\"c1959eb66d878675dbb0\",\"6\":\"63a48d34eed627347217\",\"7\":\"5f1b33007c02b15c2a4e\",\"8\":\"75df16efec295d79dd82\",\"9\":\"600e8c07ee8b577efa8f\"}[chunkId] + \".css\";\n \t\t\t\tvar fullhref = __webpack_require__.p + href;\n \t\t\t\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n \t\t\t\tfor(var i = 0; i < existingLinkTags.length; i++) {\n \t\t\t\t\tvar tag = existingLinkTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n \t\t\t\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return resolve();\n \t\t\t\t}\n \t\t\t\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n \t\t\t\tfor(var i = 0; i < existingStyleTags.length; i++) {\n \t\t\t\t\tvar tag = existingStyleTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\");\n \t\t\t\t\tif(dataHref === href || dataHref === fullhref) return resolve();\n \t\t\t\t}\n \t\t\t\tvar linkTag = document.createElement(\"link\");\n \t\t\t\tlinkTag.rel = \"stylesheet\";\n \t\t\t\tlinkTag.type = \"text/css\";\n \t\t\t\tlinkTag.onload = resolve;\n \t\t\t\tlinkTag.onerror = function(event) {\n \t\t\t\t\tvar request = event && event.target && event.target.src || fullhref;\n \t\t\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + request + \")\");\n \t\t\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n \t\t\t\t\terr.request = request;\n \t\t\t\t\tdelete installedCssChunks[chunkId]\n \t\t\t\t\tlinkTag.parentNode.removeChild(linkTag)\n \t\t\t\t\treject(err);\n \t\t\t\t};\n \t\t\t\tlinkTag.href = fullhref;\n\n \t\t\t\tvar head = document.getElementsByTagName(\"head\")[0];\n \t\t\t\thead.appendChild(linkTag);\n \t\t\t}).then(function() {\n \t\t\t\tinstalledCssChunks[chunkId] = 0;\n \t\t\t}));\n \t\t}\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\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\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 102);\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, onTickEnd, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\nexport type FC_withDebug = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We force cleaning as many objects as possible. Not sure this is needed at all.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n // 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 })(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 effect: () => Function | void,\n dependencies?: any[],\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[]): 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 current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual, withDebug = false) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && withDebug) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name}: Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 500;\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;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\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;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\nexport function setGlobal(newGlobal?: GlobalState) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n runCallbacksThrottled();\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload) => {\n onDispatch(name, payload);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${text ? text.text : lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji} ${lang('AttachSticker')} `;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n return `${noEmoji ? '' : '🎧 '}${caption || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${text ? text.text : lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && 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 && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return sender.id > 0 ? 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","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\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\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\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 && 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 getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\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\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\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\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\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 default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\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 getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\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 getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | 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): IDimensions | 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): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\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,\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 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;\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: number): 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: number) {\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 (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\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: number) {\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: number, 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: number): '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: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && !selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\nimport { LangCode, EmojiKeywords } from '../../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 selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectEmojiKeywords(global: GlobalState, language: LangCode): EmojiKeywords | undefined {\n return global.emojiKeywords[language] && global.emojiKeywords[language] !== undefined\n ? global.emojiKeywords[language] as EmojiKeywords\n : undefined;\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\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} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists && 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: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: number,\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: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, 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: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, 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: number, 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: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, 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: number, 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: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, 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: number) {\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 senderId > 0 ? 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);\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 = isChatPrivate(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 isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const isMessageEditable = (\n (isChatWithSelf || Date.now() - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !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 = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\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 const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\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 selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, 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: number, 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 || 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 if (outlyingIds) {\n const found = !lastReadId ? outlyingIds[0] : outlyingIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = !lastReadId ? listedIds[0] : listedIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\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 Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(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: number, 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: number, 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: number, 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: number,\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 selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\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 (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n} from '../config';\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: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\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 === 'Mac OS';\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);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\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);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nlet 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","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiOnProgress, ApiSessionData, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\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, sessionData?: ApiSessionData) {\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();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [sessionData],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","// 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(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\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 const request = new Request(key);\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 { 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 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","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\nimport { getGlobal } from '../lib/teact/teactn';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n}\n\nconst EXTRA_PACK_PATHS: Record = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\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;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\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 cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n};\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages } = getGlobal().settings.byKey;\n const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined;\n getTranslation.isRtl = Boolean(langInfo && langInfo.rtl);\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\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\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","// 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 React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n

\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\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 '../../../util/cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: number) {\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 Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\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 const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) return undefined;\n\n let mainDcId: number | undefined;\n const keys: Record = {};\n const hashes: Record = {};\n\n try {\n const userAuth = JSON.parse(userAuthJson);\n mainDcId = Number(userAuth.dcID);\n } catch (err) {\n // Do nothing.\n }\n\n if (!mainDcId) return undefined;\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;\n storeSession(sessionData);\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 {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\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';\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};\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 interface ISettings extends NotifySettings, Record {\n theme: ThemeKey;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\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 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 FoldersIncludedChats,\n FoldersExcludedChats,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\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 type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record;\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","import { DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY } 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;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache and refresh the page\n if (Date.now() - startedAt <= STARTUP_TIMEOUT && localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\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 = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? {emoji}\n : (\n \n ),\n );\n }\n if (type === 'html') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? emoji\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n : `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/ig;\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = [...(part.match(RE_LINK) || []), ...(part.match(RE_MENTION) || [])];\n if (!links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","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.filter((prop) => currentProps[prop] !== newProps[prop]);\n}\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { callApi } from '../api/gramjs';\nimport { ApiChat, ApiMessage } from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\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\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\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// Load notification settings from the api\nasync function loadNotificationSettings() {\n const [result] = await Promise.all([\n callApi('fetchNotificationSettings'),\n callApi('fetchNotificationExceptions'),\n ]);\n\n if (!result) return;\n setGlobal(replaceSettings(getGlobal(), result));\n}\n\nexport async function subscribe() {\n loadNotificationSettings();\n\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat, isActive: boolean) {\n const global = getGlobal();\n\n if (selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global)) || chat.isNotJoined) {\n return false;\n }\n\n // Dont show notification for active chat if client has focus\n if (isActive && document.hasFocus()) return false;\n\n switch (chat.type) {\n case 'chatTypePrivate':\n case 'chatTypeSecret':\n return Boolean(global.settings.byKey.hasPrivateChatsNotifications);\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return Boolean(global.settings.byKey.hasGroupNotifications);\n case 'chatTypeChannel':\n return Boolean(global.settings.byKey.hasBroadcastNotifications);\n }\n return false;\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\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 targetUserId: actionTargetUserId,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n const actionTargetUser = actionTargetUserId ? selectUser(global, actionTargetUserId) : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n let body: string;\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nexport function showNewMessageNotification({\n chat,\n message,\n isActiveChat,\n}: { chat: ApiChat; message: Partial; isActiveChat: boolean}) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n if (!checkIfShouldNotify(chat, isActiveChat)) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon: 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag: message.id.toString(),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date();\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 if (wasOnlineDate > today) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(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) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record,\n priorityIds?: number[],\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\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 ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { LangFn } from '../../hooks/useLang';\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\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 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 const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\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 && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && 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) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(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')) && (!isChatPrivate(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(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\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.lastMessage ? 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 return !(notifyExceptions && notifyExceptions[chat.id] && !notifyExceptions[chat.id].isMuted) && (\n chat.isMuted\n || (isChatPrivate(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && !chat.unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(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: number[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\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 += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than 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 priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n}) => {\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 );\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 e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {isLoading ? (\n
\n Please wait..\n \n
\n ) : children}\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement) {\n return (\n !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n hasOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(lang: LangFn, datetime: number | Date, isShort = false, noWeekdays = false) {\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 (isShort ? lowerFirst : upperFirst)(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 (isShort ? lowerFirst : upperFirst)(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 return isShort\n ? lowerFirst(lang(`Weekday.Short${weekDay}`))\n : upperFirst(lang(`Weekday.${weekDay}`));\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 (isShort ? lowerFirst : upperFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: 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 let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date) {\n return date.toLocaleString(\n 'en-US',\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_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 { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | 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: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && 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: number, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\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?: number[];\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","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } 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: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, 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: number, 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).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, 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: number, 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: number, 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 }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\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 && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\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\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\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\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && 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: number,\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, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && 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: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && 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: number,\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: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, 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: number, 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: number, newById: Record, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record; hash: number }>,\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?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\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: number,\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: number,\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","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\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: number,\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: number,\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 && 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: number,\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: number,\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: number,\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: number,\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 && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\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 addNotifyException(\n global: GlobalState, id: number, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\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: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: 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 description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { 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","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","function 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 request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }: Ripple) => (\n \n ))}\n
\n );\n};\n\nexport default memo(RippleEffect);\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\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, url: string): Promise {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() 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 worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n}) => {\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 { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","const RE_NOT_LETTER = /[^\\wа-яё]+/;\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","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';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\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 { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n\n useEffect(() => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n
\n );\n};\n\nexport default Menu;\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst 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: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\n\nexport function fetch(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\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 });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\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(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\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]!);\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 void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\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\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\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 = blob.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 prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","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 { 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_MOBILE_SCREEN } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_MOBILE_SCREEN && isLandscape();\n\nlet windowSize = updateSizes();\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if ((isMobileScreen() !== IS_MOBILE_SCREEN) || (IS_MOBILE_SCREEN && IS_LANDSCAPE !== isLandscape())) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n};\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 { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n toggleSafeLinkModal,\n openTelegramLink,\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_TME_INVITE_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {content}\n \n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSafeLinkModal', 'openTelegramLink',\n ]),\n)(SafeLink));\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\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","const STRIPE_ERRORS: Record> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingError(errors: Record) {\n return Object.values(errors).reduce((acc, cur) => {\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import 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 children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\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 };\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 };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n \n );\n};\n\nexport default DropdownMenu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","// 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\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\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 nativeToUnfified(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","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUser\n ? renderUserContent(targetUser, options.asPlain)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = `«${text}»`;\n }\n\n if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(lang, origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart): TextPart[] {\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 content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\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?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\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?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\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 isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\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.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\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","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","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"7c2292f972e10d28cc51.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel > 0);\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\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 }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\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 importTestSession,\n} from './sessions';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n } else {\n importTestSession();\n }\n\n void initApi(actions.apiUpdate, loadStoredSession());\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('gotToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionData } = payload;\n\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribe();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser,\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';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\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 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n subscribe();\n 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 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 setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n if (!getGlobal().authRememberMe) {\n return;\n }\n\n const { sessionData } = update;\n\n getDispatch().saveSession({ sessionData });\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: number) {\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","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\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 getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\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';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n} from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n },\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 featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n LEGACY_SESSION_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT, SESSION_USER_KEY,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n if (hasSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\n}\n\nfunction readCache(initialState: 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 // Pre-fill defaults in nested objects which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\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 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'emojiKeywords',\n 'push',\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 };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\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","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\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","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n
\n {children}\n {shouldRenderMask && (\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 } = global.settings.byKey;\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => 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}) => {\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(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, []);\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, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList.map((country: Country) => (\n \n \n {renderText(country.flag, ['hq_emoji'])}\n {country.name}\n {country.code}\n \n ))}\n {!filteredList.length && (\n \n No countries matched your filter.\n \n )}\n \n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\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;\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\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\n const fullNumber = country ? `${country.code} ${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 (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\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 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 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 parseFullNumber(value);\n }, [authError, clearAuthError, 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

Sign in to Telegram

\n

\n Please confirm your country and\n
enter your phone number.\n

\n
\n \n \n \n {canSubmit && (\n isAuthReady ? (\n \n ) : (\n \n )\n )}\n {isAuthReady && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'gotToAuthQrCode',\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","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 AuthQrCodeAsync: FC = () => {\n const AuthQrCode = useModuleLoader(Bundles.Auth, 'AuthQrCode');\n\n return AuthQrCode ? : ;\n};\n\nexport default memo(AuthQrCodeAsync);\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\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.async';\n\nimport './Auth.scss';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst Auth: FC = ({ authState, reset, initApi }) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n useEffect(() => {\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return ;\n case 'authorizationStateWaitPassword':\n return ;\n case 'authorizationStateWaitRegistration':\n return ;\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateWaitPhoneNumber':\n default:\n return ;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi']),\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","export default __webpack_public_path__ + \"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png\";","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n
\n
\n \"\"\n

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport {\n LEGACY_SESSION_KEY, INACTIVE_MARKER, SESSION_USER_KEY, PAGE_TITLE,\n} 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';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n\n return hasSession ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./src/lib/teact/teact.ts","webpack:///./src/config.ts","webpack:///./src/lib/teact/teactn.tsx","webpack:///./src/util/iteratees.ts","webpack:///./src/modules/helpers/messages.ts","webpack:///./src/modules/helpers/messageMedia.ts","webpack:///./src/modules/helpers/localSearch.ts","webpack:///./src/api/types/index.ts","webpack:///./src/modules/selectors/users.ts","webpack:///./src/modules/selectors/settings.ts","webpack:///./src/modules/selectors/chats.ts","webpack:///./src/modules/selectors/symbols.ts","webpack:///./src/modules/selectors/messages.ts","webpack:///./src/modules/selectors/localSearch.ts","webpack:///./src/modules/selectors/management.ts","webpack:///./src/modules/selectors/ui.ts","webpack:///./src/modules/selectors/globalSearch.ts","webpack:///./src/modules/selectors/payments.ts","webpack:///./src/util/environment.ts","webpack:///./src/util/buildClassName.ts","webpack:///./src/util/schedulers.ts","webpack:///./src/api/gramjs/worker/provider.ts","webpack:///./src/util/moduleLoader.ts","webpack:///./src/util/cacheApi.ts","webpack:///./src/util/files.ts","webpack:///./src/assets/lang/en-extra.json","webpack:///./src/assets/lang/es-extra.json","webpack:///./src/assets/lang/it-extra.json","webpack:///./src/assets/lang/pl-extra.json","webpack:///./src/assets/lang/ru-extra.json","webpack:///./src/util/langProvider.ts","webpack:///./src/util/callbacks.ts","webpack:///./src/lib/twemojiRegex.js","webpack:///./src/components/ui/Loading.tsx","webpack:///./src/hooks/useModuleLoader.ts","webpack:///./src/util/countries.ts","webpack:///./src/util/phoneNumber.ts","webpack:///./src/modules/actions/api/sessions.ts","webpack:///./src/types/index.ts","webpack:///./src/components/ui/Spinner.tsx","webpack:///./src/util/handleError.ts","webpack:///./src/components/common/helpers/renderText.tsx","webpack:///./src/util/arePropsShallowEqual.ts","webpack:///./src/hooks/useLang.ts","webpack:///./src/hooks/useForceUpdate.ts","webpack:///./src/components/ui/Link.tsx","webpack:///./src/util/generateIdFor.ts","webpack:///./src/util/notifications.ts","webpack:///./src/modules/helpers/users.ts","webpack:///./src/modules/helpers/chats.ts","webpack:///./src/components/ui/Button.tsx","webpack:///./src/lib/teact/dom-events.ts","webpack:///./src/hooks/useFlag.ts","webpack:///./src/hooks/useShowTransition.ts","webpack:///./src/util/dateFormat.ts","webpack:///./src/modules/reducers/chats.ts","webpack:///./src/modules/reducers/messages.ts","webpack:///./src/modules/reducers/symbols.ts","webpack:///./src/modules/reducers/users.ts","webpack:///./src/modules/reducers/globalSearch.ts","webpack:///./src/modules/reducers/localSearch.ts","webpack:///./src/modules/reducers/management.ts","webpack:///./src/modules/reducers/settings.ts","webpack:///./src/modules/reducers/twoFaSettings.ts","webpack:///./src/modules/reducers/payments.ts","webpack:///./src/hooks/usePrevious.ts","webpack:///./src/util/trimText.ts","webpack:///./node_modules/idb-keyval/dist/esm/index.js","webpack:///./src/components/ui/MenuItem.tsx","webpack:///./src/components/ui/RippleEffect.tsx","webpack:///./src/util/webpToPng.ts","webpack:///./src/components/ui/InputText.tsx","webpack:///./src/components/ui/Checkbox.tsx","webpack:///./src/util/captureEscKeyListener.ts","webpack:///./src/hooks/useHeavyAnimationCheck.ts","webpack:///./src/util/textFormat.ts","webpack:///./src/util/memo.ts","webpack:///./src/hooks/useOnChange.ts","webpack:///./src/util/searchWords.ts","webpack:///./src/components/ui/Menu.tsx","webpack:///./src/util/oggToWav.ts","webpack:///./src/util/mediaLoader.ts","webpack:///./src/util/captureKeyboardListeners.ts","webpack:///./src/util/windowSize.ts","webpack:///./src/lib/punycode.js","webpack:///./src/components/common/SafeLink.tsx","webpack:///./src/hooks/useEffectWithPrevDeps.ts","webpack:///./src/components/common/helpers/documentInfo.ts","webpack:///./src/modules/helpers/payments.ts","webpack:///./src/util/animation.ts","webpack:///./src/components/ui/DropdownMenu.tsx","webpack:///./src/hooks/useKeyboardListNavigation.ts","webpack:///./src/components/common/helpers/parseEmojiOnlyString.ts","webpack:///./src/util/emoji.ts","webpack:///./src/lib/teact/teact-dom.ts","webpack:///./src/components/common/UserLink.tsx","webpack:///./src/components/common/MessageLink.tsx","webpack:///./src/components/common/ChatLink.tsx","webpack:///./src/components/common/helpers/renderActionMessageText.tsx","webpack:///./src/api/types/messages.ts","webpack:///./src/api/types/media.ts","webpack:///./src/components/middle/message/MentionLink.tsx","webpack:///./src/util/switchTheme.ts","webpack:///./src/util/appBadge.ts","webpack:///./src/hooks/useVirtualBackdrop.ts","webpack:///./src/api/gramjs/worker/worker.ts","webpack:///./node_modules/opus-recorder/dist/decoderWorker.min.js","webpack:///./node_modules/opus-recorder/dist/waveWorker.min.js","webpack:///./src/lib/webp/webp_wasm.worker.js","webpack:///./src/modules/actions/ui/initial.ts","webpack:///./src/modules/actions/api/initial.ts","webpack:///./node_modules/process/browser.js","webpack:///./src/modules/actions/apiUpdaters/initial.ts","webpack:///./src/serviceWorker.ts","webpack:///./src/util/setupServiceWorker.ts","webpack:///./src/global/initial.ts","webpack:///./src/global/cache.ts","webpack:///./src/global/index.ts","webpack:///./src/util/activeTabMonitor.ts","webpack:///./src/util/fonts.ts","webpack:///./src/assets/telegram-logo.svg","webpack:///./src/assets/monkey.svg","webpack:///./src/components/common/UiLoader.tsx","webpack:///./src/components/auth/CountryCodeInput.tsx","webpack:///./src/components/auth/AuthPhoneNumber.tsx","webpack:///./src/components/auth/AuthCode.async.tsx","webpack:///./src/components/auth/AuthPassword.async.tsx","webpack:///./src/components/auth/AuthRegister.async.tsx","webpack:///./src/components/auth/AuthQrCode.async.tsx","webpack:///./src/components/auth/Auth.tsx","webpack:///./src/components/main/Main.async.tsx","webpack:///./src/assets/app-inactive.png","webpack:///./src/components/main/AppInactive.tsx","webpack:///./src/App.tsx","webpack:///./src/index.tsx"],"names":["webpackJsonpCallback","data","moduleId","chunkId","chunkIds","moreModules","i","resolves","length","Object","prototype","hasOwnProperty","call","installedChunks","push","modules","parentJsonpFunction","shift","installedModules","installedCssChunks","2","__webpack_require__","exports","module","l","e","promises","Promise","resolve","reject","href","fullhref","p","existingLinkTags","document","getElementsByTagName","dataHref","tag","getAttribute","rel","existingStyleTags","linkTag","createElement","type","onload","onerror","event","request","target","src","err","Error","code","parentNode","removeChild","appendChild","then","installedChunkData","promise","onScriptComplete","script","charset","timeout","nc","setAttribute","jsonpScriptSrc","error","clearTimeout","chunk","errorType","realSrc","message","name","undefined","setTimeout","head","all","m","c","d","getter","o","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","oe","console","jsonpArray","window","oldJsonpFunction","slice","s","VirtualElementTypesEnum","Fragment","renderingInstance","isEmptyElement","$element","Empty","isTextElement","Text","isTagElement","Tag","isComponentElement","Component","isRealElement","source","props","children","flatten","parsedChildren","componentInstance","isMounted","hooks","state","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","map","buildChildElement","buildTagElement","isEmptyPlaceholder","child","String","DEBUG_components","renderComponent","newRenderedValue","DEBUG_startAt","DEBUG","componentName","renderCount","renderTimes","DEBUG_MORE","log","performance","now","renderTime","warn","Math","round","handleError","renderedValue","newChild","hasElementChanged","$old","$new","unmountTree","forEach","hook","current","cleanup","effect","dependencies","nextValue","setter","forceUpdate","onUpdate","helpGc","unmountComponent","removeAllDelegatedListeners","mountComponent","forceUpdateComponent","currentElement","getTarget","setTarget","useState","initial","newValue","prepareForFrame","throttleWithPrimaryRaf","prepareComponentForFrame","throttleWithRaf","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","exec","some","dependency","useEffect","fastRaf","useLayoutEffect","onTickEnd","useMemo","resolver","useCallback","newCallback","useRef","memo","areEqual","arePropsShallowEqual","withDebug","propsRef","renderedRef","getUnequalProps","join","addEventListener","orderBy","values","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","APP_VERSION","process","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","isBigScreen","Set","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_ID","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","ANIMATION_END_DELAY","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","MEMOJI_STICKER_ID","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","CONTENT_TYPES_FOR_QUICK_UPLOAD","RE_LINK_TEMPLATE","RE_TME_LINK","RE_TME_INVITE_LINK","SERVICE_NOTIFICATIONS_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","LANG_PACKS","TIPS_USERNAME","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","React","currentGlobal","reducers","callbacks","container","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","setGlobal","actions","Number","isNaN","DEBUG_componentName","keys","areMappedPropsChanged","DEBUG_updates","updateTime","Map","runCallbacksThrottled","cb","newGlobal","getGlobal","getDispatch","addReducer","reducer","payload","onDispatch","addCallback","removeCallback","index","indexOf","splice","withGlobal","TeactNContainer","id","generateIdFor","useForceUpdate","delete","set","buildCollectionByKey","collection","reduce","byKey","member","mapValues","callback","newByKey","pick","result","pickTruthy","omit","stringKeys","filter","has","orderKey","sort","a","b","Array","isArray","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","concat","unique","from","compact","Boolean","areSortedArraysEqual","array1","array2","every","item","areSortedArraysIntersecting","findIntersectionWithSet","split","chunkSize","cloneDeep","acc","findLast","predicate","RE_LINK","RegExp","getMessageKey","chatId","parseMessageKey","match","messageId","getMessageOriginalId","previousLocalId","getMessageSummaryText","lang","noEmoji","text","photo","video","audio","voice","sticker","contact","poll","invoice","content","groupedId","isGif","emoji","title","performer","fileName","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","entities","link","find","entity","ApiMessageEntityTypes","TextUrl","url","Url","offset","substring","domain","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","action","isServiceNotificationMessage","isMessageLocal","isAnonymousOwnMessage","senderId","getSenderTitle","sender","getUserFullName","getChatTitle","getSendingState","sendingState","isHistoryClearMessage","getMessageContent","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageMediaThumbDataUri","thumbnail","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","base","hasMessageLocalBlobUrl","canMessagePlayVideoInline","getVideoOrAudioBaseHash","getDocumentHasPreview","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","size","mimeType","getMessageMediaFormat","isAnimated","ApiMediaFormat","Lottie","Progressive","IS_OPUS_SUPPORTED","BlobUrl","getMessageMediaFilename","date","blobUrl","previewBlobUrl","getChatMediaMessageIds","messages","listedIds","reverseOrder","ids","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","progress","isDownloadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","duration","buildChatThreadKey","threadId","selectUser","global","userId","users","byId","selectNotifySettings","settings","selectNotifyExceptions","notifyExceptions","selectChat","chats","selectChatUser","chat","getPrivateChatUserId","selectIsChatWithSelf","currentUserId","selectIsChatWithBot","user","isUserBot","selectSupportChat","isSupport","selectChatOnlineCount","isChatPrivate","isChatChannel","fullInfo","members","onlineCount","isUserOnline","selectChatBot","selectIsChatBotNotStarted","bot","lastMessage","messageInfo","byChatId","threadsById","MAIN_THREAD_ID","selectAreActiveChatsLoaded","listIds","active","selectIsChatListed","targetList","includes","list","selectChatListType","folderId","selectChatFolder","chatFolders","selectIsChatPinned","archived","orderedPinnedIds","chatFoldersById","pinnedChatIds","selectChatByUsername","username","usernameLowered","toLowerCase","selectCountNotMutedUnread","activeChatIds","unreadCount","selectIsChatMuted","selectCurrentStickerSearch","stickers","search","selectCurrentGifSearch","gifs","selectStickerSet","setsById","selectStickersForEmoji","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","animatedEmojis","cleanedEmoji","replace","selectEmojiKeywords","language","emojiKeywords","selectCurrentMessageList","messageLists","selectCurrentChat","selectChatMessages","selectScheduledMessages","scheduledMessages","selectThreadParam","thread","selectListedIds","selectOutlyingIds","selectCurrentMessageIds","messageListType","selectViewportIds","selectPinnedIds","selectScheduledIds","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectThreadInfo","selectFirstMessageId","selectThreadOriginChat","threadInfo","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","currentMessageList","selectIsViewportNewest","viewportIds","lastMessageId","selectChatMessage","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","focusedMessage","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","fromChatId","senderUserId","selectAllowedMessageActions","isRestricted","isPrivate","isChatWithSelf","isBasicGroup","isChatBasicGroup","isSuperGroup","isChatSuperGroup","isChannel","isServiceNotification","isOwn","isAction","isMessageEditable","Date","viaBotId","canReply","getCanPostInChat","hasPinPermission","isCreator","isUserRightBanned","getHasAdminRight","canPin","canUnpin","pinnedMessageIds","canDelete","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","noOptions","ability","selectCanDeleteSelectedMessages","selectedMessageIds","selectedMessages","messageActions","selectUploadProgress","fileTransfer","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","min","Infinity","selectFirstUnreadId","outlyingIds","lastReadId","isNotJoined","found","isFromScheduled","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","isCommonBoxChat","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","fromMessageId","selectMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectShouldAutoLoadMedia","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","isChatGroup","userOrChat","contactList","userIds","selectIsUserOrChatContact","selectShouldAutoPlayMedia","shouldAutoPlayVideos","shouldAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectCurrentTextSearch","chatThreadKey","currentSearch","localTextSearch","byChatThreadKey","isActive","selectCurrentMediaSearchPeerId","localMediaSearch","currentProfileUserId","selectedId","selectCurrentMediaSearch","peerId","selectManagement","management","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_MOBILE_SCREEN","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","query","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","PollResults","Search","Management","StickerSearch","GifSearch","UserInfo","ChatInfo","selectIsRightColumnShown","selectCurrentGlobalSearchQuery","globalSearch","selectPaymentMessageId","payment","selectPaymentRequestId","formId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","stripeCredentials","PLATFORM_ENV","userAgent","platform","navigator","os","test","getPlatform","IS_MAC_OS","IS_IOS","IS_ANDROID","IS_TOUCH_ENV","matchMedia","matches","innerWidth","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_EMOJI_SUPPORTED","documentElement","style","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","isWebpSupportedCache","isWebpSupported","webp","Image","handleLoadOrError","hasWebp","parts","debounce","fn","ms","shouldRunFirst","shouldRunLast","waitingTimeout","args","self","throttle","interval","isPending","_args","setInterval","clearInterval","throttleWith","fastPrimaryRaf","waiting","onIdle","requestIdleCallback","pause","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","isPrimary","requestAnimationFrame","currentCallbacks","currentPrimaryCallbacks","worker","requestStates","requestStatesByCallback","initApi","sessionData","Worker","update","requestState","response","callbackArgs","subscribeToWorker","makeRequest","callApi","fnName","cancelApiProgress","progressCallback","isCanceled","postMessage","assign","pop","catch","finally","Bundles","LOAD_PROMISES","MEMORY_CACHE","async","loadModule","bundleName","moduleName","Auth","Main","Extra","handleBundleLoad","bundle","getModuleFromMemory","listeners","addLoadListener","listener","cacheApi","caches","Type","fetch","cacheName","Request","cache","open","Blob","blob","substr","headers","Json","json","save","cacheData","JSON","stringify","Response","put","clear","File","constructor","fileBits","options","rest","super","this","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","charCodeAt","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","race","onseeked","canvas","videoWidth","videoHeight","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","EXTRA_PACK_PATHS","en","enExtraJson","es","esExtraJson","it","itExtraJson","pl","plExtraJson","ru","ruExtraJson","PLURAL_OPTIONS","PLURAL_RULES","ar","ca","de","fa","fr","ko","nl","pt_BR","tr","uk","uz","langPack","runCallbacks","createCallbackManager","currentLangCode","getTranslation","format","cached","langString","template","amount","optionIndex","getPluralOption","trim","processTemplate","formatInteger","setLanguage","langCode","newLangPack","remote","sourceLangPacks","fetchFromCacheOrRemote","pairs","extraLangPack","languages","langInfo","isRtl","rtl","vs16RegExp","zeroWidthJoiner","fromCharCode","removeVS16s","rawEmoji","color","className","withBackground","noLoad","autoUpdate","formatsCache","defaultPhoneNumberFormat","parsed","str","flag","phoneFormat","formatValue","phoneNumberFormat","phoneNumberGroups","count","repeat","getPhoneNumberFormat","getCountryById","countryList","getCountryFromPhoneNumber","input","phoneNumber","startsWith","possibleCountries","country","formatPhoneNumber","_","p1","p2","p3","p4","p5","separator","output","formatPhoneNumberWithCode","numberWithPlus","DC_IDS","storeSession","mainDcId","hashes","localStorage","setItem","dcID","dcId","clearStoredSession","removeItem","loadStoredSession","userAuthJson","getItem","userAuth","parse","hash","importLegacySession","sessionId","sessionJson","idb","clearLegacySessions","idbKeys","k","importTestSession","env","TEST_SESSION","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","ChatCreationProgress","ProfileEditProgress","ManagementProgress","ProfileState","PaymentStep","UPLOADING_WALLPAPER_SLUG","ManagementScreens","Spinner","buildClassName","handleErrorEvent","startedAt","isReloading","preventDefault","ErrorEvent","reason","alert","location","reload","APP_ENV","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","renderText","part","filters","params","textParts","divEl","innerText","innerHTML","escapeHtml","EMOJI_REGEX","lastIndex","replaceEmojis","addLineBreaks","highlight","lowerCaseText","queryPosition","nextSymbol","newParts","links","RE_MENTION","nextLink","endsWith","addLinks","replaceSimpleMarkdown","emojis","emojiResult","nativeToUnfified","alt","line","trimmedLine","trimLeft","indentLength","entityResult","currentProps","newProps","currentKeys","currentKeysLength","prop","useOnChange","langProvider","setTrigger","trigger","Link","onClick","handleClick","dir","store","random","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","requestPermission","unsubscribeFromPush","dispatch","deviceToken","unsubscribe","deleteDeviceToken","serviceWorkerRegistration","serviceWorker","ready","pushManager","getSubscription","subscribe","replaceSettings","loadNotificationSettings","subscribedAt","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","showNewMessageNotification","isActiveChat","hasFocus","hasPrivateChatsNotifications","hasGroupNotifications","hasBroadcastNotifications","checkIfShouldNotify","body","messageSender","messageAction","actionTargetMessage","targetUserId","actionTargetUserId","targetChatId","actionTargetChatId","actionTargetUser","privateChatUserId","privateChatUser","actionOrigin","renderActionMessageText","asPlain","senderName","getMessageSenderName","getNotificationContent","controller","icon","badge","toString","vibrate","notification","onclick","close","focusMessage","focus","notifyClientReady","USER_COLOR_KEYS","getUserFirstOrLastName","firstName","lastName","isDeletedUser","getUserStatus","status","wasOnline","wasOnlineDate","diff","getTime","floor","today","setHours","formatTime","yesterday","setDate","getDate","formatFullDate","sortUserIds","usersById","priorityIds","expires","getUserColorKey","peer","abs","getChatTypeString","isSelf","getChatDescription","about","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","isChatAdmin","adminRights","currentUserBannedRights","defaultBannedRights","migratedTo","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","getChatSlowModeOptions","slowMode","getChatOrder","max","joinDate","isChatArchived","notifySettings","isMuted","getCanDeleteChat","prepareFolderListIds","chatsById","folder","chatIdsCache","excludedChatIds","includedChatIds","excludeArchived","excludeMuted","unreadMentionsCount","hasUnreadMark","excludeRead","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","isChat","chatOrUser","sortChatIds","chatIds","shouldPrioritizeVerified","priority","isVerified","Button","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","elementRef","isClicked","setIsClicked","fullClassName","handleMouseDown","aria-label","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","element","propName","handler","eventName","resolveEventName","canUseEventDelegation","handleEvent","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeEventListener","removeDelegatedListener","tagName","realEventName","eventNames","realEvent","events","furtherCallsPrevented","stopPropagation","Proxy","Reflect","setValue","isOpen","onCloseTransitionEnd","noOpenTransition","noCloseTransition","isClosed","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","isClosing","shouldRender","transitionClassNames","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","getHours","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","lowerFirst","upperFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","hours","minutes","seconds","string","formatVoiceRecordDuration","durationInMs","milliseconds","formatDateToString","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","findIndex","timestampPlusDay","MILISECONDS_IN_DAY","toUpperCase","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","photos","updateChats","updatedById","addChats","addedById","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalCount","totalChatCount","isFullyLoaded","updateCurrentMessageList","replaceChatMessages","updateMessageStore","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","isLinkedChannelPost","canDeleteCurrentThread","currentThreadId","originalPost","deleteChatScheduledMessages","scheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","addViewportId","safeReplaceViewportIds","newViewportIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","updateScheduledMessages","updateFocusedMessage","noHighlight","updateFocusDirection","direction","enterMessageSelectMode","toggleMessageSelection","childMessageIds","withShift","oldSelectedMessages","newMessageIds","newSelectedMessageIds","prevIndex","currentIndex","to","exitMessageSelectMode","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","newResults","currentIds","gif","replaceAnimatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","updateUser","userUpdate","contactUserIds","updatedUser","updateUsers","addUsers","updateSelectedUserId","deleteUser","MEMO_EMPTY_ARRAY","getComplexKey","updateGlobalSearch","searchStatePartial","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","newState","fetchingStatus","replaceLocalTextSearch","searchParams","updateLocalTextSearch","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","updateManagement","newSettings","replaceThemeSettings","theme","themes","addNotifyException","notifyException","updateNotifySettings","peerType","isSilent","shouldShowPreviews","hasPrivateChatsMessagePreview","hasGroupMessagePreview","hasBroadcastMessagePreview","addBlockedContact","contactId","blocked","removeBlockedContact","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","setRequestInfoId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","usePrevious","next","shouldSkipUndefined","trimText","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","indexedDB","onupgradeneeded","createObjectStore","dbp","txMode","db","transaction","objectStore","createStore","customStore","del","eachCursor","openCursor","continue","items","MenuItem","destructive","useLang","handleKeyDown","keyCode","data-char","origin","role","onKeyDown","ripples","setRipples","cleanUpDebounced","button","currentTarget","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","EMPTY_IMAGE_DATA_URI","webpToPng","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","WebpWorker","onmessage","handleLibWebpMessage","label","success","readOnly","placeholder","autoComplete","inputMode","maxLength","onChange","onInput","onKeyPress","onBlur","labelText","htmlFor","subLabel","checked","blocking","onCheck","handleChange","captureEscKeyListener","captureKeyboardListener","onEsc","isAnimating","dispatchHeavyAnimationEvent","dispatchEvent","Event","handleAnimationStart","handleAnimationEnd","formatFixedNumber","number","toFixed","formatIntegerCompact","views","getFirstLetters","phrase","word","prevDeps","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","Menu","containerRef","positionX","positionY","autoClose","footer","noCloseOnBackdrop","onCloseAnimationEnd","onClose","menuRef","backdropContainerRef","useShowTransition","useEffectWithPrevDeps","prevIsOpen","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","DecoderWorker","wavWorker","WavWorker","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","DataUri","Stream","memoryCache","fetchPromises","mediaFormat","onProgress","progressiveUrl","getProgressive","mediaPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","URL","createObjectURL","sourceBuffer","addSourceBuffer","endOfStream","appendBuffer","revokeObjectURL","getFromMemory","cancelProgress","mediaData","fullSize","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","IS_LANDSCAPE","isLandscape","windowSize","updateSizes","handleResize","vh","setProperty","utf16","len","RangeError","adapt","delta","numpoints","firsttime","decode","preserveCase","case_flags","input_length","out","bias","basic","j","ic","oldi","w","digit","lastIndexOf","cp","toUnicode","domain_array","ensureProtocol","getDomain","decodedHref","decodeURI","convertPunycode","toggleSafeLinkModal","openTelegramLink","isNotSafe","ctrlKey","altKey","shiftKey","metaKey","classNames","getFileSizeString","bytes","ONE_GIGABYTE","ONE_MEGABYTE","getDocumentExtension","getFileExtension","getColorFromExtension","extension","STRIPE_ERRORS","missing_payment_information","field","fieldError","invalid_number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","SHIPPING_ERRORS","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","getShippingError","errors","cur","currentInstance","animateSingle","tick","instance","isCancelled","animate","DropdownMenu","dropdownRef","setIsOpen","menu","focusedElement","activeElement","elementChildren","onTrigger","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","querySelectorAll","newIndex","RE_EMOJI_ONLY","twemojiRegex","DETECT_UP_TO","emojiCount","EXCLUDE_EMOJIS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","updateComponent","setupComponentUpdateListener","initComponent","node","createNode","childNodes","insertBefore","replaceChild","areComponents","nextSibling","newKeys","removeAttribute","addAttribute","oldValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","newChildKey","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","createDocumentFragment","renderChildren","$firstChild","createTextNode","$child","$fragmentChild","cssText","render","headId","$head","openUserInfo","handleMessageClick","openChat","targetUser","targetMessage","textOptions","maxTextLength","unprocessed","processed","processPlaceholder","isEmbedded","renderChatContent","renderUserContent","renderOriginContent","showQuotes","messageText","renderMessageContent","renderProductContent","renderMigratedContent","replaceValue","placeholderPosition","MESSAGE_DELETED","openChatByUsername","isInitialized","HEX_COLOR_REGEX","lerp","start","end","interpolationRatio","colors","themeColors","hexToRgb","hex","g","applyColorAnimationStep","startIndex","endIndex","propertyColors","withAnimation","isDarkTheme","shouldAnimate","startAt","themeColorTag","querySelector","classList","remove","transition","updateAppBadge","setAppBadge","contains","animationLevel","messageTextSize","switchTheme","uiReadyState","authPhoneNumber","authRememberMe","authError","apiUpdate","authIsLoading","password","file","authIsLoadingQrCode","reset","langCachePrefix","langCacheVersion","init","connectionState","authNearestCountry","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","run","marker","runClearTimeout","Item","noop","nextTick","arguments","apply","browser","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","binding","cwd","chdir","umask","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","saveSession","onUpdateSession","currentUser","sessionUserAuth","updateSessionUserId","onUpdateCurrentUser","showError","ServiceWorkerNoSupportError","setPrototypeOf","scriptUrl","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","activeChatFolder","recentEmojis","added","recent","featured","saved","topPeers","audioPlayer","notifications","activeSessions","messageSendKeyCombo","shouldSuggestStickers","light","isBlurred","patternColor","dark","privacy","updateCacheThrottled","isAllowed","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","loadCache","initialState","time","timeEnd","readCache","idsToSave","cid","chatIdsToSave","mainThread","history","replaceState","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","mediaLoader","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","getFilteredList","countryId","firstElementChild","dataset","handleInput","handleInputKeyDown","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","data-country-id","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","clearAuthError","gotToAuthQrCode","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","setSelectionRange","handlePhoneNumberChange","selectionStart","selectionEnd","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","AuthQrCode","AppInactive","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"mappings":"aACE,SAASA,EAAqBC,GAQ7B,IAPA,IAMIC,EAAUC,EANVC,EAAWH,EAAK,GAChBI,EAAcJ,EAAK,GAKAK,EAAI,EAAGC,EAAW,GACpCD,EAAIF,EAASI,OAAQF,IACzBH,EAAUC,EAASE,GAChBG,OAAOC,UAAUC,eAAeC,KAAKC,EAAiBV,IAAYU,EAAgBV,IACpFI,EAASO,KAAKD,EAAgBV,GAAS,IAExCU,EAAgBV,GAAW,EAE5B,IAAID,KAAYG,EACZI,OAAOC,UAAUC,eAAeC,KAAKP,EAAaH,KACpDa,EAAQb,GAAYG,EAAYH,IAKlC,IAFGc,GAAqBA,EAAoBf,GAEtCM,EAASC,QACdD,EAASU,OAATV,GAOF,IAAIW,EAAmB,GAGnBC,EAAqB,CACxBC,EAAG,GAMAP,EAAkB,CACrBO,EAAG,GAWJ,SAASC,EAAoBnB,GAG5B,GAAGgB,EAAiBhB,GACnB,OAAOgB,EAAiBhB,GAAUoB,QAGnC,IAAIC,EAASL,EAAiBhB,GAAY,CACzCI,EAAGJ,EACHsB,GAAG,EACHF,QAAS,IAUV,OANAP,EAAQb,GAAUU,KAAKW,EA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QAfT,KACnB7hC,OAAO6+B,SAASC,WAcV,iBCuCV,SAASinC,KACP,OACE,kBAAC,EAAD,CAAUve,KAAK,OAAOhoD,IAAI,QACxB,kBAAC,GAAD,OAKSgP,mBACZkM,GAAuBnL,YAAKmL,EAAQ,CAAC,cACtC,CAAC1N,EAAWC,IAA2BsC,YAAKtC,EAAS,CAAC,eAFzCuB,CAhD6B,EAAGkuD,YAAWsJ,iBACxD,MAAOC,EAAYC,GAAgBhE,aAAQ,GAc3C,GAZAr8D,YAAU,KACRylD,cfTFj8C,EeU6B,KACzB22D,IACApqE,SAAS8X,MAAS,GAAEzM,OAAaC,MAEjCg/D,MAED,CAACF,EAAYE,IAIZD,EACF,OAAO,kBAAC,GAAD,MAGT,GAAIvJ,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,kBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAOqJ,KAMb,OAFmB9pC,aAAaQ,QAAQj1B,OAAqBy0B,aAAaQ,QAAQh1B,KAE9Ds+D,KAAe,kBAAC,GAAD,Q,OC7CjCpjE,KAEF7C,QAAQkD,IAAI,YAGd8K,cAAcksD,OAEVr3D,KAEF7C,QAAQkD,IAAI,4BAGdmjE,IAASvQ,OACP,kBAAC,GAAD,MACAh6D,SAASynE,eAAe,SAGtB1gE,KAEF7C,QAAQkD,IAAI,6BAGdpH,SAASkL,iBAAiB,WAAY,KAEpChH,QAAQkD,IAAI,eAAgB6K","file":"main.8fc50c5cddc24213b18b.js","sourcesContent":[" \t// install a JSONP callback for chunk loading\n \tfunction webpackJsonpCallback(data) {\n \t\tvar chunkIds = data[0];\n \t\tvar moreModules = data[1];\n\n\n \t\t// add \"moreModules\" to the modules object,\n \t\t// then flag all \"chunkIds\" as loaded and fire callback\n \t\tvar moduleId, chunkId, i = 0, resolves = [];\n \t\tfor(;i < chunkIds.length; i++) {\n \t\t\tchunkId = chunkIds[i];\n \t\t\tif(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {\n \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n \t\t\t}\n \t\t\tinstalledChunks[chunkId] = 0;\n \t\t}\n \t\tfor(moduleId in moreModules) {\n \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n \t\t\t}\n \t\t}\n \t\tif(parentJsonpFunction) parentJsonpFunction(data);\n\n \t\twhile(resolves.length) {\n \t\t\tresolves.shift()();\n \t\t}\n\n \t};\n\n\n \t// The module cache\n \tvar installedModules = {};\n\n \t// object to store loaded CSS chunks\n \tvar installedCssChunks = {\n \t\t2: 0\n \t}\n\n \t// object to store loaded and loading chunks\n \t// undefined = chunk not loaded, null = chunk preloaded/prefetched\n \t// Promise = chunk loading, 0 = chunk loaded\n \tvar installedChunks = {\n \t\t2: 0\n \t};\n\n\n\n \t// script path function\n \tfunction jsonpScriptSrc(chunkId) {\n \t\treturn __webpack_require__.p + \"\" + chunkId + \".\" + {\"0\":\"c42f873e780469e6d6db\",\"1\":\"fb539fa72ec126e2a2cc\",\"3\":\"b7d1e22369add742c79e\",\"4\":\"75225d931a1e76f26855\",\"5\":\"c1959eb66d878675dbb0\",\"6\":\"63a48d34eed627347217\",\"7\":\"4b051a320886f1eac385\",\"8\":\"75df16efec295d79dd82\",\"9\":\"600e8c07ee8b577efa8f\"}[chunkId] + \".js\"\n \t}\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n \t// This file contains only the entry chunk.\n \t// The chunk loading function for additional chunks\n \t__webpack_require__.e = function requireEnsure(chunkId) {\n \t\tvar promises = [];\n\n\n \t\t// mini-css-extract-plugin CSS loading\n \t\tvar cssChunks = {\"0\":1,\"3\":1,\"4\":1,\"5\":1,\"6\":1};\n \t\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n \t\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n \t\t\tpromises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {\n \t\t\t\tvar href = \"\" + ({}[chunkId]||chunkId) + \".\" + {\"0\":\"c42f873e780469e6d6db\",\"1\":\"fb539fa72ec126e2a2cc\",\"3\":\"b7d1e22369add742c79e\",\"4\":\"75225d931a1e76f26855\",\"5\":\"c1959eb66d878675dbb0\",\"6\":\"63a48d34eed627347217\",\"7\":\"4b051a320886f1eac385\",\"8\":\"75df16efec295d79dd82\",\"9\":\"600e8c07ee8b577efa8f\"}[chunkId] + \".css\";\n \t\t\t\tvar fullhref = __webpack_require__.p + href;\n \t\t\t\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n \t\t\t\tfor(var i = 0; i < existingLinkTags.length; i++) {\n \t\t\t\t\tvar tag = existingLinkTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n \t\t\t\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return resolve();\n \t\t\t\t}\n \t\t\t\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n \t\t\t\tfor(var i = 0; i < existingStyleTags.length; i++) {\n \t\t\t\t\tvar tag = existingStyleTags[i];\n \t\t\t\t\tvar dataHref = tag.getAttribute(\"data-href\");\n \t\t\t\t\tif(dataHref === href || dataHref === fullhref) return resolve();\n \t\t\t\t}\n \t\t\t\tvar linkTag = document.createElement(\"link\");\n \t\t\t\tlinkTag.rel = \"stylesheet\";\n \t\t\t\tlinkTag.type = \"text/css\";\n \t\t\t\tlinkTag.onload = resolve;\n \t\t\t\tlinkTag.onerror = function(event) {\n \t\t\t\t\tvar request = event && event.target && event.target.src || fullhref;\n \t\t\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + request + \")\");\n \t\t\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n \t\t\t\t\terr.request = request;\n \t\t\t\t\tdelete installedCssChunks[chunkId]\n \t\t\t\t\tlinkTag.parentNode.removeChild(linkTag)\n \t\t\t\t\treject(err);\n \t\t\t\t};\n \t\t\t\tlinkTag.href = fullhref;\n\n \t\t\t\tvar head = document.getElementsByTagName(\"head\")[0];\n \t\t\t\thead.appendChild(linkTag);\n \t\t\t}).then(function() {\n \t\t\t\tinstalledCssChunks[chunkId] = 0;\n \t\t\t}));\n \t\t}\n\n \t\t// JSONP chunk loading for javascript\n\n \t\tvar installedChunkData = installedChunks[chunkId];\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\t// setup Promise in chunk cache\n \t\t\t\tvar promise = new Promise(function(resolve, reject) {\n \t\t\t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n \t\t\t\t});\n \t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n \t\t\t\t// start chunk loading\n \t\t\t\tvar script = document.createElement('script');\n \t\t\t\tvar onScriptComplete;\n\n \t\t\t\tscript.charset = 'utf-8';\n \t\t\t\tscript.timeout = 120;\n \t\t\t\tif (__webpack_require__.nc) {\n \t\t\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n \t\t\t\t}\n \t\t\t\tscript.src = jsonpScriptSrc(chunkId);\n\n \t\t\t\t// create error before stack unwound to get useful stacktrace later\n \t\t\t\tvar error = new Error();\n \t\t\t\tonScriptComplete = function (event) {\n \t\t\t\t\t// avoid mem leaks in IE.\n \t\t\t\t\tscript.onerror = script.onload = null;\n \t\t\t\t\tclearTimeout(timeout);\n \t\t\t\t\tvar chunk = installedChunks[chunkId];\n \t\t\t\t\tif(chunk !== 0) {\n \t\t\t\t\t\tif(chunk) {\n \t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n \t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n \t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n \t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n \t\t\t\t\t\t\terror.type = errorType;\n \t\t\t\t\t\t\terror.request = realSrc;\n \t\t\t\t\t\t\tchunk[1](error);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tinstalledChunks[chunkId] = undefined;\n \t\t\t\t\t}\n \t\t\t\t};\n \t\t\t\tvar timeout = setTimeout(function(){\n \t\t\t\t\tonScriptComplete({ type: 'timeout', target: script });\n \t\t\t\t}, 120000);\n \t\t\t\tscript.onerror = script.onload = onScriptComplete;\n \t\t\t\tdocument.head.appendChild(script);\n \t\t\t}\n \t\t}\n \t\treturn Promise.all(promises);\n \t};\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// on error function for async loading\n \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n \tvar jsonpArray = window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || [];\n \tvar oldJsonpFunction = jsonpArray.push.bind(jsonpArray);\n \tjsonpArray.push = webpackJsonpCallback;\n \tjsonpArray = jsonpArray.slice();\n \tfor(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);\n \tvar parentJsonpFunction = oldJsonpFunction;\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 102);\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, onTickEnd, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\nexport type FC_withDebug = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement = VirtualElementEmpty | VirtualElementText | VirtualElementTag | VirtualElementComponent;\nexport type VirtualRealElement = VirtualElementTag | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We force cleaning as many objects as possible. Not sure this is needed at all.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n // 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 })(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 effect: () => Function | void,\n dependencies?: any[],\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n const exec = () => {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n };\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n schedulerFn(exec);\n }\n } else {\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(fastRaf, effect, dependencies);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[]) {\n return useLayoutEffectBase(onTickEnd, effect, dependencies);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[]): 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 current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual, withDebug = false) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && withDebug) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name}: Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v4';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const API_UPDATE_THROTTLE = 300;\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 500;\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;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\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;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\nexport const LAYERS_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = 'image/png,image/gif,image/jpeg,video/mp4,video/avi,video/quicktime';\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,6})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\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_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'];\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\nexport function setGlobal(newGlobal?: GlobalState) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n runCallbacksThrottled();\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal);\n }\n });\n }\n}\n\nfunction updateContainers() {\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload) => {\n onDispatch(name, payload);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL CONTAINERS', orderBy(Object.values(containers), 'DEBUG_updates', 'desc'));\n });\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\nimport { getUserFullName } from './users';\nimport { getChatTitle } from './chats';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nexport function getMessageKey(message: ApiMessage) {\n const { chatId, id } = message;\n\n return `msg${chatId}-${id}`;\n}\n\nexport function parseMessageKey(key: string) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: Number(match[1]), messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${text ? text.text : lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${text ? text.text : lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji} ${lang('AttachSticker')} `;\n }\n\n if (audio) {\n const caption = [audio.title, audio.performer].filter(Boolean).join(' — ') || (text && text.text);\n return `${noEmoji ? '' : '🎧 '}${caption || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${text ? text.text : lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${text ? text.text : document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return text.text;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video && 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 && text.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && isMessageLocal(message);\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && message.senderId! < 0 && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return sender.id > 0 ? 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","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo,\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\nexport type IDimensions = {\n width: number;\n height: number;\n};\n\ntype Target = 'micro' | 'pictogram' | 'inline' | 'viewerPreview' | 'viewerFull' | 'download';\n\nconst MAX_INLINE_VIDEO_SIZE = 10 * 1024 ** 2; // 10 MB\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 && 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 getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n const webPage = getMessageWebPage(message);\n return webPage ? webPage.photo : undefined;\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\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n const thumbnail = getMessageMediaThumbnail(message);\n\n return thumbnail ? thumbnail.dataUri : undefined;\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\n if (!(photo || video || sticker || webPagePhoto || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (photo || webPagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=x`;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n return `${base}?size=z`;\n }\n }\n\n if (video) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n if (hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n if (canMessagePlayVideoInline(video)) {\n return getVideoOrAudioBaseHash(video, base);\n }\n\n return `${base}?size=z`;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(video, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n default:\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 default:\n return base;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return getVideoOrAudioBaseHash(audio, base);\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n default:\n return base;\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 getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (video && IS_PROGRESSIVE_SUPPORTED && (\n (target === 'viewerFull') || (target === 'inline' && canMessagePlayVideoInline(video))\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 getMessageMediaFilename(message: ApiMessage) {\n const { photo, video, webPage } = message.content;\n\n if (photo || (webPage && webPage.photo)) {\n return `photo${message.date}.jpeg`;\n }\n\n if (video) {\n return video.fileName;\n }\n\n return undefined;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo && photo.blobUrl) || (video && video.blobUrl) || (document && document.previewBlobUrl);\n}\n\nexport function canMessagePlayVideoInline(video: ApiVideo): boolean {\n return video.isGif || video.isRound || video.size <= MAX_INLINE_VIDEO_SIZE;\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], reverseOrder = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, 'media');\n\n return reverseOrder ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): IDimensions | 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): IDimensions | 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): IDimensions | undefined {\n if (video.width && video.height) {\n return video as IDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isDownloadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isDownloadNeeded;\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,\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 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;\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: number, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","export * from './users';\nexport * from './chats';\nexport * from './messages';\nexport * from './updates';\nexport * from './media';\nexport * from './payments';\nexport * from './settings';\nexport * from './misc';\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: number): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isChatPrivate, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport { ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: number): 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: number) {\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 (isChatPrivate(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: number) {\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: number) {\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: number, 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: number): '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: number, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && !selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\nimport { LangCode, EmojiKeywords } from '../../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 selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n\nexport function selectEmojiKeywords(global: GlobalState, language: LangCode): EmojiKeywords | undefined {\n return global.emojiKeywords[language] && global.emojiKeywords[language] !== undefined\n ? global.emojiKeywords[language] as EmojiKeywords\n : undefined;\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isChatPrivate,\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} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\n\nconst MESSAGE_EDIT_ALLOWED_TIME_MS = 172800000; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists && 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: number) {\n const messages = global.messages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: number) {\n const messages = global.scheduledMessages.byChatId[chatId];\n\n return messages ? messages.byId : undefined;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: number,\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: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: number, 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: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: number) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: number, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: number, 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: number, 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: number, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: number, 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: number, 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: number, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: number, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: number, 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: number) {\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 senderId > 0 ? 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);\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 = isChatPrivate(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 isServiceNotification = isServiceNotificationMessage(message);\n\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n const isMessageEditable = (\n (isChatWithSelf || Date.now() - message.date * 1000 < MESSAGE_EDIT_ALLOWED_TIME_MS)\n && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video && content.video.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = getCanPostInChat(chat, threadId) && !isServiceNotification;\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !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 = isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages');\n\n const canDeleteForAll = canDelete && !isServiceNotification && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages')\n ))\n );\n\n const canEdit = !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isAction && !isServiceNotification;\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 const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n };\n}\n\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 selectUploadProgress(global: GlobalState, message: ApiMessage) {\n const fileTransfer = global.fileUploads.byMessageLocalId[message.previousLocalId || message.id];\n\n return fileTransfer ? fileTransfer.progress : undefined;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: number, 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: number, 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 || 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 if (outlyingIds) {\n const found = !lastReadId ? outlyingIds[0] : outlyingIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = !lastReadId ? listedIds[0] : listedIds.find((id) => {\n return id > lastReadId && byId[id] && (!byId[id].isOutgoing || byId[id].isFromScheduled);\n });\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 Number(Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, Number(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: number, 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: number, 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: number, 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: number,\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 selectShouldAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n } = global.settings.byKey;\n\n return Boolean(\n (shouldAutoDownloadMediaInPrivateChats && isChatPrivate(chat.id))\n || (shouldAutoDownloadMediaInGroups && isChatGroup(chat))\n || (shouldAutoDownloadMediaInChannels && isChatChannel(chat))\n || (shouldAutoDownloadMediaFromContacts && sender && (\n sender.id === global.currentUserId\n || selectIsUserOrChatContact(global, sender)\n )),\n );\n}\n\nexport function selectShouldAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (shouldAutoPlayVideos && !asGif) || (shouldAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isChatPrivate } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: number) {\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 (isChatPrivate(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { RightColumnContent } from '../../types';\n\nimport { IS_MOBILE_SCREEN } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n } = global;\n\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_MOBILE_SCREEN && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","\nimport { GlobalState } from '../../global/types';\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n} from '../config';\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: 'Mac OS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'Mac OS';\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 === 'Mac OS';\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);\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_MOBILE_SCREEN = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = (navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\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);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n\nlet 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","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n","import Worker from 'worker-loader!./worker';\n\nimport { ApiOnProgress, ApiSessionData, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\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, sessionData?: ApiSessionData) {\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();\n subscribeToWorker(onUpdate);\n }\n\n return makeRequest({\n type: 'initApi',\n args: [sessionData],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n const requestState = requestStates.get(data.messageId);\n if (requestState && requestState.callback) {\n requestState.callback(...data.callbackArgs);\n }\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","// 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(cacheName: string, key: string, type: Type) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const request = new Request(key);\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: contentType });\n }\n }\n\n return blob;\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 const request = new Request(key);\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 { 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 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","export default __webpack_public_path__ + \"en-extra.e73049da90714ecdae3233e8ffa74d39.json\";","export default __webpack_public_path__ + \"es-extra.b80575cdf988e1a7e3a915abe97f63b4.json\";","export default __webpack_public_path__ + \"it-extra.78e5568451a888818c7e2209e05a9602.json\";","export default __webpack_public_path__ + \"pl-extra.38fd67a6c26e58f5c912568332c7c074.json\";","export default __webpack_public_path__ + \"ru-extra.5761b75bfbe92bb46eb8bba9acbdbb4c.json\";","import { ApiLangPack } from '../api/types';\n\nimport { DEBUG, LANG_CACHE_NAME, LANG_PACKS } from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { mapValues } from './iteratees';\n\nimport enExtraJson from '../assets/lang/en-extra.json';\nimport esExtraJson from '../assets/lang/es-extra.json';\nimport itExtraJson from '../assets/lang/it-extra.json';\nimport plExtraJson from '../assets/lang/pl-extra.json';\nimport ruExtraJson from '../assets/lang/ru-extra.json';\nimport { formatInteger } from './textFormat';\nimport { getGlobal } from '../lib/teact/teactn';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n}\n\nconst EXTRA_PACK_PATHS: Record = {\n en: enExtraJson as unknown as string,\n es: esExtraJson as unknown as string,\n it: itExtraJson as unknown as string,\n pl: plExtraJson as unknown as string,\n ru: ruExtraJson as unknown as string,\n};\n\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;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cached = cache.get(`${key}_${value}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack) {\n return key;\n }\n\n const langString = langPack[key];\n if (!langString) {\n return key;\n }\n\n const template = langString[typeof value === 'number' ? getPluralOption(value) : 'value'];\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 cache.set(`${key}_${value}_${format}`, result);\n return result;\n }\n\n return template;\n};\n\nexport async function setLanguage(langCode: string, callback?: NoneToVoidFunction) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n const newLangPack = await fetchFromCacheOrRemote(langCode);\n if (!newLangPack) {\n return;\n }\n\n if (EXTRA_PACK_PATHS[langCode]) {\n try {\n const response = await fetch(EXTRA_PACK_PATHS[langCode]);\n const pairs = await response.json();\n const extraLangPack = mapValues(pairs, (value, key) => ({ key, value }));\n\n Object.assign(newLangPack, extraLangPack);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages } = getGlobal().settings.byKey;\n const langInfo = languages ? languages.find((l) => l.langCode === langCode) : undefined;\n getTranslation.isRtl = Boolean(langInfo && langInfo.rtl);\n\n if (callback) {\n callback();\n }\n\n runCallbacks(langPack);\n}\n\nasync function fetchFromCacheOrRemote(langCode: string): Promise {\n const cached = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (cached) {\n return cached;\n }\n\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\nfunction getPluralOption(amount: number) {\n const optionIndex = currentLangCode && PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[currentLangCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n return template.replace(/%\\d?\\$?[sdf@]/, String(value));\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","// 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 React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n

\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","// This data was received from Telegram Desktop (Telegram/Resources/numbers.txt)\nconst DATA = `AF🇦🇫93Afghanistan333\nAO🇦🇴244Angola333\nAL🇦🇱355Albania234\nAD🇦🇩376Andorra222\nAE🇦🇪971United Arab Emirates234\nAI🇦🇮1264Anguilla34\nAR🇦🇷54Argentina\nAM🇦🇲374Armenia233\nAG🇦🇬1268Antigua and Barbuda34\nAU🇦🇺61Australia333\nAS🇦🇸1684American Samoa34\nAT🇦🇹43Austria\nAW🇦🇼297Aruba34\nAZ🇦🇿994Azerbaijan2322\nBI🇧🇮257Burundi224\nBE🇧🇪32Belgium3222\nBJ🇧🇯229Benin233\nBF🇧🇫226Burkina Faso2222\nBD🇧🇩880Bangladesh\nBG🇧🇬359Bulgaria\nBH🇧🇭973Bahrain44\nBS🇧🇸1242Bahamas34\nBA🇧🇦387Bosnia and Herzegovina\nBY🇧🇾375Belarus2322\nBZ🇧🇿501Belize\nBO🇧🇴591Bolivia134\nBR🇧🇷55Brazil254\nBB🇧🇧1246Barbados34\nBM🇧🇲1441Bermuda34\nBN🇧🇳673Brunei34\nBQ🇧🇶599Bonaire, Sint Eustatius and Saba\nBT🇧🇹975Bhutan\nBW🇧🇼267Botswana233\nCF🇨🇫236Central African Republic2222\nCA🇨🇦1Canada334\nCH🇨🇭41Switzerland234\nCK🇨🇰682Cook Islands\nCL🇨🇱56Chile144\nCN🇨🇳86China344\nCI🇨🇮225Côte d\\`Ivoire233\nCM🇨🇲237Cameroon44\nCD🇨🇩243DR Congo234\nCG🇨🇬242Republic of the Congo234\nCO🇨🇴57Colombia334\nKM🇰🇲269Comoros34\nCV🇨🇻238Cape Verde34\nCR🇨🇷506Costa Rica\nCU🇨🇺53Cuba44\nCY🇨🇾357Cyprus44\nCW🇨🇼599Curaçao\nCZ🇨🇿420Czech Republic\nDE🇩🇪49Germany38\nDJ🇩🇯253Djibouti2222\nDM🇩🇲1767Dominica34\nDK🇩🇰45Denmark44\nDO🇩🇴1Dominican Republic334\nDZ🇩🇿213Algeria3222\nEC🇪🇨593Ecuador\nEG🇪🇬20Egypt234\nER🇪🇷291Eritrea133\nES🇪🇸34Spain333\nEE🇪🇪372Estonia\nET🇪🇹251Ethiopia234\nFI🇫🇮358Finland\nFJ🇫🇯679Fiji\nFK🇫🇰500Falkland Islands\nFM🇫🇲691Micronesia\nFO🇫🇴298Faroe Islands33\nFR🇫🇷33France12222\nGA🇬🇦241Gabon1222\nGB🇬🇧44United Kingdom46\nGE🇬🇪995Georgia\nGF🇬🇫594French Guiana\nGH🇬🇭233Ghana\nGI🇬🇮350Gibraltar44\nGL🇬🇱299Greenland33\nGN🇬🇳224Guinea333\nGM🇬🇲220Gambia34\nGP🇬🇵590Guadeloupe\nGU🇬🇺1671Guam34\nGW🇬🇼245Guinea-Bissau34\nGQ🇬🇶240Equatorial Guinea333\nGR🇬🇷30Greece244\nGD🇬🇩1473Grenada34\nGT🇬🇹502Guatemala134\nGY🇬🇾592Guyana\nHK🇭🇰852Hong Kong\nHN🇭🇳504Honduras44\nHR🇭🇷385Croatia\nHT🇭🇹509Haiti\nHU🇭🇺36Hungary234\nID🇮🇩62Indonesia\nIN🇮🇳91India55\nIO🇩🇬246Diego Garcia34\nIE🇮🇪353Ireland234\nIR🇮🇷98Iran334\nIQ🇮🇶964Iraq334\nIS🇮🇸354Iceland34\nIL🇮🇱972Israel234\nIT🇮🇹39Italy334\nJM🇯🇲1876Jamaica34\nJO🇯🇴962Jordan144\nJP🇯🇵81Japan244\nKZ🇰🇿7Kazakhstan3322\nKE🇰🇪254Kenya333\nKG🇰🇬996Kyrgyzstan\nKH🇰🇭855Cambodia\nKI🇰🇮686Kiribati\nKN🇰🇳1869Saint Kitts and Nevis34\nKR🇰🇷82South Korea\nKW🇰🇼965Kuwait44\nKY🇰🇾1345Cayman Islands34\nLA🇱🇦856Laos\nLB🇱🇧961Lebanon\nLR🇱🇷231Liberia\nLY🇱🇾218Libya234\nLC🇱🇨1758Saint Lucia34\nLI🇱🇮423Liechtenstein\nLK🇱🇰94Sri Lanka234\nLS🇱🇸266Lesotho233\nLT🇱🇹370Lithuania35\nLU🇱🇺352Luxembourg\nLV🇱🇻371Latvia35\nMA🇲🇦212Morocco234\nMC🇲🇨377Monaco44\nMD🇲🇩373Moldova233\nMG🇲🇬261Madagascar2232\nMP🇲🇵1670Northern Mariana Islands34\nMO🇲🇴853Macau\nMS🇲🇸1664Montserrat34\nMV🇲🇻960Maldives\nMX🇲🇽52Mexico\nMH🇲🇭692Marshall Islands\nMK🇲🇰389Macedonia\nML🇲🇱223Mali44\nMT🇲🇹356Malta2222\nMM🇲🇲95Myanmar\nME🇲🇪382Montenegro\nMN🇲🇳976Mongolia\nMZ🇲🇿258Mozambique234\nMQ🇲🇶596Martinique\nMR🇲🇷222Mauritania44\nMU🇲🇺230Mauritius\nMW🇲🇼265Malawi\nMY🇲🇾60Malaysia\nNA🇳🇦264Namibia234\nNC🇳🇨687New Caledonia\nNE🇳🇪227Niger2222\nNF🇳🇫672Norfolk Island\nNG🇳🇬234Nigeria\nNI🇳🇮505Nicaragua44\nNL🇳🇱31Netherlands12222\nNO🇳🇴47Norway44\nNP🇳🇵977Nepal\nNU🇳🇺683Niue\nNR🇳🇷674Nauru\nNZ🇳🇿64New Zealand\nOM🇴🇲968Oman44\nPK🇵🇰92Pakistan334\nPA🇵🇦507Panama44\nPE🇵🇪51Peru333\nPF🇵🇫689French Polynesia\nPH🇵🇭63Philippines334\nPM🇵🇲508Saint Pierre and Miquelon\nPR🇵🇷1Puerto Rico334\nPS🇵🇸970Palestine324\nPW🇵🇼680Palau\nPG🇵🇬675Papua New Guinea\nPL🇵🇱48Poland333\nKP🇰🇵850North Korea\nPT🇵🇹351Portugal144\nPY🇵🇾595Paraguay333\nQA🇶🇦974Qatar\nRE🇷🇪262Réunion333\nRO🇷🇴40Romania333\nRU🇷🇺7Russia3322\nRW🇷🇼250Rwanda333\nSA🇸🇦966Saudi Arabia\nSD🇸🇩249Sudan234\nSN🇸🇳221Senegal234\nSG🇸🇬65Singapore44\nSH🇸🇭290Saint Helena23\nSH🇸🇭247Saint Helena4\nSB🇸🇧677Solomon Islands\nSL🇸🇱232Sierra Leone233\nSV🇸🇻503El Salvador44\nSM🇸🇲378San Marino334\nSO🇸🇴252Somalia233\nRS🇷🇸381Serbia234\nSS🇸🇸211South Sudan234\nST🇸🇹239São Tomé and Príncipe25\nSR🇸🇷597Suriname34\nSK🇸🇰421Slovakia\nSI🇸🇮386Slovenia\nSE🇸🇪46Sweden234\nSZ🇸🇿268Swaziland44\nSC🇸🇨248Seychelles1222\nSX🇸🇽1721Sint Maarten34\nSY🇸🇾963Syria\nTC🇹🇨1649Turks and Caicos Islands34\nTD🇹🇩235Chad2222\nTG🇹🇬228Togo233\nTH🇹🇭66Thailand144\nTJ🇹🇯992Tajikistan\nTK🇹🇰690Tokelau\nTM🇹🇲993Turkmenistan26\nTL🇹🇱670Timor-Leste\nTO🇹🇴676Tonga\nTT🇹🇹1868Trinidad and Tobago34\nTN🇹🇳216Tunisia233\nTR🇹🇷90Turkey334\nTV🇹🇻688Tuvalu\nTW🇹🇼886Taiwan\nTZ🇹🇿255Tanzania234\nUG🇺🇬256Uganda234\nUA🇺🇦380Ukraine2322\nUY🇺🇾598Uruguay44\nUS🇺🇸1United States334\nUZ🇺🇿998Uzbekistan27\nVA🇻🇦3Vatican City\nVC🇻🇨1784Saint Vincent and the Grenadines34\nVE🇻🇪58Venezuela334\nVG🇻🇬1284British Virgin Islands34\nVI🇻🇮1340US Virgin Islands34\nVN🇻🇳84Vietnam\nVU🇻🇺678Vanuatu\nWF🇼🇫681Wallis and Futuna\nWS🇼🇸685Samoa\nXK🇽🇰383Kosovo44\nYE🇾🇪967Yemen333\nZA🇿🇦27South Africa234\nZM🇿🇲260Zambia234\nZW🇿🇼263Zimbabwe234`;\n\nconst formatsCache: Record = {};\nexport const defaultPhoneNumberFormat = /(\\d{1,3})(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?(\\d{1,3})?/;\n\nconst parsed = DATA\n .split('\\n')\n .map((str) => {\n const id = str.substr(0, 2);\n const flag = str.substr(2, 4);\n const code = `+${str.match(/\\d+/)![0]}`;\n const name = str.split(/\\d+/)[1];\n const format = str.match(/\\d+$/);\n const phoneFormat = getPhoneNumberFormat(format);\n\n return {\n id, flag, code, name, phoneFormat,\n };\n });\n\nfunction getPhoneNumberFormat(format: RegExpMatchArray | null) {\n if (!format) {\n return defaultPhoneNumberFormat;\n }\n\n const formatValue = format[0] as string;\n let phoneNumberFormat;\n\n if (!formatsCache[formatValue]) {\n const phoneNumberGroups = formatValue.split('').map(Number);\n phoneNumberFormat = phoneNumberGroups.reduce((result, count, i) => {\n return `${result}(\\\\d{1,${count}})${i > 0 ? '?' : ''}`;\n }, '');\n formatsCache[formatValue] = new RegExp(`${phoneNumberFormat}${'()?'.repeat(5 - phoneNumberGroups.length)}`);\n }\n\n return formatsCache[formatValue];\n}\n\nexport default parsed;\n","import countryList, { defaultPhoneNumberFormat } from './countries';\n\nexport function getCountryById(id: string) {\n return countryList.find((c) => c.id === id) as Country;\n}\n\n// Empty groups are used to preserve 5 callback arguments for `replace` method\nfunction getPhoneNumberFormat(country?: Country) {\n return country ? country.phoneFormat : defaultPhoneNumberFormat;\n}\n\nexport function getCountryFromPhoneNumber(input: string) {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (!phoneNumber.startsWith('+')) {\n phoneNumber = `+${phoneNumber}`;\n }\n\n const possibleCountries = countryList\n .filter((country: Country) => phoneNumber.startsWith(country.code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return possibleCountries[possibleCountries.length - 1];\n}\n\nexport function formatPhoneNumber(input: string, country?: Country) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.code.length - 1);\n } else if (input.startsWith('+')) {\n return input;\n }\n\n phoneNumber = phoneNumber.replace(getPhoneNumberFormat(country), (_, p1, p2, p3, p4, p5) => {\n const separator = country && country.id === 'GB' ? ' ' : '-';\n\n let output = '';\n if (p1) output = `${p1}`;\n if (p2) output += ` ${p2}`;\n if (p3) output += `${separator}${p3}`;\n if (p4) output += `${separator}${p4}`;\n if (p5) output += `${separator}${p5}`;\n return output;\n });\n\n return phoneNumber;\n}\n\nexport function formatPhoneNumberWithCode(phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `${country.code} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n\nexport { countryList };\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 '../../../util/cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: number) {\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 Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\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 const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) return undefined;\n\n let mainDcId: number | undefined;\n const keys: Record = {};\n const hashes: Record = {};\n\n try {\n const userAuth = JSON.parse(userAuthJson);\n mainDcId = Number(userAuth.dcID);\n } catch (err) {\n // Do nothing.\n }\n\n if (!mainDcId) return undefined;\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;\n storeSession(sessionData);\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 {\n ApiLanguage, ApiMessage, ApiStickerSet, ApiShippingAddress,\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';\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};\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 interface ISettings extends NotifySettings, Record {\n theme: ThemeKey;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n shouldAutoDownloadMediaFromContacts: boolean;\n shouldAutoDownloadMediaInPrivateChats: boolean;\n shouldAutoDownloadMediaInGroups: boolean;\n shouldAutoDownloadMediaInChannels: boolean;\n shouldAutoPlayGifs: boolean;\n shouldAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: number[];\n allowChatIds: number[];\n blockUserIds: number[];\n blockChatIds: number[];\n}\n\nexport interface IInputPrivacyContact {\n id: number;\n accessHash?: string;\n}\n\nexport interface IInputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: IInputPrivacyContact[];\n allowedChats?: IInputPrivacyContact[];\n blockedUsers?: IInputPrivacyContact[];\n blockedChats?: IInputPrivacyContact[];\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 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 FoldersIncludedChats,\n FoldersExcludedChats,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\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 type ProfileTabType = 'members' | 'media' | 'documents' | 'links' | 'audio';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record;\n};\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","import { DEBUG_ALERT_MSG, GLOBAL_STATE_CACHE_KEY } 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;\nconst STARTUP_TIMEOUT = 5000;\n\nconst startedAt = Date.now();\nlet isReloading = false;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (isReloading) {\n return;\n }\n\n // For startup errors, we just clean the cache and refresh the page\n if (Date.now() - startedAt <= STARTUP_TIMEOUT && localStorage.getItem(GLOBAL_STATE_CACHE_KEY)) {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n isReloading = true;\n window.location.reload();\n\n return;\n }\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err && err.message) || err}\\n${err && err.stack}`);\n }\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { nativeToUnfified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\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 = nativeToUnfified(removeVS16s(emoji));\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? {emoji}\n : (\n \n ),\n );\n }\n if (type === 'html') {\n emojiResult.push(\n IS_EMOJI_SUPPORTED\n ? emoji\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n : `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'ig');\nconst RE_MENTION = /@[\\w\\d_-]+/ig;\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = [...(part.match(RE_LINK) || []), ...(part.match(RE_MENTION) || [])];\n if (!links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","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.filter((prop) => currentProps[prop] !== newProps[prop]);\n}\n","import { ApiMediaFormat } from '../api/types';\n\nimport * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { callApi } from '../api/gramjs';\nimport { ApiChat, ApiMessage } from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\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\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\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// Load notification settings from the api\nasync function loadNotificationSettings() {\n const [result] = await Promise.all([\n callApi('fetchNotificationSettings'),\n callApi('fetchNotificationExceptions'),\n ]);\n\n if (!result) return;\n setGlobal(replaceSettings(getGlobal(), result));\n}\n\nexport async function subscribe() {\n loadNotificationSettings();\n\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat, isActive: boolean) {\n const global = getGlobal();\n\n if (selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global)) || chat.isNotJoined) {\n return false;\n }\n\n // Dont show notification for active chat if client has focus\n if (isActive && document.hasFocus()) return false;\n\n switch (chat.type) {\n case 'chatTypePrivate':\n case 'chatTypeSecret':\n return Boolean(global.settings.byKey.hasPrivateChatsNotifications);\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return Boolean(global.settings.byKey.hasGroupNotifications);\n case 'chatTypeChannel':\n return Boolean(global.settings.byKey.hasBroadcastNotifications);\n }\n return false;\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\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 targetUserId: actionTargetUserId,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n const actionTargetUser = actionTargetUserId ? selectUser(global, actionTargetUserId) : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n let body: string;\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUser,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nexport function showNewMessageNotification({\n chat,\n message,\n isActiveChat,\n}: { chat: ApiChat; message: Partial; isActiveChat: boolean}) {\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n if (!checkIfShouldNotify(chat, isActiveChat)) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon: 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag: message.id.toString(),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n }\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date();\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 if (wasOnlineDate > today) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n today.setHours(0, 0, 0, 0);\n if (wasOnlineDate > yesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(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) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function sortUserIds(\n userIds: number[],\n usersById: Record,\n priorityIds?: number[],\n) {\n return orderBy(userIds, (id) => {\n const now = Date.now() / 1000;\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\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 ? Math.abs(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\nimport { NotifyException, NotifySettings } from '../../types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { LangFn } from '../../hooks/useLang';\n\nexport function isChatPrivate(chatId: number) {\n return chatId > 0;\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 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 const { inviteLink } = chat.fullInfo || {};\n\n if (inviteLink && inviteLink.length) {\n return inviteLink;\n }\n\n return username ? `t.me/${username}` : '';\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 && chat.currentUserBannedRights[key])\n || (chat.defaultBannedRights && 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) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isChatPrivate(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')) && (!isChatPrivate(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(chat: ApiChat) {\n if (chat.currentUserBannedRights && chat.currentUserBannedRights.sendMessages) {\n return 'You are not allowed to send messages in this chat.';\n }\n if (chat.defaultBannedRights && chat.defaultBannedRights.sendMessages) {\n return 'Sending messages is not allowed in this chat.';\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.lastMessage ? 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 return !(notifyExceptions && notifyExceptions[chat.id] && !notifyExceptions[chat.id].isMuted) && (\n chat.isMuted\n || (isChatPrivate(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n chatIdsCache?: number[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById).map(Number))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && !chat.unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isChatPrivate(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: number[],\n orderedPinnedIds?: number[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat && chat.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds && excludedChatIds.length)\n || (includedChatIds && includedChatIds.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: number[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function isChat(chatOrUser?: ApiUser | ApiChat): chatOrUser is ApiChat {\n if (!chatOrUser) {\n return false;\n }\n\n return chatOrUser.id < 0;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: number, sender?: ApiUser) {\n if (!sender || isChatPrivate(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: number[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: number[],\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 += 3e9; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that last message date can't be less than 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 priority += Date.now() + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n}) => {\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 );\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 e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {isLoading ? (\n
\n Please wait..\n \n
\n ) : children}\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName.replace(/^on/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement) {\n return (\n !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n hasOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\nexport function formatTime(datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n\n return `${hours}:${minutes}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(lang: LangFn, datetime: number | Date, isShort = false, noWeekdays = false) {\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 (isShort ? lowerFirst : upperFirst)(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 (isShort ? lowerFirst : upperFirst)(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 return isShort\n ? lowerFirst(lang(`Weekday.Short${weekDay}`))\n : upperFirst(lang(`Weekday.${weekDay}`));\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 (isShort ? lowerFirst : upperFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true)}, ${formatTime(date)}`;\n}\n\nexport function formatMediaDuration(duration: 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 let string = '';\n if (hours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date) {\n return date.toLocaleString(\n 'en-US',\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILISECONDS_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 { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: number[] | 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: number[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds && 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: number, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).forEach((id) => {\n global = updateChat(global, Number(id), updatedById[Number(id)]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateChat(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: number,\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?: number[];\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","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport { MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT } 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: number | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n // TODO Support stack navigation\n messageLists: chatId ? [{ chatId, threadId, type }] : undefined,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: number, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: number, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current && current.threadsById),\n [threadId]: {\n ...(current && current.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: number, 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: number, 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).map(Number).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: number, 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: number, 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: number, 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 }, undefined);\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: number,\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 && forwardInfo.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\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\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\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\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList && 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: number,\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, undefined);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds && 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: number,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds && 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: number,\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: number,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(viewportIds, newViewportIds) ? viewportIds : newViewportIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: number, 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: number, 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: number, newById: Record, hash: number | undefined,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n hash,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: number, update: Partial<{ byId: Record; hash: number }>,\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?: number, messageId?: number, noHighlight = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\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: number,\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: number,\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","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: number,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: number,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\nexport function updateUser(global: GlobalState, userId: number, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n const { hash, userIds: contactUserIds } = global.contactList || {};\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return global;\n }\n\n if (updatedUser.isContact && (contactUserIds && !contactUserIds.includes(userId))) {\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: [userId, ...contactUserIds],\n },\n };\n }\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n Object.keys(updatedById).map(Number).forEach((id) => {\n global = updateUser(global, id, updatedById[id]);\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n Object.keys(addedById).map(Number).forEach((id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n global = updateUser(global, id, addedById[id]);\n }\n });\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: number): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: number): GlobalState {\n const { byId } = global.users;\n const { hash, userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n hash: hash || 0,\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType && resultsByType[type] ? resultsByType[type]!.foundIds : undefined;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: number,\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: number,\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: number,\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 && 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: number,\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: number,\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: number,\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: number,\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 && resultsByType[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: number, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\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 addNotifyException(\n global: GlobalState, id: number, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: number): GlobalState {\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: number): GlobalState {\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n formId: 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 description,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n description,\n photoUrl,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { 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","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","function 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 request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n const dbp = promisifyRequest(request);\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }: Ripple) => (\n \n ))}\n
\n );\n};\n\nexport default memo(RippleEffect);\n","import WebpWorker from 'worker-loader!../lib/webp/webp_wasm.worker';\nimport { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\ntype TEncodedImage = {\n result: Uint8ClampedArray;\n width: number;\n height: number;\n};\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, url: string): Promise {\n if (isWebpSupported() || url.substr(0, 15) !== 'data:image/webp') {\n return url;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(url));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${url}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new WebpWorker() 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 worker.requests = worker.requests || new Map();\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n}) => {\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 { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","import { useEffect } from '../lib/teact/teact';\n\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration: number) => {\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n isAnimating = true;\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","export function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => word.length && word.match(/./u)![0].toUpperCase())\n .join('');\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","const RE_NOT_LETTER = /[^\\wа-яё]+/;\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","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';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\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 { transitionClassNames } = useShowTransition(isOpen, onCloseAnimationEnd);\n\n useEffect(() => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined), [isOpen, onClose]);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n
\n );\n};\n\nexport default Menu;\n","import DecoderWorker from 'worker-loader!opus-recorder/dist/decoderWorker.min';\nimport WavWorker from 'worker-loader!opus-recorder/dist/waveWorker.min';\n\nconst 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: DecoderWorker | undefined = new DecoderWorker();\n let wavWorker: WavWorker | undefined = new WavWorker();\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.DataUri]: cacheApi.Type.Text,\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\n\nexport function fetch(\n url: string, mediaFormat: T, onProgress?: ApiOnProgress,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, onProgress)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, onProgress)\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 });\n\n fetchPromises.set(url, promise);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n cancelApiProgress(progressCallback);\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(url: string, mediaFormat: ApiMediaFormat, onProgress?: ApiOnProgress) {\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]!);\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 void callApi('downloadMedia', { url, mediaFormat }, (progress: number, arrayBuffer: ArrayBuffer) => {\n if (onProgress) {\n onProgress(progress);\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\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const remote = await callApi('downloadMedia', { url, mediaFormat }, onProgress);\n if (!remote) {\n throw new Error('Failed to fetch media');\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 = blob.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 prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","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 { 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_MOBILE_SCREEN } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_MOBILE_SCREEN && isLandscape();\n\nlet windowSize = updateSizes();\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if ((isMobileScreen() !== IS_MOBILE_SCREEN) || (IS_MOBILE_SCREEN && IS_LANDSCAPE !== isLandscape())) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('resize', handleResize);\nwindow.addEventListener('orientationchange', handleResize);\n\nexport function updateSizes(): IDimensions {\n const vh = window.innerHeight * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n};\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 { withGlobal } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\nimport { GlobalActions } from '../../global/types';\n\nimport { DEBUG, RE_TME_INVITE_LINK, RE_TME_LINK } from '../../config';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n toggleSafeLinkModal,\n openTelegramLink,\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_TME_INVITE_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {content}\n \n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'toggleSafeLinkModal', 'openTelegramLink',\n ]),\n)(SafeLink));\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies);\n};\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","const STRIPE_ERRORS: Record> = {\n missing_payment_information: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n fieldError: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n fieldError: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n fieldError: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n fieldError: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message, code, param } = error;\n const { field, fieldError, description } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n return {\n field,\n fieldError,\n description: description || message,\n };\n}\n\nconst SHIPPING_ERRORS: Record> = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n fieldError: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n fieldError: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n fieldError: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n fieldError: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n fieldError: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n fieldError: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n fieldError: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n fieldError: 'Incorrect email',\n },\n};\n\n\nexport function getShippingError(errors: Record) {\n return Object.values(errors).reduce((acc, cur) => {\n const error = SHIPPING_ERRORS[cur.message];\n if (error) {\n acc = {\n ...acc,\n [error.field]: error.fieldError,\n };\n }\n return acc;\n }, {});\n}\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import 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 children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\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 };\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 };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n
\n );\n};\n\nexport default DropdownMenu;\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","// 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\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\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 nativeToUnfified(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","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value);\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: number;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isChat,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUser?: ApiUser,\n targetMessage?: ApiMessage,\n targetChatId?: number,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const { text } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 16 };\n\n let unprocessed: string;\n let processed = processPlaceholder(\n text,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUser\n ? renderUserContent(targetUser, options.asPlain)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const showQuotes = text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, options.maxTextLength)!;\n\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = `«${text}»`;\n }\n\n if (options.asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isChat(origin)\n ? renderChatContent(lang, origin, asPlain)\n : renderUserContent(origin, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: number, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart): TextPart[] {\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 content.push(replaceValue);\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","export interface ApiPhotoSize {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n width: number;\n height: number;\n}\n\nexport interface ApiThumbnail {\n dataUri: string;\n height: number;\n width: number;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash: string;\n emoji: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\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?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n description?: string;\n receiptMsgId?: number;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserId?: number;\n targetChatId?: number;\n type: 'historyClear' | 'other';\n photo?: ApiPhoto;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n hasDocument?: true;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\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?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\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 isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\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.\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: number;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n });\n}\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","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","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"8ede9bdfe3390ee397af.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"01705582fc3eca0e007b.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"0dbbe0a906f6c2adf071.worker.js\");\n};","module.exports = function() {\n return new Worker(__webpack_public_path__ + \"a66075669d8d0ac2d740.worker.js\");\n};","import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n IS_ANDROID, IS_IOS, IS_SAFARI, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\n\naddReducer('init', (global) => {\n const {\n theme, animationLevel, messageTextSize, language,\n } = global.settings.byKey;\n\n setLanguage(language);\n\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel > 0);\n\n if (IS_SAFARI) {\n document.body.classList.add('is-safari');\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 }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { initApi, callApi } from '../../../api/gramjs';\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 importTestSession,\n} from './sessions';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n } else {\n importTestSession();\n }\n\n void initApi(actions.apiUpdate, loadStoredSession());\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('gotToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionData } = payload;\n\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddReducer('signOut', () => {\n (async () => {\n await unsubscribe();\n await callApi('destroy');\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser,\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';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus') {\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 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error':\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n actions.showError({ error: update.error });\n\n break;\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n subscribe();\n 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 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 setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n if (!getGlobal().authRememberMe) {\n return;\n }\n\n const { sessionData } = update;\n\n getDispatch().saveSession({ sessionData });\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: number) {\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","export var ServiceWorkerNoSupportError = (function() {\n\n\tfunction ServiceWorkerNoSupportError() {\n\t\tvar err = Error.call(this, 'ServiceWorker is not supported.');\n\t\tObject.setPrototypeOf(err, ServiceWorkerNoSupportError.prototype);\n\t\treturn err;\n\t}\n\n\tServiceWorkerNoSupportError.prototype = Object.create(Error.prototype);\n\n\treturn ServiceWorkerNoSupportError;\n})();\n\nexport var scriptUrl = __webpack_public_path__ + \"serviceWorker.js\";\n\nexport default function registerServiceWorkerIfSupported(mapScriptUrlOrOptions, maybeOptions) {\n\n\tvar targetScriptUrl = scriptUrl;\n\tvar options = maybeOptions;\n\n\tif (typeof mapScriptUrlOrOptions === 'function') {\n\t\ttargetScriptUrl = mapScriptUrlOrOptions(targetScriptUrl);\n\t} else {\n\t\toptions = mapScriptUrlOrOptions;\n\t}\n\n\tif ('serviceWorker' in navigator) {\n\t\treturn navigator.serviceWorker.register(targetScriptUrl, options);\n\t}\n\n\treturn Promise.reject(new ServiceWorkerNoSupportError());\n}\n","import { scriptUrl } from 'service-worker-loader!../serviceWorker';\n\nimport { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action:WorkerAction = e.data;\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n dispatch.focusMessage(action.payload);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(scriptUrl);\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 getDispatch().showError({ error: { message: 'SERVICE_WORKER_DISABLED' } });\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';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n} from '../config';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n uiReadyState: 0,\n\n authRememberMe: true,\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n },\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 featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n globalSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n mediaViewer: {},\n\n audioPlayer: {},\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n errors: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n messageTextSize: DEFAULT_MESSAGE_TEXT_SIZE_PX,\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n theme: 'light',\n shouldAutoDownloadMediaFromContacts: true,\n shouldAutoDownloadMediaInPrivateChats: true,\n shouldAutoDownloadMediaInGroups: true,\n shouldAutoDownloadMediaInChannels: true,\n shouldAutoPlayGifs: true,\n shouldAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n LEGACY_SESSION_KEY,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN, GLOBAL_STATE_CACHE_USER_LIST_LIMIT, SESSION_USER_KEY,\n} from '../config';\nimport { IS_MOBILE_SCREEN } from '../util/environment';\nimport { pick } from '../util/iteratees';\nimport { INITIAL_STATE } from './initial';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\nconst UPDATE_THROTTLE = 1000;\n\nconst updateCacheThrottled = throttle(updateCache, UPDATE_THROTTLE, false);\n\nlet isAllowed = false;\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n });\n\n addReducer('reset', () => {\n isAllowed = false;\n removeCallback(updateCacheThrottled);\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n });\n}\n\nexport function loadCache(initialState: GlobalState) {\n if (!GLOBAL_STATE_CACHE_DISABLED) {\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n if (hasSession) {\n isAllowed = true;\n addCallback(updateCacheThrottled);\n return readCache(initialState);\n } else {\n isAllowed = false;\n }\n }\n\n return undefined;\n}\n\nfunction readCache(initialState: 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 // Pre-fill defaults in nested objects which may be missing in older cache\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n }\n\n return {\n ...initialState,\n ...cached,\n };\n}\n\nfunction updateCache() {\n onIdle(() => {\n if (!isAllowed) {\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 'chatFolders',\n 'topPeers',\n 'recentEmojis',\n 'emojiKeywords',\n 'push',\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 };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n });\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter((cid) => cid > 0),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave as number[]),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n const currentMessageList = selectCurrentMessageList(global);\n\n return {\n byChatId,\n messageLists: !currentMessageList || IS_MOBILE_SCREEN ? undefined : [{\n ...currentMessageList,\n threadId: MAIN_THREAD_ID,\n type: 'thread',\n }],\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","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n const newGlobal = loadCache(initial) || initial;\n\n const currentMessageList = selectCurrentMessageList(newGlobal) || {};\n window.history.replaceState(currentMessageList, '');\n\n return newGlobal;\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","export default __webpack_public_path__ + \"telegram-logo.df3a91becaa9678c529b4c4cadd45204.svg\";","export default __webpack_public_path__ + \"monkey.a3d5fcdc50b18dc55695f7dd4101a8c9.svg\";","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.DataUri);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n
\n {children}\n {shouldRenderMask && (\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 } = global.settings.byKey;\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\n\nimport { countryList } from '../../util/phoneNumber';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\nimport { ANIMATION_END_DELAY } from '../../config';\n\ntype OwnProps = {\n id: string;\n value?: Country;\n isLoading?: boolean;\n onChange: (value: Country) => 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}) => {\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(countryList);\n\n function updateFilter(filterValue?: string) {\n setFilter(filterValue);\n setFilteredList(getFilteredList(filterValue));\n }\n\n const handleChange = useCallback((e: React.SyntheticEvent) => {\n const { countryId } = (e.currentTarget.firstElementChild as HTMLDivElement).dataset;\n const country = countryList.find((c) => c.id === countryId);\n\n if (country) {\n onChange(country);\n }\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, []);\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, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const inputValue = filter !== undefined\n ? filter\n : (value && value.name) || '';\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList.map((country: Country) => (\n \n \n {renderText(country.flag, ['hq_emoji'])}\n {country.name}\n {country.code}\n \n ))}\n {!filteredList.length && (\n \n No countries matched your filter.\n \n )}\n \n );\n};\n\nfunction getFilteredList(filter = ''): Country[] {\n return filter.length\n ? countryList.filter((country) => searchWords(country.name, filter))\n : countryList;\n}\n\nexport default memo(CountryCodeInput);\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryById, getCountryFromPhoneNumber } from '../../util/phoneNumber';\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;\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n clearAuthError,\n gotToAuthQrCode,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\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\n const fullNumber = country ? `${country.code} ${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 (authNearestCountry && !country && !isTouched) {\n setCountry(getCountryById(authNearestCountry));\n }\n }, [country, authNearestCountry, isTouched]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n const suggestedCountry = getCountryFromPhoneNumber(newFullNumber);\n const selectedCountry = !country || (suggestedCountry && suggestedCountry.id !== country.id)\n ? suggestedCountry\n : country;\n\n if (!newFullNumber.length) {\n setCountry(undefined);\n } else if (!country || (selectedCountry && selectedCountry.code !== country.code)) {\n setCountry(selectedCountry);\n }\n\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [country]);\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 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 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 parseFullNumber(value);\n }, [authError, clearAuthError, 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

Sign in to Telegram

\n

\n Please confirm your country and\n
enter your phone number.\n

\n
\n \n \n \n {canSubmit && (\n isAuthReady ? (\n \n ) : (\n \n )\n )}\n {isAuthReady && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'gotToAuthQrCode',\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","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 AuthQrCodeAsync: FC = () => {\n const AuthQrCode = useModuleLoader(Bundles.Auth, 'AuthQrCode');\n\n return AuthQrCode ? : ;\n};\n\nexport default memo(AuthQrCodeAsync);\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\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.async';\n\nimport './Auth.scss';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst Auth: FC = ({ authState, reset, initApi }) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n useEffect(() => {\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return ;\n case 'authorizationStateWaitPassword':\n return ;\n case 'authorizationStateWaitRegistration':\n return ;\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateWaitPhoneNumber':\n default:\n return ;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi']),\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","export default __webpack_public_path__ + \"app-inactive.bc7953c2dfebcabce2c43ca7dc778a89.png\";","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n
\n
\n \"\"\n

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport {\n LEGACY_SESSION_KEY, INACTIVE_MARKER, SESSION_USER_KEY, PAGE_TITLE,\n} 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';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n const hasSession = localStorage.getItem(SESSION_USER_KEY) || localStorage.getItem(LEGACY_SESSION_KEY);\n\n return hasSession ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('GLOBAL STATE', getGlobal());\n});\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/report.html b/dist/report.html index 466ad431..adf8c9ba 100644 --- a/dist/report.html +++ b/dist/report.html @@ -3,7 +3,7 @@ - telegram-t [15 Jun 2021 at 00:26] + telegram-t [15 Jun 2021 at 02:21]