tweb/public/13.234dc6639cd6dd1f11ca.chu...

2 lines
798 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(this.webpackJsonp=this.webpackJsonp||[]).push([[13],{108:function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var i=s(33),n=s(65);class a extends n.b{constructor(e={}){super(Object.assign({plainText:!0},e)),this.passwordVisible=!1,this.onVisibilityClick=e=>{Object(i.a)(e),this.passwordVisible=!this.passwordVisible,this.toggleVisible.classList.toggle("eye-hidden",this.passwordVisible),this.input.type=this.passwordVisible?"text":"password",this.onVisibilityClickAdditional&&this.onVisibilityClickAdditional()};const t=this.input;t.type="password",t.setAttribute("required",""),t.name="notsearch_password",t.autocomplete="off";const s=document.createElement("input");s.classList.add("stealthy"),s.tabIndex=-1,s.type="password",t.parentElement.prepend(s),t.parentElement.insertBefore(s.cloneNode(),t.nextSibling);const n=this.toggleVisible=document.createElement("span");n.classList.add("toggle-visible","tgico"),this.container.classList.add("input-field-password"),this.container.append(n),n.addEventListener("click",this.onVisibilityClick),n.addEventListener("touchend",this.onVisibilityClick)}}},119:function(e,t,s){"use strict";function i(e,t){const s=e.length;if(s!==t.length)return!1;for(let i=0;i<s;++i)if(e[i]!==t[i])return!1;return!0}s.d(t,"a",(function(){return i}))},120:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(14);function n(e,t=!1){if(!i.a||t&&document.activeElement===e)if(e.focus(),void 0!==window.getSelection&&void 0!==document.createRange){var s=document.createRange();s.selectNodeContents(e),s.collapse(!1);var n=window.getSelection();n.removeAllRanges(),n.addRange(s)}else if(void 0!==document.body.createTextRange){var a=document.body.createTextRange();a.moveToElementText(e),a.collapse(!1),a.select()}}},122:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(71);class n{constructor(e,t){this.passwordInputField=e,this.size=t,this.needFrame=0,this.container=document.createElement("div"),this.container.classList.add("media-sticker-wrapper")}load(){return this.loadPromise?this.loadPromise:this.loadPromise=i.a.loadAnimationAsAsset({container:this.container,loop:!1,autoplay:!1,width:this.size,height:this.size,noCache:!0},"TwoFactorSetupMonkeyPeek").then(e=>(this.animation=e,this.animation.addEventListener("enterFrame",e=>{(1===this.animation.direction&&e>=this.needFrame||-1===this.animation.direction&&e<=this.needFrame)&&(this.animation.setSpeed(1),this.animation.pause())}),this.passwordInputField.onVisibilityClickAdditional=()=>{this.passwordInputField.passwordVisible?(this.animation.setDirection(1),this.animation.curFrame=0,this.needFrame=16,this.animation.play()):(this.animation.setDirection(-1),this.animation.curFrame=16,this.needFrame=0,this.animation.play())},i.a.waitForFirstFrame(e)))}remove(){this.animation&&this.animation.remove()}}},131:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(71);class n{constructor(e,t){this.inputField=e,this.size=t,this.max=45,this.needFrame=0,this.container=document.createElement("div"),this.container.classList.add("media-sticker-wrapper");const s=e.input;s.addEventListener("blur",()=>{this.playAnimation(0)}),s.addEventListener("input",t=>{this.playAnimation(e.value.length)})}playAnimation(e){if(!this.animation)return;let t;(e=Math.min(e,30))?(t=Math.round(Math.min(this.max,e)*(165/this.max)+11.33),this.idleAnimation&&(this.idleAnimation.stop(!0),this.idleAnimation.canvas.style.display="none"),this.animation.canvas.style.display=""):t=0;const s=this.needFrame>t?-1:1;this.animation.setDirection(s),0!==this.needFrame&&0===t&&this.animation.setSpeed(7),this.needFrame=t,this.animation.play()}load(){return this.loadPromise?this.loadPromise:this.loadPromise=Promise.all([i.a.loadAnimationAsAsset({container:this.container,loop:!0,autoplay:!0,width:this.size,height:this.size},"TwoFactorSetupMonkeyIdle").then(e=>(this.idleAnimation=e,this.inputField.value.length||e.play(),i.a.waitForFirstFrame(e))),i.a.loadAnimationAsAsset({container:this.container,loop:!1,autoplay:!1,width:this.size,height:this.size},"TwoFactorSetupMonkeyTracking").then(e=>(this.animation=e,this.inputField.value.length||(this.animation.canvas.style.display="none"),this.animation.addEventListener("enterFrame",e=>{(1===this.animation.direction&&e>=this.needFrame||-1===this.animation.direction&&e<=this.needFrame)&&(this.animation.setSpeed(1),this.animation.pause()),0===e&&0===this.needFrame&&this.idleAnimation&&(this.idleAnimation.canvas.style.display="",this.idleAnimation.play(),this.animation.canvas.style.display="none")}),i.a.waitForFirstFrame(e)))])}remove(){this.animation&&this.animation.remove(),this.idleAnimation&&this.idleAnimation.remove()}}},132:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(65);class n extends i.b{constructor(e){super(Object.assign({plainText:!0},e));const t=this.input;t.type="tel",t.setAttribute("required",""),t.autocomplete="off";let s=0;this.input.addEventListener("input",t=>{this.input.classList.remove("error"),this.setLabel();const i=this.value.replace(/\D/g,"").slice(0,e.length);this.setValueSilently(i);const n=this.value.length;if(n===e.length)e.onFill(this.value);else if(n===s)return;s=n})}}},154:function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));var i=s(120),n=s(121),a=s(2),o=s(65);class r extends o.b{constructor(e={}){super(Object.assign({label:"Contacts.PhoneNumber.Placeholder",name:"phone"},e)),this.pasted=!1,this.lastValue="",this.container.classList.add("input-field-phone");let t=this.input;if(t instanceof HTMLInputElement)t.type="tel",t.autocomplete="rr55RandomRR55";else{t.inputMode="decimal";const e=window.devicePixelRatio;if(e>1){let s;a.b?s=-.16*e:a.a&&(s=0),t.style.setProperty("--letter-spacing",s+"px")}const s=this.setValueSilently.bind(this);this.setValueSilently=e=>{s(e),Object(i.a)(this.input,!0)}}t.addEventListener("input",()=>{t.classList.remove("error");const s=this.value;let i;Math.abs(s.length-this.lastValue.length)>1&&!this.pasted&&a.c&&this.setValueSilently(this.lastValue+s),this.pasted=!1,this.setLabel();let o,r,l,c="";"+"===this.value.replace(/\++/,"+")?this.setValueSilently("+"):(i=Object(n.a)(this.value),o=i.formatted,r=i.country,c=i.leftPattern,l=i.code,this.setValueSilently(this.lastValue=o?"+"+o:"")),t.dataset.leftPattern=c,e.onInput&&e.onInput(i)}),t.addEventListener("paste",()=>{this.pasted=!0}),t.addEventListener("keypress",e=>{const t=e.key;if(/\D/.test(t)&&!e.metaKey&&!e.ctrlKey&&"Backspace"!==t&&("+"!==t||!e.shiftKey))return e.preventDefault(),!1})}}},184:function(e,t,s){"use strict";s.r(t),s.d(t,"AppDialogsManager",(function(){return Oc}));var i=s(64),n=s(75),a=s(0),o=s(63),r=s(72),l=s(57),c=s(33),d=s(127),h=s(178),p=s(191);const u=[...h.a].concat([...p.a]);var g=new Set(u),m=s(66),b=s(62),v=s(98),f=s(79);function y(e){Object(f.a)(e.history,(t,s,i)=>{t.action.photo||(i.splice(s,1),void 0!==e.count&&--e.count)})}var w=s(18);class S{constructor(e){this.previous=[],this.next=[],this.reverse=!1,this.loadCount=50,this.loadWhenLeft=20,this.loadedAllUp=!1,this.loadedAllDown=!1,Object(w.a)(this,e)}setTargets(e,t,s){this.previous=e,this.next=t,this.reverse=s}get index(){return void 0!==this.count?this.previous.length:-1}reset(e=!1){this.current=void 0,this.previous=[],this.next=[],this.setLoaded(!0,e),this.setLoaded(!1,e)}go(e,t=!0){let s,i;if(e>0){if(s=this.next.splice(0,e),i=s.pop(),!i)return;void 0!==this.current&&s.unshift(this.current),this.previous.push(...s)}else{if(s=this.previous.splice(Math.max(0,this.previous.length+e),-e),i=s.shift(),!i)return;void 0!==this.current&&s.push(this.current),this.next.unshift(...s)}return this.next.length<this.loadWhenLeft&&this.load(!this.reverse),this.previous.length<this.loadWhenLeft&&this.load(this.reverse),this.current=i,t&&this.onJump&&this.onJump(i,e>0),this.current}unsetCurrent(e){e?this.previous.push(this.current):this.next.unshift(this.current),this.current=void 0}goUnsafe(e,t){const s=e>0?Math.max(0,e-this.next.length):Math.min(0,e+this.previous.length),i=this.go(e,!s&&t);return{item:s?void 0:i,leftLength:s}}setLoaded(e,t){return(e?this.loadedAllDown:this.loadedAllUp)!==t&&(e?this.loadedAllDown=t:this.loadedAllUp=t,t||(e?this.loadPromiseDown=null:this.loadPromiseUp=null),!0)}load(e){if(e?this.loadedAllDown:this.loadedAllUp)return Promise.resolve();let t,s=e?this.loadPromiseDown:this.loadPromiseUp;return s||(t=e?this.reverse?this.previous[0]:this.next[this.next.length-1]:this.reverse?this.next[this.next.length-1]:this.previous[0],null!=t||(t=this.current),s=this.loadMore(t,e,this.loadCount).then(t=>{if((e?this.loadPromiseDown:this.loadPromiseUp)!==s)return;t.items.length<this.loadCount&&this.setLoaded(e,!0),void 0===this.count&&(this.count=t.count||t.items.length);(e?t.items.forEach.bind(t.items):f.a.bind(null,t.items))(t=>{const s=this.processItem?this.processItem(t):t;s&&(e?this.reverse?this.previous.unshift(s):this.next.push(s):this.reverse?this.next.push(s):this.previous.unshift(s))}),this.onLoadedMore&&this.onLoadedMore()},()=>{}).then(()=>{e?this.loadPromiseDown=null:this.loadPromiseUp=null}),e?this.loadPromiseDown=s:this.loadPromiseUp=s,s)}}class C extends S{constructor(e={}){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{const n=t?0:s;let a=null==e?void 0:e.mid;return void 0===a&&(a=this.searchContext.maxId),t||(a=v.a.incrementMessageId(a,1)),i.a.getSearch(Object.assign(Object.assign({},this.searchContext),{peerId:this.searchContext.peerId||(null==e?void 0:e.peerId),maxId:a,limit:n?0:s,backLimit:n})).then(e=>("inputMessagesFilterChatPhotos"===this.searchContext.inputFilter._&&y(e),e.next_rate&&(this.searchContext.nextRate=e.next_rate),{count:e.count,items:e.history}))},processItem:t=>{if(this.filterMids([t.mid]).length)return e.processItem(t)}})),this.onHistoryDelete=({peerId:e,msgs:t})=>{const s=s=>s.peerId===e&&t.has(s.mid),i=(e,t,i)=>{s(e)&&i.splice(t,1)};Object(f.a)(this.previous,i),Object(f.a)(this.next,i),this.current&&s(this.current)&&(this.current=void 0,this.onEmptied&&this.onEmptied())},this.onHistoryMultiappend=e=>{if(void 0!==this.searchContext.folderId)return;if(!this.loadedAllUp||this.loadPromiseUp)return;const t=e[this.searchContext.peerId];if(!t)return;const s=Array.from(t).sort((e,t)=>e-t),i=this.filterMids(s).map(e=>this.processItem(e)).filter(Boolean);i.length&&(this.current?this.next.push(...i):this.previous.push(...i))},this.onMessageSent=({message:e})=>{this.onHistoryMultiappend({[e.peerId]:new Set([e.mid])})},a.a.addEventListener("history_delete",this.onHistoryDelete),a.a.addEventListener("history_multiappend",this.onHistoryMultiappend),a.a.addEventListener("message_sent",this.onMessageSent),e.isInner||(this.otherSideLoader=new C(Object.assign(Object.assign({},e),{isInner:!0})))}filterMids(e){const t=this.searchContext.isScheduled?i.a.getScheduledMessagesStorage(this.searchContext.peerId):i.a.getMessagesStorage(this.searchContext.peerId);return i.a.filterMessagesByInputFilterFromStorage(this.searchContext.inputFilter._,e,t,e.length)}setSearchContext(e){this.searchContext=e,void 0!==this.searchContext.folderId&&(this.loadedAllUp=!0,void 0===this.searchContext.nextRate&&(this.loadedAllDown=!0)),"inputMessagesFilterChatPhotos"===this.searchContext.inputFilter._&&(this.loadedAllUp=!0),!1===this.searchContext.useSearch&&(this.loadedAllDown=this.loadedAllUp=!0),this.otherSideLoader&&this.otherSideLoader.setSearchContext(e)}reset(){super.reset(),this.searchContext=void 0,this.otherSideLoader&&this.otherSideLoader.reset()}getPrevious(){let e=this.previous;return this.otherSideLoader&&(e=e.concat(this.otherSideLoader.previous)),e}getNext(){let e=this.next;return this.otherSideLoader&&(e=e.concat(this.otherSideLoader.next)),e}getCurrent(){var e;return this.current||(null===(e=this.otherSideLoader)||void 0===e?void 0:e.current)}goToOtherEnd(e){return e>0?this.go(-this.previous.length):this.go(this.next.length)}goRound(e,t){var s;let i;if(null===(s=this.otherSideLoader)||void 0===s?void 0:s.current){if(i=this.otherSideLoader.goUnsafe(e,t),i.item)return i.item;if(!((e=i.leftLength)>0?this.otherSideLoader.next:this.otherSideLoader.previous).length){if(!(e>0?this.otherSideLoader.loadedAllUp:this.otherSideLoader.loadedAllDown))return;if(e>0&&(1===this.otherSideLoader.searchContext.maxId||this.otherSideLoader.loadedAllDown)||e<0&&(0===this.otherSideLoader.searchContext.maxId||this.otherSideLoader.loadedAllUp))return this.otherSideLoader.goToOtherEnd(e);this.otherSideLoader.unsetCurrent(e>0)}}if(i=this.goUnsafe(e,t),!i.item){if(this.loadedAllUp&&this.loadedAllDown)return this.goToOtherEnd(e);this.otherSideLoader&&(e=i.leftLength,i=this.otherSideLoader.goUnsafe(e,t),i.item&&this.unsetCurrent(e>0))}return null==i?void 0:i.item}setLoaded(e,t){var s;const i=super.setLoaded(e,t);if(i&&this.otherSideLoader&&t&&!1!==(null===(s=this.searchContext)||void 0===s?void 0:s.useSearch)){const e=this.loadedAllUp;this.otherSideLoader.setSearchContext(Object.assign(Object.assign({},this.searchContext),{maxId:e?1:0})),this.otherSideLoader.reverse=this.reverse,this.otherSideLoader.setLoaded(e,!0),this.otherSideLoader.load(!e)}return i}cleanup(){this.reset(),a.a.removeEventListener("history_delete",this.onHistoryDelete),a.a.removeEventListener("history_multiappend",this.onHistoryMultiappend),a.a.removeEventListener("message_sent",this.onMessageSent),this.onEmptied=void 0,this.otherSideLoader&&(this.otherSideLoader.cleanup(),this.otherSideLoader=void 0)}}var L=s(84),I=s(82),M=s(35),E=s(60),P=s(67),k=s(59),T=s(7);class x{constructor(e,t,s=!0,i,n=!0,a=!0,o){this.name=e,this.type=t,this.clearable=s,this.autonomous=a,this.onFound=o,this.list=_c.createChatList(),this.container=document.createElement("div"),i&&(this.container.className=i),e&&(this.nameEl=document.createElement("div"),this.nameEl.classList.add("search-group__name"),"string"==typeof e&&this.nameEl.append(Object(T.d)(e)),this.container.append(this.nameEl)),this.container.classList.add("search-group","search-group-"+t),this.container.append(this.list),this.container.style.display="none",n&&_c.setListClickListener(this.list,o,void 0,a)}clear(){this.container.style.display="none",this.clearable&&(this.list.innerHTML="")}setActive(){this.container.style.display=""}toggle(){this.list.childElementCount?this.setActive():this.clear()}}class A{constructor(e,t,s,i){this.container=e,this.searchInput=t,this.searchGroups=s,this.onSearch=i,this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1,this.searchPromise=null,this.searchTimeout=0,this.query="",this.listsContainer=null,this.threadId=0,this.scrollable=new P.b(this.container),this.listsContainer=this.scrollable.container;for(let e in this.searchGroups)this.listsContainer.append(this.searchGroups[e].container);this.searchGroups.messages&&this.scrollable.setVirtualContainer(this.searchGroups.messages.list),this.searchInput.onChange=e=>{this.query=e,this.reset(!1),this.searchMore()},this.scrollable.onScrolledBottom=()=>{this.query.trim()&&(this.searchTimeout||(this.searchTimeout=window.setTimeout(()=>{this.searchMore(),this.searchTimeout=0},0)))}}reset(e=!0){e&&(this.searchInput.value="",this.query="",this.peerId=void 0,this.threadId=0),this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1;for(let e in this.searchGroups)this.searchGroups[e].clear();this.searchPromise=null}beginSearch(e,t=0,s=""){this.peerId=e,this.threadId=t,this.query!==s&&(this.searchInput.inputField.value=s),this.searchInput.input.focus()}searchMore(){if(this.searchPromise)return this.searchPromise;const e=this.query;if(!e.trim())return void(this.onSearch&&this.onSearch(0));if(-1!==this.foundCount&&this.loadedCount>=this.foundCount)return Promise.resolve();const t=this.minMsgId||0;return this.searchPromise=i.a.getSearch({peerId:this.peerId,query:e,inputFilter:{_:"inputMessagesFilterEmpty"},maxId:t,limit:20,threadId:this.threadId}).then(t=>{if(this.searchPromise=null,this.searchInput.value!==e)return;const{count:s,history:i}=t;i.length&&i[0].mid===this.minMsgId&&i.shift();const n=this.searchGroups.messages;i.forEach(t=>{try{const s=this.peerId?t.fromId:t.peerId;_c.addDialogAndSetLastMessage({peerId:s,container:this.scrollable,drawStatus:!1,avatarSize:54,meAsSaved:!1,message:t,query:e})}catch(e){console.error("[appSearch] render search result",e)}}),n.toggle(),this.minMsgId=i.length&&i[i.length-1].mid,-1===this.loadedCount&&(this.loadedCount=0),this.loadedCount+=i.length,-1===this.foundCount&&(this.foundCount=s,n.nameEl&&Object(k.a)(n.nameEl,Object(T.d)(s?"Chat.Search.MessagesFound":"Chat.Search.NoMessagesFound",[s])),this.onSearch&&this.onSearch(this.foundCount))}).catch(e=>{console.error("search error",e),this.searchPromise=null})}}var O=s(65);class j{constructor(e,t){this.prevValue="",this.timeout=0,this.onInput=()=>{if(!this.onChange)return;let e=this.value;e!==this.prevValue&&(this.prevValue=e,clearTimeout(this.timeout),this.timeout=window.setTimeout(()=>{this.onChange(e)},200))},this.onClearClick=()=>{this.value="",this.onChange&&this.onChange(""),this.onClear&&this.onClear()},this.inputField=new O.b({placeholder:e,plainText:!0}),this.container=this.inputField.container,this.container.classList.remove("input-field"),this.container.classList.add("input-search"),this.onChange=t,this.input=this.inputField.input,this.input.classList.add("input-search-input");const s=document.createElement("i");s.classList.add("tgico","tgico-search"),this.clearBtn=document.createElement("i"),this.clearBtn.classList.add("tgico","btn-icon","tgico-close"),this.input.addEventListener("input",this.onInput),this.clearBtn.addEventListener("click",this.onClearClick),this.container.append(s,this.clearBtn)}get value(){return this.inputField.value}set value(e){this.prevValue=e,clearTimeout(this.timeout),this.inputField.value=e}remove(){clearTimeout(this.timeout),this.input.removeEventListener("input",this.onInput),this.clearBtn.removeEventListener("click",this.onClearClick)}}var _=s(140),F=s(86),D=s(15),R=s(83),B=s(58);var N=(e,t={})=>Object(B.a)("btn-icon",Object.assign({icon:e||void 0},t)),U=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class H{constructor(e,t){this._constructor(e,t)}_constructor(e,t=!0){this.slider=e,this.destroyable=t,this.container=document.createElement("div"),this.container.classList.add("tabs-tab","sidebar-slider-item"),this.header=document.createElement("div"),this.header.classList.add("sidebar-header"),this.closeBtn=N("left sidebar-close-button",{noRipple:!0}),this.title=document.createElement("div"),this.title.classList.add("sidebar-header__title"),this.header.append(this.closeBtn,this.title),this.content=document.createElement("div"),this.content.classList.add("sidebar-content"),this.scrollable=new P.b(this.content,void 0,void 0,!0),this.container.append(this.header,this.content),this.slider.addTab(this),this.listenerSetter=new R.a}close(){return this.slider.closeTab(this)}open(...e){return U(this,void 0,void 0,(function*(){if(this.init)try{const e=this.init();this.init=null,e instanceof Promise&&(yield e)}catch(e){console.error("open tab error",e)}this.slider.selectTab(this)}))}init(){}onCloseAfterTimeout(){this.destroyable&&(this.slider.tabs.delete(this),this.container.remove()),this.listenerSetter&&this.listenerSetter.removeAll()}setTitle(e){this.title.innerHTML="",this.title.append(Object(T.d)(e))}}class z extends H{constructor(e){super(e),this.eventListener=new D.a}onCloseAfterTimeout(){return this.eventListener.dispatchEvent("destroy"),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}var V=s(76);class K{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{F.a.findItemByType(this.navigationType)?F.a.back(this.navigationType):this.historyTabIds.length&&this.closeTab(this.historyTabIds[this.historyTabIds.length-1])},this.closeTab=(e,t,s)=>{if(void 0!==e&&this.historyTabIds[this.historyTabIds.length-1]!==e)return!1;const i=this.historyTabIds.pop();this.onCloseTab(i,t,s);const n=this.historyTabIds[this.historyTabIds.length-1];return this._selectTab(void 0!==n?n instanceof H?n.container:n:this.canHideFirst?-1:0,t),!0},Object(w.a)(this,e),this.tabs||(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=Object(_.a)(this.tabsContainer,"navigation",250),this.canHideFirst||this._selectTab(0),Array.from(this.sidebarEl.querySelectorAll(".sidebar-close-button")).forEach(e=>{Object(l.b)(e,this.onCloseBtnClick)})}selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof H?e:this.tabs.get(e);return t&&(t.onOpen&&t.onOpen(),t.onOpenAfterTimeout&&setTimeout(()=>{t.onOpenAfterTimeout()},250)),F.a.pushItem({type:this.navigationType,onPop:e=>(this.closeTab(void 0,e,!0),!0)}),this.historyTabIds.push(e),this._selectTab(e instanceof H?e.container:e),!0}removeTabFromHistory(e){Object(V.a)(this.historyTabIds,e),this.onCloseTab(e,void 0)}sliceTabsUntilTab(e,t){for(let s=this.historyTabIds.length-1;s>=0;--s){const i=this.historyTabIds[s];if(i!==t){if(i instanceof e)break;this.removeTabFromHistory(i)}}}getTab(e){return this.historyTabIds.find(t=>t instanceof e)}isTabExists(e){return!!this.getTab(e)}onCloseTab(e,t,s){s||F.a.removeByType(this.navigationType,!0);const i=e instanceof H?e:this.tabs.get(e);i&&(i.onClose&&i.onClose(),i.onCloseAfterTimeout&&setTimeout(()=>{i.onCloseAfterTimeout()},250))}addTab(e){e.container.parentElement||(this.tabsContainer.append(e.container),e.closeBtn&&e.closeBtn.addEventListener("click",this.onCloseBtnClick))}}var G=s(68),W=s(152);class q{constructor(e){this.container=document.createElement("div"),this.container.classList.add("avatar-edit"),this.canvas=document.createElement("canvas"),this.canvas.classList.add("avatar-edit-canvas"),this.icon=document.createElement("span"),this.icon.classList.add("tgico","tgico-cameraadd"),this.container.append(this.canvas,this.icon),Object(l.b)(this.container,()=>{(new W.a).open(this.canvas,e)})}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}var Q=(e={})=>Object(B.a)("btn-circle btn-corner z-depth-1"+(e.className?" "+e.className:""),e);class $ extends H{constructor(){super(...arguments),this.uploadAvatar=null,this.isGeoChat=!1}init(){this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new q(e=>{this.uploadAvatar=e});const e=new Kn({}),t=document.createElement("div");t.classList.add("input-wrapper"),this.groupNameInputField=new O.b({label:"CreateGroup.NameHolder",maxLength:128}),this.groupLocationInputField=new O.b({label:"ChatLocation",name:"location",canBeEdited:!1}),t.append(this.groupNameInputField.container,this.groupLocationInputField.container),this.groupNameInputField.input.addEventListener("input",()=>{let e=!!this.groupNameInputField.value.length&&!this.groupNameInputField.input.classList.contains("error");this.isGeoChat&&(e=e&&!!this.userLocationCoords&&!!this.userLocationAddress),this.nextBtn.classList.toggle("is-visible",!!e)}),this.nextBtn=Q({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.groupNameInputField.value;if(this.isGeoChat){if(!this.userLocationAddress||!this.userLocationCoords)return;G.a.createChannel({title:e,about:"",geo_point:Object.assign({_:"inputGeoPoint"},this.userLocationCoords),address:this.userLocationAddress,megagroup:!0}).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{G.a.editPhoto(e,t)}),this.peerIds.length&&G.a.inviteToChannel(e,this.peerIds),$n.removeTabFromHistory(this),$n.selectTab(0)})}else this.nextBtn.disabled=!0,G.a.createChat(e,this.peerIds.map(e=>e.toUserId())).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{G.a.editPhoto(e,t)}),$n.removeTabFromHistory(this),$n.selectTab(0)})});const s=new Kn({name:"Members",nameArgs:[this.peerIds.length]}),i=this.list=_c.createChatList({new:!0});s.content.append(i),e.content.append(this.avatarEdit.container,t),this.content.append(this.nextBtn),this.scrollable.append(e.container,s.container)}onCloseAfterTimeout(){this.avatarEdit.clear(),this.uploadAvatar=null,this.groupNameInputField.value="",this.groupLocationInputField.container.classList.add("hide"),this.nextBtn.disabled=!1}open(e,t=!1){this.isGeoChat=t,this.peerIds=e;const s=super.open();return s.then(()=>{t?(this.setTitle("NearbyCreateGroup"),this.groupLocationInputField.container.classList.remove("hide"),this.groupLocationInputField.setValueSilently(T.c.format("Loading",!0)),this.startLocating()):this.groupLocationInputField.container.classList.add("hide"),this.peerIds.forEach(e=>{const{dom:t}=_c.addDialogNew({dialog:e,container:this.list,drawStatus:!1,rippleEnabled:!1,avatarSize:48});t.lastMessageSpan.append(E.a.getUserStatusString(e))})}),s}startLocating(){navigator.geolocation.getCurrentPosition(e=>{this.userLocationCoords={lat:e.coords.latitude,long:e.coords.longitude};let t="https://nominatim.openstreetmap.org/reverse";t+="?lat="+e.coords.latitude,t+="&lon="+e.coords.longitude,t+="&format=json",t+="&addressdetails=1",t+="&accept-language=en",fetch(t).then(e=>e.json()).then(e=>{this.userLocationAddress=e.display_name,this.groupLocationInputField.setValueSilently(e.display_name)})},e=>{e instanceof GeolocationPositionError?this.groupLocationInputField.setValueSilently("Location permission denied. Please retry later."):this.groupLocationInputField.setValueSilently("An error has occurred. Please retry later.")})}}var Y=s(4),X=s(27),J=s(130),Z=s(92),ee=s(61),te=s(77),se=s(28),ie=s(10),ne=s(37),ae=s(2),oe=s(71),re=s(53),le=s(1),ce=s(91),de=s(114),he=s(14),pe=s(112),ue=s(3),ge=s(41),me=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const be=(()=>{try{return ae.g&&+navigator.userAgent.match(/ Version\/(\d+)/)[1]<14}catch(e){return!1}})();const ve=new class{constructor(){if(this.media=new Map,this.scheduled=new Map,this.mediaDetails=new Map,this.waitingMediaForLoad=new Map,this.waitingScheduledMediaForLoad=new Map,this.waitingDocumentsForLoad={},this.playbackRates={voice:1,video:1,audio:1},this.seekBackward=(e,t=this.playingMedia)=>{t&&(t.currentTime=Math.max(0,t.currentTime-(e.seekOffset||10)))},this.seekForward=(e,t=this.playingMedia)=>{t&&(t.currentTime=Math.min(t.duration,t.currentTime+(e.seekOffset||10)))},this.seekTo=(e,t=this.playingMedia)=>{t&&(t.currentTime=e.seekTime)},this.onMediaDocumentLoad=e=>{const t=this.mediaDetails.get(e),s=L.a.getDoc(t.docId);"audio"===s.type&&s.supportsStreaming&&be&&this.handleSafariStreamable(e);const i=ce.a.getCacheContext(s);e.src=i.url,this.playingMedia===e&&(e.playbackRate=this.playbackRate,"audio"===s.type&&(e.loop=this.loop));const n=this.waitingDocumentsForLoad[s.id];n&&(n.delete(e),n.size||delete this.waitingDocumentsForLoad[s.id])},this.onPlay=e=>{const t=e.target,s=this.mediaDetails.get(t),{peerId:i,mid:n}=s,o=this.pip;o&&o.pause();const r=this.getMessageByMedia(t);if(this.playingMedia!==t){this.stop(),this.setMedia(t,r);const e=e=>e.mid===n&&e.peerId===i,s=this.listLoader,a=s.getCurrent();if(!a||!e(a)){const t=s.getPrevious();let a,o=t.findIndex(e);-1!==o?a=-(t.length-o):(o=s.getNext().findIndex(e),-1!==o&&(a=o+1)),-1!==o?a&&this.go(a,!1):this.setTargets({peerId:i,mid:n})}}setTimeout(()=>{this.playingMedia===t&&a.a.dispatchEvent("media_play",this.getPlayingDetails())},0)},this.onPause=e=>{a.a.dispatchEvent("media_pause")},this.onEnded=e=>{if(!e.isTrusted)return;this.onPause(e);const t=this.listLoader;!this.lockedSwitchers&&(this.round||!t.current||t.next.length)&&t.getNext().length&&this.next()||(this.stop(),a.a.dispatchEvent("media_stop"))},this.play=()=>this.toggle(!0),this.pause=()=>this.toggle(!1),this.stop=(e=this.playingMedia)=>{if(!e)return!1;if(e.paused||e.pause(),e.currentTime=0,Object(de.a)(e,"ended"),e===this.playingMedia){const t=this.mediaDetails.get(e);if(null==t?void 0:t.clean){e.src="";const s=t.peerId,i=t.isScheduled?this.scheduled:this.media,n=i.get(s);n&&(n.delete(t.mid),n.size||i.delete(s)),e.remove(),this.mediaDetails.delete(e)}this.playingMedia=void 0,this.playingMediaType=void 0}return!0},this.playItem=e=>{const{peerId:t,mid:s}=e,i=this.searchContext.isScheduled;this.getMedia(t,s,i).play(),setTimeout(()=>{this.resolveWaitingForLoadMedia(t,s,i)},0)},this.go=(e,t)=>{const s=this.listLoader;if(!this.lockedSwitchers&&s)return"audio"===this.playingMediaType?s.goRound(e,t):s.go(e,t)},this.browserPlay=this.bindBrowserCallback(e=>this.toggle(!0,e)),this.browserPause=this.bindBrowserCallback(e=>this.toggle(!1,e)),this.browserStop=this.bindBrowserCallback(e=>this.stop(e)),this.browserSeekBackward=this.bindBrowserCallback((e,t)=>this.seekBackward(t,e)),this.browserSeekForward=this.bindBrowserCallback((e,t)=>this.seekForward(t,e)),this.browserSeekTo=this.bindBrowserCallback((e,t)=>this.seekTo(t,e)),this.browserNext=this.bindBrowserCallback(e=>e||this.next()),this.browserPrevious=this.bindBrowserCallback(e=>e?this.seekToStart(e):this.previous()),this.next=()=>this.go(1),this.previous=()=>{if(!this.seekToStart(this.playingMedia))return this.go(-1)},this.container=document.createElement("div"),this.container.style.cssText="display: none;",document.body.append(this.container),navigator.mediaSession){const e={play:this.browserPlay,pause:this.browserPause,stop:this.browserStop,seekbackward:this.browserSeekBackward,seekforward:this.browserSeekForward,seekto:this.browserSeekTo,previoustrack:this.browserPrevious,nexttrack:this.browserNext};for(const t in e)try{navigator.mediaSession.setActionHandler(t,e[t])}catch(e){console.warn("MediaSession action is not supported:",t)}}a.a.addEventListener("document_downloaded",e=>{const t=this.waitingDocumentsForLoad[e.id];if(t)for(const e of t)this.onMediaDocumentLoad(e)});const e={};["volume","muted","playbackRate","loop","round"].forEach(t=>{const s="_"+t;e[t]={get:()=>this[s],set:e=>{this[s]!==e&&(this[s]=e,!this.playingMedia||"loop"===t&&"audio"!==this.playingMediaType||"round"===t||(this.playingMedia[t]=e),"playbackRate"===t&&void 0!==this.playingMediaType&&(this.playbackRates[this.playingMediaType]=e),this.dispatchPlaybackParams())}}}),Object.defineProperties(this,e)}dispatchPlaybackParams(){a.a.dispatchEvent("media_playback_params",this.getPlaybackParams())}getPlaybackParams(){const{volume:e,muted:t,playbackRate:s,playbackRates:i,loop:n,round:a}=this;return{volume:e,muted:t,playbackRate:s,playbackRates:i,loop:n,round:a}}setPlaybackParams(e){this.playbackRates=e.playbackRates,this._volume=e.volume,this._muted=e.muted,this._playbackRate=e.playbackRate,this._loop=e.loop,this._round=e.round}addMedia(e,t,s){const{peerId:n,mid:o}=e,r=!!e.pFlags.is_scheduled?this.scheduled:this.media;let l=r.get(e.peerId);l||r.set(e.peerId,l=new Map);let c=l.get(o);if(c)return c;const d=i.a.getMediaFromMessage(e);l.set(o,c=document.createElement("round"===d.type||"video"===d.type?"video":"audio")),"round"===d.type&&c.setAttribute("playsinline","true");const h={peerId:n,mid:o,docId:d.id,clean:s,isScheduled:e.pFlags.is_scheduled};this.mediaDetails.set(c,h),c.volume=1,this.container.append(c),c.addEventListener("play",this.onPlay),c.addEventListener("pause",this.onPause),c.addEventListener("ended",this.onEnded),"audio"!==d.type&&(null==e?void 0:e.pFlags.media_unread)&&e.fromId!==a.a.myId&&c.addEventListener("timeupdate",()=>{i.a.readMessages(n,[o])},{once:!0});const p=Object(ie.a)();if(t)p.resolve();else{const t=e.pFlags.is_scheduled?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad;let s=t.get(n);s||t.set(n,s=new Map),s.set(o,p)}return p.then(()=>{const e=ce.a.getCacheContext(d);if(d.supportsStreaming||e.url)this.onMediaDocumentLoad(c);else{let e=this.waitingDocumentsForLoad[d.id];e||(e=this.waitingDocumentsForLoad[d.id]=new Set),e.add(c),L.a.downloadDoc(d)}}),c}getMedia(e,t,s){const i=(s?this.scheduled:this.media).get(e);return null==i?void 0:i.get(t)}handleSafariStreamable(e){e.addEventListener("play",()=>{const t=e.currentTime;e.addEventListener("progress",()=>{e.currentTime=e.duration-1,e.addEventListener("progress",()=>{e.currentTime=t,e.paused||e.play()},{once:!0})},{once:!0})})}resolveWaitingForLoadMedia(e,t,s){const i=s?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad,n=i.get(e);if(!n)return;const a=n.get(t);a&&(a.resolve(),n.delete(t),n.size||i.delete(e))}isSafariBuffering(e){return!!e.safariBuffering}setSafariBuffering(e,t){e.safariBuffering=t}setNewMediadata(e,t=this.playingMedia){var s,n;return me(this,void 0,void 0,(function*(){if(document.pictureInPictureElement)return;yield Object(pe.e)(t,void 0,!1);const a=i.a.getMediaFromMessage(e),l=[],c="voice"===a.type||"round"===a.type;let h="",p="";if(null===(s=a.thumbs)||void 0===s?void 0:s.length){const s=a.thumbs[a.thumbs.length-1];if(!s.bytes){const i=ce.a.getCacheContext(a,s.type);if(i.url)l.push({src:i.url,sizes:`${s.w}x${s.h}`,type:"image/jpeg"});else{r.a.preloadPhoto(a,s).then(()=>{this.playingMedia===t&&i.url&&this.setNewMediadata(e)})}}}else if(c){const s=e.fromId||e.peerId,i=o.a.getPeerPhoto(s);if(i){const n=d.a.loadAvatar(s,i,"photo_small");if(n.cached){const e=yield n.loadPromise;l.push({src:e,sizes:"160x160",type:"image/jpeg"})}else n.loadPromise.then(s=>{this.playingMedia===t&&s&&this.setNewMediadata(e)})}h=o.a.getPeerTitle(s,!0,!1),p=T.c.format("voice"===a.type?"AttachAudio":"AttachRound",!0)}if(!c){const e=a.attributes.find(e=>"documentAttributeAudio"===e._);h=null!==(n=null==e?void 0:e.title)&&void 0!==n?n:a.file_name,p=null==e?void 0:e.performer}l.length||(ae.b?he.a?l.push({src:"assets/img/apple-touch-icon-precomposed.png",sizes:"180x180",type:"image/png"}):l.push({src:"assets/img/apple-touch-icon.png",sizes:"180x180",type:"image/png"}):[72,96,144,192,256,384,512].forEach(e=>{const t=`${e}x${e}`;l.push({src:`assets/img/android-chrome-${t}.png`,sizes:t,type:"image/png"})}));const u=new MediaMetadata({title:h,artist:p,artwork:l});navigator.mediaSession.metadata=u}))}setCurrentMediadata(){const{playingMedia:e}=this;if(!e)return;const t=this.getMessageByMedia(e);this.setNewMediadata(t,e)}getMessageByMedia(e){const t=this.mediaDetails.get(e),{peerId:s,mid:n}=t;return t.isScheduled?i.a.getScheduledMessageByPeer(s,n):i.a.getMessageByPeer(s,n)}getPlayingDetails(){const{playingMedia:e}=this;if(!e)return;const t=this.getMessageByMedia(e);return{doc:i.a.getMediaFromMessage(t),message:t,media:e,playbackParams:this.getPlaybackParams()}}toggle(e,t=this.playingMedia){return!!t&&(void 0===e&&(e=t.paused),t.paused===e&&(e?t.play():t.pause(),!0))}bindBrowserCallback(e){return t=>{e(this.pip,t)}}seekToStart(e){return(null==e?void 0:e.currentTime)>5&&(e.currentTime=0,this.toggle(!0,e),!0)}willBePlayed(e){this.willBePlayedMedia=e}setSearchContext(e){return!Object(ge.a)(this.searchContext,e)&&(this.searchContext=Object(ue.a)(e),!0)}getSearchContext(){return this.searchContext}setTargets(e,t,s){let i=this.listLoader;i?i.reset():i=this.listLoader=new C({loadCount:10,loadWhenLeft:5,processItem:e=>(this.addMedia(e,!1),{peerId:e.peerId,mid:e.mid}),onJump:(e,t)=>{this.playItem(e)},onEmptied:()=>{a.a.dispatchEvent("media_stop"),this.stop()}});const n=void 0===this.searchContext.folderId;t?i.setTargets(t,s,n):i.reverse=n,i.setSearchContext(this.searchContext),i.current=e,i.load(!0),i.load(!1)}getPlaybackMediaTypeFromMessage(e){const t=i.a.getMediaFromMessage(e);let s="audio";return(null==t?void 0:t.type)&&("voice"===t.type||"round"===t.type?s="voice":"video"===t.type&&(s="video")),s}setMedia(e,t){const s=this.getPlaybackMediaTypeFromMessage(t);this._playbackRate=this.playbackRates[s],this.playingMedia=e,this.playingMediaType=s,this.playingMedia.volume=this.volume,this.playingMedia.muted=this.muted,this.playingMedia.playbackRate=this.playbackRate,"audio"===s&&(this.playingMedia.loop=this.loop),"mediaSession"in navigator&&this.setNewMediadata(t)}setSingleMedia(e,t){const s=this.playingMedia,i=this.pause();let n;return e&&(n=()=>{const e=this.pip;e&&e.pause()},e.paused||n(),e.addEventListener("play",n)),this.willBePlayed(void 0),e?this.setMedia(e,t):this.playingMedia=void 0,this.toggleSwitchers(!1),(t=i)=>{this.toggleSwitchers(!0),s&&(this.mediaDetails.get(s)?this.setMedia(s,this.getMessageByMedia(s)):this.next()||this.previous()),this.playingMedia===e&&(this.playingMedia=void 0,this.playingMediaType=void 0),e&&e.removeEventListener("play",n),t&&this.play()}}toggleSwitchers(e){this.lockedSwitchers=!e}setPictureInPicture(e){this.pip=e;const t=new R.a;t.add(e)("leavepictureinpicture",()=>{this.pip===e&&(this.pip=void 0,t.removeAll())},{once:!0}),t.add(e)("play",t=>{this.playingMedia!==e&&this.pause()})}};le.a.appMediaPlaybackController=ve;var fe=ve,ye=s(124),we=s(137),Se=s(40),Ce=s(34),Le=s(36);function Ie(e){return function(e,t){let s,i=!1;return(...n)=>{s=n,i||(i=!0,e(()=>{i=!1,t(...s)}))}}(Le.b,e)}var Me=s(20);function Ee(e,t=2){if(0===e)return Object(T.d)("FileSize.B",[0]);const s=t<0?0:t,i=Math.floor(Math.log(e)/Math.log(1024));return Object(T.d)(["FileSize.B","FileSize.KB","FileSize.MB","FileSize.GB"][i],[parseFloat((e/Math.pow(1024,i)).toFixed(s))])}var Pe=s(115),ke=s(104);function Te(e,t=!1){const s=parseInt(e+"",10),i=Math.floor(s/3600);let n=Math.floor((s-3600*i)/60),a=s-3600*i-60*n;return i&&(t=!0),n<10&&(n=t?"0"+n:n),a<10&&(a="0"+a),(i?i+":":"")+n+":"+a}function xe(e,t,s,i){const n=e=>{s({x:e.pageX,y:e.pageY,event:e})},a=t=>{document.removeEventListener("mousemove",n),e.addEventListener("mousedown",o,{once:!0}),i&&i({x:t.pageX,y:t.pageY,event:t})},o=s=>{0===s.button?(t({x:s.pageX,y:s.pageY,event:s}),n(s),document.addEventListener("mousemove",n),document.addEventListener("mouseup",a,{once:!0})):e.addEventListener("mousedown",o,{once:!0})};e.addEventListener("mousedown",o,{once:!0});const r=e=>{e.preventDefault(),s({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e})},l=t=>{document.removeEventListener("touchmove",r),e.addEventListener("touchstart",c,{passive:!1,once:!0}),i&&i({x:t.touches[0].clientX,y:t.touches[0].clientY,isTouch:!0,event:t})},c=e=>{t({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e}),r(e),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",l,{passive:!1,once:!0})};return e.addEventListener("touchstart",c,{passive:!1,once:!0}),()=>{e.removeEventListener("mousedown",o),document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",a),e.removeEventListener("touchstart",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",l)}}class Ae{constructor(e,t=0){this.mousedown=!1,this.events={},this.withTransition=!1,this.useTransform=!1,this.vertical=!1,this.onMouseMove=e=>{this.scrub(e)},this.onMouseDown=e=>{var t;this.rect=this.container.getBoundingClientRect(),this.mousedown=!0,this.scrub(e),this.container.classList.add("is-focused"),(null===(t=this.events)||void 0===t?void 0:t.onMouseDown)&&this.events.onMouseDown(e)},this.onMouseUp=e=>{var t;this.mousedown=!1,this.container.classList.remove("is-focused"),(null===(t=this.events)||void 0===t?void 0:t.onMouseUp)&&this.events.onMouseUp(e)},this.onInput=()=>{var e;const t=+this.seek.value;this.setFilled(t),(null===(e=this.events)||void 0===e?void 0:e.onScrub)&&this.events.onScrub(t)},Object(w.a)(this,e),this.container=document.createElement("div"),this.container.classList.add("progress-line"),this.useTransform?this.container.classList.add("use-transform"):this.withTransition&&this.container.classList.add("with-transition"),this.filled=document.createElement("div"),this.filled.classList.add("progress-line__filled");const s=this.seek=document.createElement("input");s.classList.add("progress-line__seek"),s.type="range",s.step=""+this.step,s.min=""+this.min,s.max=""+this.max,s.value=""+t,t&&this.setProgress(t);const i=""+this.step,n=i.indexOf(".");this.decimals=-1===n?0:i.length-n-1,this.container.append(this.filled,s)}get value(){return+this.seek.value}setHandlers(e){this.events=e}setListeners(){this.seek.addEventListener("input",this.onInput),this._removeListeners=xe(this.container,this.onMouseDown,this.onMouseMove,this.onMouseUp)}setProgress(e){this.seek.value=""+e,this.setFilled(+this.seek.value)}addProgress(e){this.seek.value=""+(+this.seek.value+e),this.setFilled(+this.seek.value)}setFilled(e){let t=(e-this.min)/(this.max-this.min);t=Object(ke.a)(t,0,1),this.useTransform?this.filled.style.transform=`scaleX(${t})`:this.filled.style.width=100*t+"%"}scrub(e){var t;const s=this.vertical?this.rect.height:this.rect.width,i=Object(ke.a)(this.vertical?-(e.y-this.rect.bottom):e.x-this.rect.left,0,s);let n=this.min+i/s*(this.max-this.min);return n-this.min<(this.max-this.min)/2&&(n-=this.step/10),n=+n.toFixed(this.decimals),n=Object(ke.a)(n,this.min,this.max),this.setProgress(n),(null===(t=this.events)||void 0===t?void 0:t.onScrub)&&this.events.onScrub(n),n}removeListeners(){this._removeListeners&&(this._removeListeners(),this._removeListeners=null),this.seek.removeEventListener("input",this.onInput),this.events={}}}class Oe extends Ae{constructor(e,t,s,i){super({step:1e3/60/1e3,min:0,max:1,withTransition:s,useTransform:i},0),this.progressRAF=0,this.onLoadedData=()=>{this.max=this.media.duration,this.seek.setAttribute("max",""+this.max)},this.onEnded=()=>{this.setProgress()},this.onPlay=()=>{let e=()=>{this.setProgress(),this.progressRAF=this.media.paused?0:window.requestAnimationFrame(e)};this.progressRAF&&window.cancelAnimationFrame(this.progressRAF),this.streamable&&this.setLoadProgress(),this.progressRAF=window.requestAnimationFrame(e)},this.onTimeUpdate=()=>{this.media.paused&&(this.setProgress(),this.streamable&&this.setLoadProgress())},this.onProgress=e=>{this.setLoadProgress()},e&&this.setMedia(e,t)}setMedia(e,t=!1){this.media&&this.removeListeners(),t&&!this.filledLoad?(this.filledLoad=document.createElement("div"),this.filledLoad.classList.add("progress-line__filled","progress-line__loaded"),this.container.prepend(this.filledLoad)):this.filledLoad&&this.filledLoad.classList.toggle("hide",!t),this.media=e,this.streamable=t,(!e.paused||e.currentTime>0)&&this.onPlay();let s=!1;this.setSeekMax(),this.setListeners(),this.setHandlers({onMouseDown:()=>{s=!this.media.paused,s&&this.media.pause()},onMouseUp:e=>{s&&this.media.play()}})}scrub(e){const t=super.scrub(e);return this.media.currentTime=t,t}setLoadProgress(){if(fe.isSafariBuffering(this.media))return;const e=this.media.buffered,t=e.length,s=this.media.currentTime;let i=0,n=0;for(let a=0;a<t;++a){const t=e.start(a);s>=t&&t>=i&&(i=t,n=e.end(a))}const a=this.media.duration?n/this.media.duration:0;this.filledLoad.style.width=100*a+"%"}setSeekMax(){this.max=this.media.duration||0,this.max>0?this.onLoadedData():this.media.addEventListener("loadeddata",this.onLoadedData)}setProgress(){if(fe.isSafariBuffering(this.media))return;const e=this.media.currentTime;super.setProgress(e)}setListeners(){super.setListeners(),this.media.addEventListener("ended",this.onEnded),this.media.addEventListener("play",this.onPlay),this.media.addEventListener("timeupdate",this.onTimeUpdate),this.streamable&&this.media.addEventListener("progress",this.onProgress)}removeListeners(){super.removeListeners(),this.media&&(this.media.removeEventListener("loadeddata",this.onLoadedData),this.media.removeEventListener("ended",this.onEnded),this.media.removeEventListener("play",this.onPlay),this.media.removeEventListener("timeupdate",this.onTimeUpdate),this.streamable&&this.media.removeEventListener("progress",this.onProgress)),this.progressRAF&&(window.cancelAnimationFrame(this.progressRAF),this.progressRAF=0)}}function je(e){e.classList.add("is-voice");const t=e.message,s=i.a.getMediaFromMessage(t);t.pFlags.out&&e.classList.add("is-out");let n=s.attributes.find(e=>"documentAttributeAudio"===e._).waveform||new Uint8Array([]);n=function(e){e instanceof Uint8Array||(e=new Uint8Array(e));const t=8*e.length/5|0;if(!t)return new Uint8Array([]);let s;try{const i=new DataView(e.buffer);s=new Uint8Array(t);for(let e=0;e<t;e++){const t=5*e/8|0,n=5*e%8,a=i.getUint16(t,!0);s[e]=a>>n&31}}catch(e){s=new Uint8Array([])}return s}(n.slice(0,63));const{svg:a,container:o,availW:r}=function(e,t){const s=b.b.isMobile?16:23,i=b.b.isMobile?152:190,n=b.b.isMobile?190:256,a=Object(ke.a)(t/60*n,i,n),o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.classList.add("audio-waveform-bars"),o.setAttributeNS(null,"width",""+a),o.setAttributeNS(null,"height",""+s),o.setAttributeNS(null,"viewBox",`0 0 ${a} ${s}`);const r=Math.max(...e),l=e.length?e.length:100,c=Math.min(a/4|0,l);let d=0;const h=s-4;let p="";for(let t=0,i=0,n=0;t<l;++t){const a=e[t]||0;if(n+c>=l){n=n+c-l,n<(c+1)/2&&d<a&&(d=a);const e=Math.max((d*h+(r+1)/2)/(r+1),4);p+=`\n <rect x="${i}" y="${s-e}" width="2" height="${e}" rx="1" ry="1"></rect>\n `,i+=4,d=n<(c+1)/2?0:a}else d<a&&(d=a),n+=c}const u=document.createElement("div");return u.classList.add("audio-waveform"),u.append(o),o.insertAdjacentHTML("beforeend",p),{svg:o,container:u,availW:a}}(n,s.duration),d=o.cloneNode(!0);d.classList.add("audio-waveform-fake"),o.classList.add("audio-waveform-background");const h=document.createElement("div");h.classList.add("audio-waveform-container"),h.append(o,d);const p=document.createElement("div");p.classList.add("audio-time"),e.append(h,p);let u=a;return()=>{let t=e.audio;const s=()=>{d.style.width=t.currentTime/t.duration*100+"%"};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&s();const i=Ie(s);return e.addAudioListener("timeupdate",i),e.addAudioListener("ended",i),e.addAudioListener("play",()=>{Object(Pe.b)(()=>!!t&&(s(),!t.paused),e)}),e.readyPromise.then(()=>{let e=!1,s=!1;function i(e){let s;if(e instanceof MouseEvent)s=e.offsetX;else{const t=e.target.getBoundingClientRect();s=e.targetTouches[0].pageX-t.left}const i=s/r*t.duration;t.currentTime=i}u.addEventListener("mouseleave",i=>{e&&(t.play(),e=!1),s=!1}),u.addEventListener("mousemove",t=>{s=!0,e&&i(t)}),u.addEventListener("mousedown",s=>{s.preventDefault(),0===s.button&&(t.paused||t.pause(),i(s),e=!0)}),u.addEventListener("mouseup",i=>{s&&e&&(t.play(),e=!1)}),Object(l.b)(u,e=>{Object(c.a)(e),t.paused||i(e)})},Se.a),()=>{u.remove(),u=null,t=null}}}function _e(e=!0){const t=new ye.a({cancelable:!0,tryAgainOnFail:e});return t.construct(),e||(t.circle.setAttributeNS(null,"r","23"),t.totalLength=143.58203125),t}a.a.addEventListener("messages_media_read",({mids:e,peerId:t})=>{e.forEach(e=>{const s=`[data-mid="${e}"][data-peer-id="${t}"]`;Array.from(document.querySelectorAll(`audio-element.is-unread${s}, .media-round.is-unread${s}`)).forEach(e=>{e.classList.remove("is-unread")})})});const Fe=(e,t)=>{let s,i;const n=!e.classList.contains("search-super-item"),a=Object(Ce.a)(e,n?"bubbles-inner":"tabs-tab");if(a){const t=':not([data-is-outgoing="1"])',o=".audio:not(.is-voice)"+t;let r;if(r=e.matches(o)?[o]:[".audio.is-voice"+t,".media-round"+t],n){const e=".bubble:not(.webpage) ";r=r.map(t=>e+t)}const l=r.join(", "),c=Array.from(a.querySelectorAll(l)),d=c.indexOf(e),h=c.map(e=>({peerId:e.dataset.peerId.toPeerId(),mid:+e.dataset.mid}));s=h.slice(0,d),i=h.slice(d+1)}return(i.length&&i[0].mid<t||s.length&&s[s.length-1].mid>t)&&([s,i]=[i.reverse(),s.reverse()]),[s,i]};class De extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new R.a}render(){var e,t;this.classList.add("audio"),this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const s=i.a.getMediaFromMessage(this.message),n="voice"===s.type,a=!this.voiceAsMusic&&n,o=this.message.pFlags.is_outgoing,r=o&&this.preloader,d=Te(0|s.duration);this.innerHTML='\n <div class="audio-toggle audio-ico">\n <div class="audio-play-icon">\n <div class="part one" x="0" y="0" fill="#fff"></div>\n <div class="part two" x="0" y="0" fill="#fff"></div>\n </div>\n </div>';const h=this.firstElementChild,p=document.createElement("div");p.classList.add("audio-download");"audio"!==s.type&&this.message&&this.message.pFlags.media_unread&&this.classList.add("is-unread"),r&&(this.classList.add("is-outgoing"),this.append(p));const u=a?je(this):function(e){var t;const s=e.withTime,n=e.message,a=i.a.getMediaFromMessage(n),o="voice"===a.type||"round"===a.type,r=document.createElement("div");r.classList.add("audio-description");const l=a.attributes.find(e=>"documentAttributeAudio"===e._);if(!o){const t=[];(null==l?void 0:l.performer)&&t.push(X.b.wrapEmojiText(l.performer)),s?t.push(Object(ne.d)(n.date)):t.length||t.push(Ee(a.size)),e.showSender&&t.push(i.a.wrapSenderToPeer(n)),r.append(...Object(T.g)(t," • "))}e.insertAdjacentHTML("beforeend",'\n <div class="audio-details">\n <div class="audio-title"></div>\n <div class="audio-subtitle"><div class="audio-time"></div></div>\n </div>');const c=e.querySelector(".audio-title"),d=new we.a;d.dataset.fontWeight=e.dataset.fontWeight,d.dataset.sizeType=e.dataset.sizeType,o?d.append(i.a.wrapSenderToPeer(n)):Object(m.a)(d,X.b.wrapEmojiText(null!==(t=null==l?void 0:l.title)&&void 0!==t?t:a.file_name)),c.append(d),e.showSender&&c.append(i.a.wrapSentTime(n));const h=e.querySelector(".audio-subtitle");return h.append(r),()=>{let t=!1,s=new Oe(e.audio,a.supportsStreaming);e.addAudioListener("ended",()=>{e.classList.remove("audio-show-progress"),h.lastChild.replaceWith(r),t=!1});const i=()=>{t||(e.classList.add("audio-show-progress"),t=!0,s&&h.lastChild.replaceWith(s.container))};return e.addAudioListener("play",i),(!e.audio.paused||e.audio.currentTime>0)&&i(),()=>{s.removeListeners(),s.container.remove(),s=null}}}(this),g=this.querySelector(".audio-time");g.innerHTML=d;const b=this.onLoad=e=>{this.onLoad=void 0;const t=this.audio=fe.addMedia(this.message,e),s=this.readyPromise=Object(ie.a)();this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?s.resolve():this.addAudioListener("canplay",()=>s.resolve(),{once:!0}),this.onTypeDisconnect=u();const i=()=>Te(0|t.currentTime)+(a?" / "+d:""),n=()=>{g.innerText=i(),h.classList.toggle("playing",!t.paused)};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&n();const o=(e,s=t.paused)=>{if(e&&Object(c.a)(e),s){const e=!!this.searchContext;if(fe.setSearchContext(this.searchContext||{peerId:Me.c,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,s]=e?Fe(this,this.message.mid):[];fe.setTargets({peerId:this.message.peerId,mid:this.message.mid},t,s)}t.play().catch(()=>{})}else t.pause()};return Object(l.b)(h,e=>o(e),{listenerSetter:this.listenerSetter}),this.addAudioListener("ended",()=>{h.classList.remove("playing"),g.innerText=d}),this.addAudioListener("timeupdate",()=>{!t.currentTime&&t.paused||fe.isSafariBuffering(t)||(g.innerText=i())}),this.addAudioListener("pause",()=>{h.classList.remove("playing")}),this.addAudioListener("play",n),o};if(null===(e=s.thumbs)||void 0===e?void 0:e.length){const e=[],t=Ps({photo:s,message:null,container:h,boxWidth:48,boxHeight:48,loadPromises:this.loadPromises,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue});h.style.width=h.style.height="",t.images.thumb&&e.push(t.images.thumb),t.images.full&&e.push(t.images.full),this.classList.add("audio-with-thumb"),e.forEach(e=>e.classList.add("audio-thumb"))}if(o)r&&(this.dataset.isOutgoing="1",this.preloader.attach(p,!1));else{let e=this.preloader;const i="audio"!==s.type;b(i);const n=t=>{if(this.audio.src)return;fe.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid,this.message.pFlags.is_scheduled);const i=()=>{t&&(fe.willBePlayed(this.audio),ae.g&&!this.audio.autoplay&&(this.audio.autoplay=!0))};if(i(),!e)if(s.supportsStreaming){let e;this.classList.add("corner-download");const t=()=>{const t=_e(!1),s=Object(ie.a)();s.notifyAll({done:75,total:100}),s.catch(()=>{this.audio.pause(),fe.willBePlayed(void 0)}),s.cancel=()=>{s.cancel=Se.a;const e=new Error;e.type="CANCELED",s.reject(e)},t.attach(p,!1,s),e=this.addAudioListener("pause",()=>{s.cancel()},{once:!0}),i()},s=this.addAudioListener("play",t);this.readyPromise.then(()=>{this.listenerSetter.remove(s),this.listenerSetter.remove(e)})}else{e=_e(),t||(this.readyPromise=Object(ie.a)());const n=()=>{i();const n=L.a.downloadDoc(s);return t||n.then(()=>{this.readyPromise.resolve()}),e.attach(p,!1,n),{download:n}};e.setDownloadFunction(n),n()}this.classList.contains("corner-download")?h.append(p):this.append(p),this.classList.add("downloading"),this.readyPromise.then(()=>{this.classList.remove("downloading"),p.classList.add("downloaded"),setTimeout(()=>{p.remove()},200),fe.willBePlayedMedia===this.audio&&(this.audio.play(),fe.willBePlayed(void 0))})};(null===(t=this.audio)||void 0===t?void 0:t.src)||(i?n(!1):Object(l.b)(h,()=>{n(!0)},{once:!0,capture:!0,passive:!1,listenerSetter:this.listenerSetter}))}}get addAudioListener(){return this.listenerSetter.add(this.audio)}disconnectedCallback(){this.isConnected||(this.onTypeDisconnect&&(this.onTypeDisconnect(),this.onTypeDisconnect=null),this.readyPromise&&this.readyPromise.reject(),this.listenerSetter.removeAll(),this.listenerSetter=null,this.preloader=null)}}customElements.define("audio-element",De);var Re=s(133);class Be{constructor(e,t){this.className=e,this.fill=t,this.container=document.createElement("div"),this.container.className=e,this.border=document.createElement("div"),this.border.classList.add(e+"-border"),this.content=document.createElement("div"),this.content.classList.add(e+"-content"),this.title=document.createElement("div"),this.title.classList.add(e+"-title"),this.title.setAttribute("dir","auto"),this.subtitle=document.createElement("div"),this.subtitle.classList.add(e+"-subtitle"),this.subtitle.setAttribute("dir","auto"),this.content.append(this.title,this.subtitle),this.container.append(this.border,this.content)}}function Ne(e){var t,s;let{title:n,titleEl:a,subtitle:o,subtitleEl:l,mediaEl:c,message:d,loadPromises:h}=e;void 0!==n&&("string"==typeof n&&(n=Object(Re.a)(n,140),n=X.a.wrapEmojiText(n)),Object(k.a)(a,n)),h||(h=[]);let p=d&&d.media,u=!1,g=!1;const m=c?Array.from(c.children).slice():[];let b;if(p&&c){if(l.textContent="",l.append(i.a.wrapMessageForReply(d,void 0,void 0,void 0,void 0,!0)),p.webpage&&(p=p.webpage),p.photo||p.document&&(null===(t=p.document.thumbs)||void 0===t?void 0:t.length)){b=nc.chat.bubbles.getMiddleware();const e=nc.chat.bubbles.lazyLoadQueue;if("sticker"===(null===(s=p.document)||void 0===s?void 0:s.type))u=!0,xs({doc:p.document,div:c,lazyLoadQueue:e,group:tc,width:32,height:32,middleware:b,loadPromises:h});else{const t=p.photo||p.document;g="round"===t.type;try{Ps({photo:t,container:c,boxWidth:32,boxHeight:32,size:r.a.choosePhotoSize(t,32,32),middleware:b,lazyLoadQueue:e,noBlur:!0,withoutPreloader:!0,loadPromises:h}),u=!0}catch(e){}}}}else d?(l.textContent="",l.append(i.a.wrapMessageForReply(d))):("string"==typeof o&&(o=Object(Re.a)(o,140),o=X.a.wrapEmojiText(o)),Object(k.a)(l,o||""));return Promise.all(h).then(()=>{b&&!b()||(m.forEach(e=>e.remove()),c&&c.classList.toggle("is-round",g))}),u}class Ue extends Be{constructor(e){super(e,(e,t="",s)=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const i=Ne({title:e,titleEl:this.title,subtitle:t,subtitleEl:this.subtitle,mediaEl:this.mediaEl,message:s});this.container.classList.toggle("is-media",i),i?this.content.prepend(this.mediaEl):this.mediaEl.remove()}),this.className=e}}function He(e,t){return e.reduce((e,t)=>e+t,t)}const ze=0,Ve=1,Ke=2,Ge=4,We=8;class qe{constructor(e,t,s,i,n=t){this.sizes=e,this.maxWidth=t,this.minWidth=s,this.spacing=i,this.maxHeight=n,this.count=e.length,this.ratios=qe.countRatios(e),this.proportions=qe.countProportions(this.ratios),this.averageRatio=He(this.ratios,1)/this.count,this.maxSizeRatio=t/this.maxHeight}layout(){return this.count?this.count>=5||this.ratios.find(e=>e>2)?new Qe(this.ratios,this.averageRatio,this.maxWidth,this.minWidth,this.spacing).layout():2===this.count?this.layoutTwo():3===this.count?this.layoutThree():this.layoutFour():[]}layoutTwo(){return"ww"===this.proportions&&this.averageRatio>1.4*this.maxSizeRatio&&this.ratios[1]-this.ratios[0]<.2?this.layoutTwoTopBottom():"ww"===this.proportions||"qq"===this.proportions?this.layoutTwoLeftRightEqual():this.layoutTwoLeftRight()}layoutThree(){return"n"===this.proportions[0]?this.layoutThreeLeftAndOther():this.layoutThreeTopAndOther()}layoutFour(){return"w"===this.proportions[0]?this.layoutFourTopAndOther():this.layoutFourLeftAndOther()}layoutTwoTopBottom(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],(this.maxHeight-this.spacing)/2)));return[{geometry:{x:0,y:0,width:e,height:t},sides:We|Ve|Ke},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:We|Ge|Ke}]}layoutTwoLeftRightEqual(){const e=(this.maxWidth-this.spacing)/2,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],1*this.maxHeight)));return[{geometry:{x:0,y:0,width:e,height:t},sides:Ve|We|Ge},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:Ve|Ke|Ge}]}layoutTwoLeftRight(){const e=Math.round(1.5*this.minWidth),t=Math.min(Math.round(Math.max(.4*(this.maxWidth-this.spacing),(this.maxWidth-this.spacing)/this.ratios[0]/(1/this.ratios[0]+1/this.ratios[1]))),this.maxWidth-this.spacing-e),s=this.maxWidth-t-this.spacing,i=Math.min(this.maxHeight,Math.round(Math.min(s/this.ratios[0],t/this.ratios[1])));return[{geometry:{x:0,y:0,width:s,height:i},sides:Ve|We|Ge},{geometry:{x:s+this.spacing,y:0,width:t,height:i},sides:Ve|Ke|Ge}]}layoutThreeLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min((this.maxHeight-this.spacing)/2,this.ratios[1]*(this.maxWidth-this.spacing)/(this.ratios[2]+this.ratios[1]))),s=e-t-this.spacing,i=Math.max(this.minWidth,Math.round(Math.min((this.maxWidth-this.spacing)/2,Math.min(t*this.ratios[2],s*this.ratios[1])))),n=Math.min(Math.round(e*this.ratios[0]),this.maxWidth-this.spacing-i);return[{geometry:{x:0,y:0,width:n,height:e},sides:Ve|We|Ge},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:Ve|Ke},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:Ge|Ke}]}layoutThreeTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),s=(this.maxWidth-this.spacing)/2,i=Math.min(this.maxHeight-t-this.spacing,Math.round(Math.min(s/this.ratios[1],s/this.ratios[2]))),n=e-s-this.spacing;return[{geometry:{x:0,y:0,width:e,height:t},sides:We|Ve|Ke},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:Ge|We},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:Ge|Ke}]}layoutFourTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),s=Math.round((this.maxWidth-2*this.spacing)/(this.ratios[1]+this.ratios[2]+this.ratios[3])),i=Math.max(this.minWidth,Math.round(Math.min(.4*(this.maxWidth-2*this.spacing),s*this.ratios[1]))),n=Math.round(Math.max(Math.max(1*this.minWidth,.33*(this.maxWidth-2*this.spacing)),s*this.ratios[3])),a=e-i-n-2*this.spacing,o=Math.min(this.maxHeight-t-this.spacing,s);return[{geometry:{x:0,y:0,width:e,height:t},sides:We|Ve|Ke},{geometry:{x:0,y:t+this.spacing,width:i,height:o},sides:Ge|We},{geometry:{x:i+this.spacing,y:t+this.spacing,width:a,height:o},sides:Ge},{geometry:{x:i+this.spacing+a+this.spacing,y:t+this.spacing,width:n,height:o},sides:Ke|Ge}]}layoutFourLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min(e*this.ratios[0],.6*(this.maxWidth-this.spacing))),s=Math.round((this.maxHeight-2*this.spacing)/(1/this.ratios[1]+1/this.ratios[2]+1/this.ratios[3])),i=Math.round(s/this.ratios[1]),n=Math.round(s/this.ratios[2]),a=e-i-n-2*this.spacing,o=Math.max(this.minWidth,Math.min(this.maxWidth-t-this.spacing,s));return[{geometry:{x:0,y:0,width:t,height:e},sides:Ve|We|Ge},{geometry:{x:t+this.spacing,y:0,width:o,height:i},sides:Ve|Ke},{geometry:{x:t+this.spacing,y:i+this.spacing,width:o,height:n},sides:Ke},{geometry:{x:t+this.spacing,y:i+n+2*this.spacing,width:o,height:a},sides:Ge|Ke}]}static countRatios(e){return e.map(e=>e.w/e.h)}static countProportions(e){return e.map(e=>e>1.2?"w":e<.8?"n":"q").join("")}}class Qe{constructor(e,t,s,i,n,a=4*s/3){this.averageRatio=t,this.maxWidth=s,this.minWidth=i,this.spacing=n,this.maxHeight=a,this.ratios=Qe.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map(e=>t>1.1?Object(ke.a)(e,1,2.75):Object(ke.a)(e,.6667,1))}layout(){let e=new Array(this.count),t=[];const s=(e,t)=>{const s=He(this.ratios.slice(e,e+t),0);return(this.maxWidth-(t-1)*this.spacing)/s},i=e=>{let i=[],n=0;for(let t of e)i.push(s(n,t)),n+=t;t.push({lineCounts:e,heights:i})};for(let e=1;e!==this.count;++e){const t=this.count-e;e>3||t>3||i([e,t])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t){const s=this.count-e-t;e>3||t>(this.averageRatio<.85?4:3)||s>3||i([e,t,s])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t)for(let s=1;s!==this.count-e-t;++s){const n=this.count-e-t-s;e>3||t>3||s>3||n>3||i([e,t,s,n])}let n=null,a=0;for(const e of t){const{heights:t,lineCounts:s}=e,i=s.length,o=He(t,0)+this.spacing*(i-1),r=Math.min(...t),l=(Math.max(...t),r<this.minWidth?1.5:1),c=(()=>{for(let e=1;e!==i;++e)if(s[e-1]>s[e])return 1.5;return 1})(),d=Math.abs(o-this.maxHeight)*l*c;(!n||d<a)&&(n=e,a=d)}const o=n.lineCounts,r=n.heights,l=o.length;let c=0,d=0;for(let t=0;t!==l;++t){const s=o[t],i=r[t],n=Math.round(i);let a=0;for(let o=0;o!==s;++o){const r=ze|(0===t?Ve:ze)|(t===l-1?Ge:ze)|(0===o?We:ze)|(o===s-1?Ke:ze),h=this.ratios[c],p=o===s-1?this.maxWidth-a:Math.round(h*i);e[c]={geometry:{x:a,y:d,width:p,height:n},sides:r},a+=p+this.spacing,++c}d+=n+this.spacing}return e}}var $e=s(145),Ye=s(87);class Xe{constructor(e){this._disabled=!1,this.avatarSize=120,this.isChanged=()=>{if(this.uploadAvatar)return!0;let e=0,t=0,s=0;return this.inputFields.forEach(i=>{i.isValid()&&(i.isChanged()&&++e,i.required&&++s),i.required&&++t}),t===s&&e>0},this.handleChange=()=>{this.nextBtn.classList.toggle("is-visible",this.isChanged())},Object(w.a)(this,e),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=Q({icon:"check"}),e.withoutAvatar||(this.avatarElem=document.createElement("avatar-element"),this.avatarElem.classList.add("avatar-placeholder","avatar-"+this.avatarSize),this.avatarElem.updateWithOptions({peerId:this.peerId}),e.doNotEditAvatar||(this.avatarEdit=new q(e=>{this.uploadAvatar=e,this.handleChange(),this.avatarElem.remove()}),this.avatarEdit.container.append(this.avatarElem))),this.inputFields.forEach(e=>{this.listenerSetter.add(e.input)("input",this.handleChange)}),this.handleChange()}get disabled(){return this._disabled}set disabled(e){this._disabled=e,this.inputFields.forEach(t=>t.input.toggleAttribute("disabled",e)),this.handleChange()}lockWithPromise(e,t=!1){this.disabled=!0,e.then(()=>{t&&(this.disabled=!1)},()=>{this.disabled=!1})}}function Je(e,t){const s=document.createElement("form");return e.forEach(e=>{const{container:i,input:n}=e;s.append(i),n.addEventListener("change",e=>{n.checked&&t(n.value,e)})}),s}class Ze{constructor(e={}){this.freezed=!1,this.container=document.createElement(e.radioField||e.checkboxField?"label":"div"),this.container.classList.add("row"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("row-subtitle"),this.subtitle.setAttribute("dir","auto"),e.subtitle?"string"==typeof e.subtitle?Object(m.a)(this.subtitle,e.subtitle):this.subtitle.append(e.subtitle):e.subtitleLangKey&&this.subtitle.append(Object(T.d)(e.subtitleLangKey,e.subtitleLangArgs)),this.container.append(this.subtitle);let t=!!e.havePadding;if(e.radioField||e.checkboxField){if(e.radioField&&(this.radioField=e.radioField,this.container.append(this.radioField.label),t=!0),e.checkboxField){this.checkboxField=e.checkboxField;const s=e.checkboxField.label.classList.contains("checkbox-field-toggle");s?(this.container.classList.add("row-with-toggle"),e.titleRight=this.checkboxField.label):(t=!0,this.container.append(this.checkboxField.label)),e.noCheckboxSubtitle||s||this.checkboxField.input.addEventListener("change",()=>{Object(k.a)(this.subtitle,Object(T.d)(this.checkboxField.input.checked?"Checkbox.Enabled":"Checkbox.Disabled"))})}(e.radioField||e.checkboxField).label.classList.add("disable-hover")}if(e.title||e.titleLangKey){let t;const s=e.titleRight||e.titleRightSecondary;if(s?(t=document.createElement("div"),t.classList.add("row-title-row"),this.container.append(t)):t=this.container,this.title=document.createElement("div"),this.title.classList.add("row-title"),this.title.setAttribute("dir","auto"),e.title?"string"==typeof e.title?this.title.innerHTML=e.title:this.title.append(e.title):this.title.append(Object(T.d)(e.titleLangKey)),t.append(this.title),s){const i=this.titleRight=document.createElement("div");i.classList.add("row-title","row-title-right"),e.titleRightSecondary&&i.classList.add("row-title-right-secondary"),"string"==typeof s?i.innerHTML=s:i.append(s),t.append(i)}}e.icon&&(t=!0,this.title.classList.add("tgico","tgico-"+e.icon),this.container.classList.add("row-with-icon")),t&&this.container.classList.add("row-with-padding"),e.navigationTab&&(e.clickable=()=>e.navigationTab.open()),(e.clickable||e.radioField||e.checkboxField)&&("function"==typeof e.clickable&&this.container.addEventListener("click",t=>{this.freezed||e.clickable(t)}),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||Object(te.a)(this.container,void 0,void 0,!0))}createMedia(e){this.container.classList.add("row-with-padding");const t=this.media=document.createElement("div");return t.classList.add("row-media"),e&&t.classList.add("row-media-"+e),this.container.append(t),t}}const et=(e,t)=>Je(e.map(e=>({container:e.container,input:e.radioField.input})),t);function tt(e){navigator.clipboard?navigator.clipboard.writeText(e):function(e){var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(t)}(e)}var st=s(21),it=s(45);class nt{constructor(e){const t=this.label=document.createElement("label");t.classList.add("radio-field"),e.alignRight&&t.classList.add("radio-field-right");const s=this.input=document.createElement("input");s.type="radio",s.name="input-radio-"+e.name,e.value&&(s.value=e.value,e.stateKey&&(M.c.getState().then(t=>{s.checked=Object(it.a)(t,e.stateKey)===e.value}),s.addEventListener("change",()=>{M.c.setByKey(e.stateKey,e.value)})));const i=this.main=document.createElement("div");i.classList.add("radio-field-main"),e.text?i.innerHTML=e.text:e.langKey&&Object(T.b)(i,e.langKey),t.append(s,i)}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e);const t=new Event("change",{bubbles:!0,cancelable:!0});this.input.dispatchEvent(t)}setValueSilently(e){this.input.checked=e}}const at=document.createElement("div");function ot(e){Object(k.a)(at,e),document.body.append(at),at.dataset.timeout&&clearTimeout(+at.dataset.timeout),at.dataset.timeout=""+setTimeout(()=>{at.remove(),delete at.dataset.timeout},3e3)}function rt(e){ot(Object(T.d)(e.langPackKey,e.langPackArguments))}at.classList.add("toast");var lt=s(89),ct=s(8);class dt extends O.b{constructor(e){super(e),this.checkUsernameDebounced=Object(lt.a)(this.checkUsername.bind(this),150,!1,!0),e.listenerSetter.add(this.input)("input",()=>{const e=this.getValue();if(e===this.originalValue||!e.length)return this.setState(O.a.Neutral,this.options.label),void(this.options.onChange&&this.options.onChange());X.b.isUsernameValid(e)?this.setState(O.a.Neutral):this.setError(this.options.invalidText),this.input.classList.contains("error")?this.options.onChange&&this.options.onChange():this.checkUsernameDebounced(e)})}getValue(){let e=this.value;return this.options.head&&(e=e.slice(this.options.head.length),this.setValueSilently(this.options.head+e)),e}checkUsername(e){this.checkUsernamePromise||(this.options.peerId?this.checkUsernamePromise=ct.a.invokeApi("channels.checkUsername",{channel:G.a.getChannelInput(this.options.peerId.toChatId()),username:e}):this.checkUsernamePromise=ct.a.invokeApi("account.checkUsername",{username:e}),this.checkUsernamePromise.then(t=>{this.getValue()===e&&(t?this.setState(O.a.Valid,this.options.availableText):this.setError(this.options.takenText))},t=>{if(this.getValue()===e)switch(t.type){case"USERNAME_INVALID":this.setError(this.options.invalidText)}}).then(()=>{this.checkUsernamePromise=void 0,this.options.onChange&&this.options.onChange();const t=this.getValue();t!==e&&this.isValidToChange()&&X.b.isUsernameValid(t)&&this.checkUsername(t)}))}}var ht=s(73),pt=s(70);class ut extends ht.b{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),t.buttons&&Object(ht.a)(t.buttons),Object.assign({overlayClosable:!0},t)),this.className=e,t.peerId){const e=new fc;e.classList.add("avatar-32"),e.updateWithOptions({isDialog:!0,peerId:t.peerId}),this.header.prepend(e)}t.noTitle||(t.titleLangKey||!t.title?this.title.append(Object(T.d)(t.titleLangKey||"AppName",t.titleLangArgs)):t.title instanceof HTMLElement?this.title.append(t.title):this.title.innerText=t.title||"");const s=document.createDocumentFragment();if(t.descriptionLangKey||t.description){const e=this.description=document.createElement("p");e.classList.add("popup-description"),t.descriptionLangKey?e.append(Object(T.d)(t.descriptionLangKey,t.descriptionLangArgs)):t.description&&Object(m.a)(e,t.description),s.append(e)}t.checkboxes&&(this.container.classList.add("have-checkbox"),t.checkboxes.forEach(e=>{e.withRipple=!1;const t=new pt.a(e);e.checkboxField=t,s.append(t.label)}),t.buttons.forEach(e=>{if(e.callback){const s=e.callback;e.callback=()=>{const e=new Set;t.checkboxes.forEach(t=>{t.checkboxField.checked&&e.add(t.text)}),s(e)}}})),this.container.insertBefore(s,this.header.nextElementSibling)}}var gt=s(78);class mt extends z{init(){this.container.classList.add("edit-peer-container","group-type-container");const e=G.a.isBroadcast(this.chatId);this.setTitle(e?"ChannelType":"GroupType");const t=new Kn({name:e?"ChannelType":"GroupType"}),s=Object(st.b)(),i=new Ze({radioField:new nt({langKey:e?"ChannelPrivate":"MegaPrivate",name:s,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),o=new Ze({radioField:new nt({langKey:e?"ChannelPublic":"MegaPublic",name:s,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),r=et([i,o],e=>{const t=[d,u];"public"===e&&t.reverse(),t[0].container.classList.remove("hide"),t[1].container.classList.add("hide"),m()}),c=G.a.getChat(this.chatId);t.content.append(r);const d=new Kn({}),h=new Ze({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{tt(this.chatFull.exported_invite.link),ot(T.c.format("LinkCopied",!0))}}),p=Object(B.a)("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});Object(l.b)(p,()=>{new ut("revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const e=Object(gt.a)([p],!0);n.default.getChatInviteLink(this.chatId,!0).then(t=>{e(),h.title.innerHTML=t})}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()},{listenerSetter:this.listenerSetter}),d.content.append(h.container,p);const u=new Kn({caption:e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup",noDelimiter:!0}),g=document.createElement("div");g.classList.add("input-wrapper");const m=()=>{const e=i.radioField.checked&&"t.me/"!==v||b.isValidToChange()&&b.input.classList.contains("valid");f.classList.toggle("is-visible",e)},b=new dt({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:m,peerId:this.chatId.toPeerId(!0),head:"t.me/"}),v="t.me/"+(c.username||"");g.append(b.container),u.content.append(g);const f=Q({icon:"check",className:"is-visible"});this.content.append(f),Object(l.b)(f,()=>{Object(ee.g)(f);const e=o.radioField.checked?b.getValue():"";G.a.migrateChat(this.chatId).then(t=>G.a.updateUsername(t,e)).then(()=>{this.close()})},{listenerSetter:this.listenerSetter}),("t.me/"!==v?o:i).radioField.checked=!0,b.setOriginalValue(v),this.scrollable.append(t.container,d.container,u.container);{const t=new Kn({name:"SavingContentTitle",caption:e?"RestrictSavingContentInfoChannel":"RestrictSavingContentInfoGroup"}),s=new pt.a({text:"RestrictSavingContent",withRipple:!0});this.listenerSetter.add(s.input)("change",()=>{const e=s.toggleDisability(!0);G.a.toggleNoForwards(this.chatId,s.checked).then(()=>{e()})});const i=()=>{s.setValueSilently(!!c.pFlags.noforwards)};this.listenerSetter.add(a.a)("chat_update",e=>{this.chatId===e&&i()}),i(),t.content.append(s.label),this.scrollable.append(t.container)}}}var bt=s(85);class vt{constructor(e){this.loading=!1,this.loaded=!1,Object(w.a)(this,e),e.scrollable.onScrolledBottom=()=>{this.load()}}load(){return this.loaded?Promise.resolve():this.loading?this.promise:(this.loading=!0,void(this.promise=this.getPromise().then(e=>{this.loading=!1,this.promise=void 0,e?(this.loaded=!0,this.scrollable.onScrolledBottom=null):this.scrollable.checkForTriggers()},()=>{this.promise=void 0,this.loading=!1})))}}var ft=s(102),yt=s(106),wt=s(69),St=s(100),Ct=s(157),Lt=s(39),It=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Mt{constructor(e){this.container=document.createElement("div"),this.list=_c.createChatList(),this.chatsContainer=document.createElement("div"),this.selected=new Set,this.freezed=!1,this.folderId=0,this.offsetIndex=0,this.query="",this.loadedWhat={},this.renderedPeerIds=new Set,this.peerType=["dialogs"],this.multiSelect=!0,this.rippleEnabled=!0,this.avatarSize=48,this.exceptSelf=!1,this.tempIds={},this.selfPresence="Presence.YourChat",this.needSwitchList=!1,this.onInput=()=>{const e=this.input.value;if(this.query!==e){(this.peerType.includes("contacts")||this.peerType.includes("dialogs"))&&(this.cachedContacts=null),this.peerType.includes("dialogs")&&(this.folderId=0,this.offsetIndex=0);for(let e in this.tempIds)++this.tempIds[e];this.list=_c.createChatList(),this.promise=null,this.loadedWhat={},this.query=e,this.renderedPeerIds.clear(),this.needSwitchList=!0,this.getMoreResults()}},this.checkForTriggers=()=>{this.scrollable.checkForTriggers()},Object(w.a)(this,e),this.container.classList.add("selector");const t=(this.renderResultsFunc||this.renderResults).bind(this);if(this.renderResultsFunc=e=>(this.needSwitchList&&(this.scrollable.splitUp.replaceWith(this.list),this.scrollable.setVirtualContainer(this.list),this.needSwitchList=!1),e=e.filter(e=>{const t=!this.renderedPeerIds.has(e);return t&&this.renderedPeerIds.add(e),t}),this.filterPeerTypeBy&&(e=e.filter(e=>{if(e.isPeerId()){if(!o.a.getPeer(e).deleted)return this.filterPeerTypeBy.find(t=>o.a[t](e))}return!0})),t(e)),this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.placeholder?Object(T.b)(this.input,this.placeholder,void 0,"placeholder"):Object(T.b)(this.input,"SendMessageTo",void 0,"placeholder"),this.input.type="text",this.multiSelect){const e=new Kn({});e.innerContainer.classList.add("selector-search-section");let t=document.createElement("div");t.classList.add("selector-search-container"),this.selectedContainer=document.createElement("div"),this.selectedContainer.classList.add("selector-search"),this.selectedContainer.append(this.input),t.append(this.selectedContainer),this.selectedScrollable=new P.b(t),Object(l.b)(this.selectedContainer,e=>{if(this.freezed)return;let t=e.target;if(t=Object(Ce.a)(t,"selector-user"),!t)return;const s=t.dataset.key,i=this.chatsContainer.querySelector('[data-peer-id="'+s+'"]');i?i.click():this.remove(s.toPeerId())}),e.content.append(t),this.container.append(e.container)}this.chatsContainer.classList.add("chatlist-container");const s=new Kn({name:this.sectionNameLangPackKey,noShadow:!0});s.content.append(this.list),this.chatsContainer.append(s.container),this.scrollable=new P.b(this.chatsContainer),this.scrollable.setVirtualContainer(this.list),Object(l.b)(this.chatsContainer,e=>{const t=Object(yt.a)(e.target,"data-peer-id");if(Object(c.a)(e),!t)return;if(this.freezed)return;let s=t.dataset.peerId;if(s=s.isPeerId()?s.toPeerId():s,!this.multiSelect)return void this.add(s);this.selected.has(s)?this.remove(s):this.add(s);const i=t.querySelector("input");i.checked=!i.checked});const i=Object(lt.a)(this.onInput,200,!1,!0);this.input.addEventListener("input",i),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},this.scrollable.container.prepend(Wn()),this.container.append(this.chatsContainer),this.appendTo.append(this.container),setTimeout(()=>{let t=this.getMoreResults();e.onFirstRender&&t.then(()=>{e.onFirstRender()})},0)}renderSaved(){this.exceptSelf||this.offsetIndex||0!==this.folderId||!this.peerType.includes("dialogs")||this.query&&!E.a.testSelfSearch(this.query)||this.renderResultsFunc([a.a.myId])}getTempId(e){return void 0===this.tempIds[e]&&(this.tempIds[e]=0),++this.tempIds[e]}getMoreDialogs(){return It(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=St.a.height/72*1.25|0,t=this.getTempId("dialogs"),s=i.a.getConversations(this.query,this.offsetIndex,e,this.folderId,!0).promise;this.promise=s;const n=yield s;if(this.tempIds.dialogs!==t)return;this.promise=null;let o=n.dialogs;if(o.length){const e=o[o.length-1].index||0;o=o.slice(),Object(Lt.a)(o,e=>e.peerId===a.a.myId),this.chatRightsAction&&(o=o.filter(e=>this.filterByRights(e.peerId))),this.renderSaved(),this.offsetIndex=e}if(this.renderResultsFunc(o.map(e=>e.peerId)),n.isEnd){if(!this.loadedWhat.dialogs)return this.renderSaved(),this.loadedWhat.dialogs=!0,this.offsetIndex=0,this.folderId=1,this.getMoreDialogs();if(this.loadedWhat.archived=!0,!this.loadedWhat.contacts)return this.getMoreContacts()}}))}filterByRights(e){return e.isUser()&&("send_messages"!==this.chatRightsAction||E.a.canSendToUser(e))||G.a.hasRights(e.toChatId(),this.chatRightsAction)}getMoreContacts(){return It(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.contacts)return;const e=this.peerType.includes("contacts");if(!this.cachedContacts){const t=this.getTempId("contacts"),s=Promise.all([e?E.a.getContactsPeerIds(this.query):[],this.query?E.a.searchContacts(this.query):void 0]);this.promise=s;let[i,n]=yield s;if(this.tempIds.contacts!==t)return;if(n){let t=e?n.my_results.concat(n.results):n.my_results;this.chatRightsAction&&(t=t.filter(e=>this.filterByRights(e))),this.peerType.includes("dialogs")||(t=t.filter(e=>e.isUser())),this.cachedContacts=Object(Ct.a)(i.concat(t))}else this.cachedContacts=i.slice();Object(V.a)(this.cachedContacts,a.a.myId),this.promise=null}const t=St.a.height/72*1.25|0,s=this.cachedContacts.splice(0,t);this.renderResultsFunc(s),this.cachedContacts.length||(this.loadedWhat.contacts=!0)}))}getMoreChannelParticipants(){return It(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.channelParticipants)return;const e=this.getTempId("channelParticipants"),t=n.default.getChannelParticipants(this.peerId.toChatId(),{_:"channelParticipantsSearch",q:this.query},50,this.list.childElementCount),s=yield t;if(this.tempIds.channelParticipants!==e)return;const i=s.participants.map(e=>G.a.getParticipantPeerId(e));Object(V.a)(i,a.a.myId),this.renderResultsFunc(i),(this.list.childElementCount>=s.count||s.participants.length<50)&&(this.loadedWhat.channelParticipants=!0)}))}getMoreResults(){const e=(()=>{const e=[];return!this.peerType.includes("dialogs")||this.loadedWhat.archived||(e.push(this.getMoreDialogs()),this.loadedWhat.archived)?(!this.peerType.includes("contacts")&&!this.peerType.includes("dialogs")||this.loadedWhat.contacts||e.push(this.getMoreContacts()),this.peerType.includes("channelParticipants")&&!this.loadedWhat.channelParticipants&&e.push(this.getMoreChannelParticipants()),e):e})(),t=Promise.all(e);return e.length&&t.then(this.checkForTriggers),t}renderResults(e){!this.peerType.includes("dialogs")&&this.loadedWhat.contacts&&(e=e.filter(e=>E.a.isNonContactUser(e))),e.forEach(e=>{const{dom:t}=_c.addDialogNew({dialog:e,container:this.scrollable,drawStatus:!1,rippleEnabled:this.rippleEnabled,avatarSize:this.avatarSize});if(this.multiSelect){const s=this.selected.has(e),i=new pt.a;s&&(i.input.checked=!0),t.containerEl.prepend(i.label)}let s;s=e.isAnyChat()?n.default.getChatMembersString(e.toChatId()):e===a.a.myId?Object(T.d)(this.selfPresence):E.a.getUserStatusString(e),t.lastMessageSpan.append(s)})}add(e,t,s=!0){if(this.selected.add(e),!this.multiSelect)return void this.onChange(this.selected.size);this.query.trim()&&(this.input.value="",this.onInput());const i=document.createElement("div");i.classList.add("selector-user","scale-in");const n=new fc;return n.classList.add("selector-user-avatar","tgico","avatar-32"),n.isDialog=!0,i.dataset.key=""+e,e.isPeerId()&&(void 0===t&&(t=new wt.a({peerId:e.toPeerId(),dialog:!0}).element),n.updateWithOptions({peerId:e})),t&&("string"==typeof t?i.innerHTML=t:(Object(k.a)(i,t),i.append(t))),i.insertAdjacentElement("afterbegin",n),this.selectedContainer.insertBefore(i,this.input),this.onChange&&this.onChange(this.selected.size),s&&this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center"}),i}remove(e){if(!this.multiSelect)return;const t=this.selectedContainer.querySelector(`[data-key="${e}"]`);t.classList.remove("scale-in"),t.offsetWidth,t.classList.add("scale-out");const s=()=>{this.selected.delete(e),t.remove(),this.onChange&&this.onChange(this.selected.size)};a.a.settings.animationsEnabled?t.addEventListener("animationend",s,{once:!0}):s()}getSelected(){return[...this.selected]}addInitial(e){e.forEach(e=>{this.add(e,void 0,!1)}),window.requestAnimationFrame(()=>{this.selectedScrollable.scrollIntoViewNew({element:this.input,position:"center",forceDirection:ft.a.Static})})}}var Et=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Pt extends ht.b{constructor(e){super("popup-forward",null,{closable:!0,overlayClosable:!0,body:!0}),this.selector=new Mt({appendTo:this.body,onChange:()=>Et(this,void 0,void 0,(function*(){const t=this.selector.getSelected(),s=t[t.length-1].toPeerId();if(e.onSelect){const t=e.onSelect(s);if(t instanceof Promise)try{yield t}catch(e){return}}this.selector=null,this.hide()})),peerType:e.peerTypes,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),he.a||this.selector.input.focus()},chatRightsAction:e.chatRightsAction,multiSelect:!1,rippleEnabled:!1,avatarSize:46,peerId:e.peerId,placeholder:e.placeholder,selfPresence:e.selfPresence}),this.title.append(this.selector.input)}}class kt extends z{init(){let e;this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle("UserRestrictions");{const t=new Kn({name:"UserRestrictionsCanDo"}),s=document.createElement("div");s.classList.add("chatlist-container"),t.content.insertBefore(s,t.title);const i=_c.createChatList({new:!0});s.append(i);const{dom:n}=_c.addDialogNew({dialog:this.userId.toPeerId(!1),container:i,drawStatus:!1,rippleEnabled:!0,avatarSize:48});n.lastMessageSpan.append(E.a.getUserStatusString(this.userId));const a=new xt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content,participant:"channelParticipantBanned"===this.participant._?this.participant:void 0});e=()=>{const e=a.takeOut();"channelParticipantBanned"===this.participant._&&Object(ge.a)(this.participant.banned_rights.pFlags,e.pFlags)||G.a.editBanned(this.chatId,this.participant,e)},this.eventListener.addEventListener("destroy",e,{once:!0}),this.scrollable.append(t.container)}{const t=new Kn({});if("channelParticipantBanned"===this.participant._){const s=Object(B.a)("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});Object(l.b)(s,()=>{const t=Object(gt.a)([s],!0);G.a.clearChannelParticipantBannedRights(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()},()=>{t()})},{listenerSetter:this.listenerSetter}),t.content.append(s)}const s=Object(B.a)("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});Object(l.b)(s,()=>{Object(gt.a)([s],!0);G.a.kickFromChannel(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()})},{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container)}}}var Tt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class xt{constructor(e){this.v=[{flags:["send_messages"],text:"UserRestrictionsSend",exceptionText:"UserRestrictionsNoSend"},{flags:["send_media"],text:"UserRestrictionsSendMedia",exceptionText:"UserRestrictionsNoSendMedia"},{flags:["send_stickers","send_gifs"],text:"UserRestrictionsSendStickers",exceptionText:"UserRestrictionsNoSendStickers"},{flags:["send_polls"],text:"UserRestrictionsSendPolls",exceptionText:"UserRestrictionsNoSendPolls"},{flags:["embed_links"],text:"UserRestrictionsEmbedLinks",exceptionText:"UserRestrictionsNoEmbedLinks"},{flags:["invite_users"],text:"UserRestrictionsInviteUsers",exceptionText:"UserRestrictionsNoInviteUsers"},{flags:["pin_messages"],text:"UserRestrictionsPinMessages",exceptionText:"UserRestrictionsNoPinMessages"},{flags:["change_info"],text:"UserRestrictionsChangeInfo",exceptionText:"UserRestrictionsNoChangeInfo"}],this.toggleWith={send_messages:["send_media","send_stickers","send_polls","embed_links"]};const t=G.a.getChat(e.chatId),s=t.default_banned_rights,i=e.participant?G.a.combineParticipantBannedRights(e.chatId,e.participant.banned_rights):s,n=e.participant?"UserRestrictionsDisabled":"EditCantEditPermissionsPublic";for(const a of this.v){const o=a.flags[0];a.checkboxField=new pt.a({text:a.text,checked:G.a.hasRights(e.chatId,o,i),restriction:!0,withRipple:!0}),(e.participant&&s.pFlags[o]||t.username&&(a.flags.includes("pin_messages")||a.flags.includes("change_info")))&&(a.checkboxField.input.disabled=!0,Object(l.b)(a.checkboxField.label,e=>{ot(T.c.format(n,!0))},{listenerSetter:e.listenerSetter})),this.toggleWith[o]&&e.listenerSetter.add(a.checkboxField.input)("change",()=>{if(!a.checkboxField.checked){this.v.filter(e=>this.toggleWith[o].includes(e.flags[0])).forEach(e=>{e.checkboxField.checked=!1})}}),e.appendTo.append(a.checkboxField.label)}}takeOut(){const e={_:"chatBannedRights",until_date:2147483647,pFlags:{}};for(const t of this.v){!t.checkboxField.checked&&t.flags.forEach(t=>{e.pFlags[t]=!0})}return e}}class At extends z{init(){return Tt(this,void 0,void 0,(function*(){let e;this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions");{const t=new Kn({name:"ChannelPermissionsHeader"});e=new xt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content}),this.eventListener.addEventListener("destroy",()=>{G.a.editChatDefaultBannedRights(this.chatId,e.takeOut())},{once:!0}),this.scrollable.append(t.container)}{const t=new Kn({name:"PrivacyExceptions"}),s=new Ze({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{new Pt({peerTypes:["channelParticipants"],onSelect:e=>{setTimeout(()=>{i(e)},0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId})}}),i=e=>Tt(this,void 0,void 0,(function*(){let t;try{t=yield n.default.getChannelParticipant(this.chatId,e)}catch(e){return void ot("User is no longer participant")}const s=new kt(this.slider);s.participant=t,s.chatId=this.chatId,s.userId=e,s.open()}));t.content.append(s.container);const r=t.generateContentElement();r.classList.add("chatlist-container");const c=_c.createChatList({new:!0});r.append(c),Object(l.b)(c,e=>{const t=Object(bt.a)(e.target,"LI");if(!t)return;const s=t.dataset.peerId.toPeerId();i(s)},{listenerSetter:this.listenerSetter});const d=(t,s)=>{const i=s.banned_rights,n=G.a.getChat(this.chatId).default_banned_rights,a=[];e.v.forEach(e=>{const t=e.flags[0];i.pFlags[t]&&!n.pFlags[t]&&a.push(e.exceptionText)});const o=t.querySelector(".user-last-message");a.length&&(o.innerHTML="",o.append(...Object(T.f)(a.map(e=>Object(T.d)(e)),!1))),o.classList.toggle("hide",!a.length)},h=(e,t)=>{const{dom:s}=_c.addDialogNew({dialog:o.a.getPeerId(e.peer),container:c,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:t});d(s.listEl,e)};this.listenerSetter.add(a.a)("updateChannelParticipant",e=>{var t,s,i;const n="channelParticipantBanned"===(null===(t=e.new_participant)||void 0===t?void 0:t._)&&!e.new_participant.banned_rights.pFlags.view_messages,a=c.querySelector(`[data-peer-id="${e.user_id}"]`);n?(a?d(a,e.new_participant):h(e.new_participant,!1),"channelParticipantBanned"!==(null===(s=e.prev_participant)||void 0===s?void 0:s._)&&++g):(a&&a.remove(),"channelParticipantBanned"===(null===(i=e.prev_participant)||void 0===i?void 0:i._)&&--g),p()});const p=()=>{Object(k.a)(s.subtitle,Object(T.d)(g?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[g]))};let u,g=0;const m=()=>(u=new vt({scrollable:this.scrollable,getPromise:()=>n.default.getChannelParticipants(this.chatId,{_:"channelParticipantsBanned",q:""},50,c.childElementCount).then(e=>{for(const t of e.participants)h(t,!0);return g=e.count,p(),e.participants.length<50||e.count===c.childElementCount})}),u.load());this.scrollable.append(t.container),G.a.isChannel(this.chatId)?yield m():(p(),this.listenerSetter.add(a.a)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{this.chatId===e&&(this.chatId=t,m())}))}}))}onOpenAfterTimeout(){this.scrollable.onScroll()}}class Ot{constructor(e,t=o.a.getDialogType(e),s){const n=new wt.a({peerId:e}).element,a=(t,n=p&&!!t.size)=>{let a=G.a.leave(e.toChatId());n&&(a=a.finally(()=>i.a.flushHistory(e))),s&&s(a)},r=t=>{let n;if(e.isUser())n=i.a.flushHistory(e,!1,p?!!t.size:void 0);else{if(!t.size)return a(t);n=G.a.delete(e.toChatId())}s&&s(n)};let l,c,d,h,p;switch(t){case"channel":G.a.hasRights(e.toChatId(),"delete_chat")?(G.a.deleteChannel,l="ChannelDeleteMenu",c="AreYouSureDeleteAndExitChannel",h=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:r}],p=[{text:"DeleteChannelForAll"}]):(l="LeaveChannelMenu",c="ChannelLeaveAlertWithName",d=[n],h=[{langKey:"LeaveChannel",isDanger:!0,callback:a}]);break;case"chat":l="DeleteChatUser",c="AreYouSureDeleteThisChatWithUser",d=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}],p=[{text:"DeleteMessagesOptionAlso",textArgs:[new wt.a({peerId:e}).element]}];break;case"saved":l="DeleteChatUser",c="AreYouSureDeleteThisChatSavedMessages",h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}];break;case"megagroup":case"group":G.a.hasRights(e.toChatId(),"delete_chat")?(l="DeleteMegaMenu",c="AreYouSureDeleteAndExit",h=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:r}],p=[{text:"DeleteChat.DeleteGroupForAll"}]):(l="LeaveMegaMenu",c="AreYouSureDeleteAndExitName",d=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:e=>a(e,!0)}])}new ut("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:c,descriptionLangArgs:d,buttons:h,checkboxes:p}).show()}}var jt=s(101),_t=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ft extends z{init(){var e;return _t(this,void 0,void 0,(function*(){this.setTitle("Reactions");const t=yield jt.a.getActiveAvailableReactions(),s=yield n.default.getChatFull(this.chatId);let i=null!==(e=s.available_reactions)&&void 0!==e?e:[];const a=new Set(i),o=new Kn({caption:G.a.isBroadcast(this.chatId)?"EnableReactionsChannelInfo":"EnableReactionsGroupInfo"}),r=new pt.a({toggle:!0,checked:!!a.size}),l=new Ze({checkboxField:r,titleLangKey:"EnableReactions"});o.content.append(l.container);const c=new Kn({name:"AvailableReactions"}),d=t.map(e=>{const t=new pt.a({toggle:!0,checked:a.has(e.reaction)});this.listenerSetter.add(t.input)("change",()=>{t.checked?(a.add(e.reaction),r.checked||r.setValueSilently(!0)):(a.delete(e.reaction),!a.size&&r.checked&&r.setValueSilently(!1)),p()});const s=new Ze({checkboxField:t,title:e.title,havePadding:!0});return Os({row:s,doc:e.static_icon,size:"small"}),c.content.append(s.container),t});this.listenerSetter.add(l.checkboxField.input)("change",()=>{r.checked?d.every(e=>!e.checked)&&(d.forEach(e=>e.checked=!0),p()):(d.forEach(e=>e.checked=!1),p())});const h=()=>{const e=Array.from(a);if([...e].sort().join()===[...i].sort().join())return;const t=n.default.getCachedFullChat(this.chatId);t&&(t.available_reactions=e),G.a.setChatAvailableReactions(this.chatId,e),i=e},p=Object(lt.a)(h,3e3,!1,!0);this.eventListener.addEventListener("destroy",h,{once:!0}),this.scrollable.append(o.container,c.container)}))}}var Dt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Rt extends H{_init(){var e;return Dt(this,void 0,void 0,(function*(){this.listenerSetter.removeAll(),this.scrollable.container.innerHTML="",null!==(e=this.tempId)&&void 0!==e||(this.tempId=0);const t=++this.tempId;this.container.classList.add("edit-peer-container","edit-group-container"),this.setTitle("Edit");let s=yield n.default.getChatFull(this.chatId,!0);const i=G.a.getChat(this.chatId),o=G.a.isBroadcast(this.chatId),r=G.a.isChannel(this.chatId),c=[],d=e=>{c.push(e)};this.listenerSetter.add(a.a)("chat_update",e=>{this.chatId===e&&c.forEach(e=>e())}),this.listenerSetter.add(a.a)("chat_full_update",e=>{this.chatId===e&&(s=n.default.getCachedFullChat(e)||s)});const h=this.chatId.toPeerId(!0),p=G.a.hasRights(this.chatId,"change_type"),u=G.a.hasRights(this.chatId,"change_permissions");{const e=new Kn({noDelimiter:!0}),n=[],r=document.createElement("div");if(r.classList.add("input-wrapper"),this.chatNameInputField=new O.b({label:o?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0}),this.descriptionInputField=new O.b({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255}),this.chatNameInputField.setOriginalValue(i.title),this.descriptionInputField.setOriginalValue(s.about),r.append(this.chatNameInputField.container,this.descriptionInputField.container),n.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new Xe({peerId:h,inputFields:n,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),e.content.append(this.editPeer.avatarEdit.container,r),p){const t=new Ze({titleLangKey:o?"ChannelType":"GroupType",clickable:()=>{const e=new mt(this.slider);e.chatId=this.chatId,e.chatFull=s,e.open(),this.listenerSetter.add(e.eventListener)("destroy",n)},icon:"lock"}),n=()=>{let e;t.subtitle.textContent="",e=o?i.username?"TypePublic":"TypePrivate":i.username?"TypePublicGroup":"TypePrivateGroup",t.subtitle.append(Object(T.d)(e))};n(),e.content.append(t.container)}if(p||u){const i=new Ze({titleLangKey:"Reactions",icon:"reactions",clickable:()=>{const e=new Ft(this.slider);e.chatId=this.chatId,e.open().then(()=>{this.tempId===t&&this.listenerSetter.add(e.eventListener)("destroy",a)})}}),n=(yield jt.a.getAvailableReactions()).filter(e=>!e.pFlags.inactive).length,a=()=>{var e;const t=null!==(e=s.available_reactions)&&void 0!==e?e:[];i.subtitle.innerHTML=t.length+"/"+n};a(),e.content.append(i.container)}if(u&&!o){const t=["send_messages","send_media","send_stickers","send_polls","embed_links","invite_users","pin_messages","change_info"],s=new Ze({titleLangKey:"ChannelPermissions",clickable:()=>{const e=new At(this.slider);e.chatId=this.chatId,e.open()},icon:"permissions"}),n=()=>{s.subtitle.innerHTML=t.reduce((e,t)=>e+ +G.a.hasRights(this.chatId,t,i.default_banned_rights),0)+"/"+t.length};n(),e.content.append(s.container),this.listenerSetter.add(a.a)("chat_update",e=>{this.chatId===e&&n()})}if(this.scrollable.append(e.container),Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;let e=[];const t=this.chatId;this.chatNameInputField.isValidToChange()&&e.push(G.a.editTitle(t,this.chatNameInputField.value)),this.descriptionInputField.isValidToChange()&&e.push(G.a.editAbout(t,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then(e=>G.a.editPhoto(t,e))),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter}),o&&G.a.hasRights(this.chatId,"change_info")){const t=new pt.a({text:"PeerInfo.SignMessages",checked:!!i.pFlags.signatures,withRipple:!0});this.listenerSetter.add(t.input)("change",()=>{const e=t.toggleDisability(!0);G.a.toggleSignatures(this.chatId,t.checked).then(()=>{e()})}),d(()=>{t.setValueSilently(!!i.pFlags.signatures)}),e.content.append(t.label)}}if(!o){const e=new Kn({});if(!o&&p){const t=new pt.a({text:"ChatHistory",withRipple:!0});this.listenerSetter.add(t.input)("change",()=>{const e=t.toggleDisability(!0);G.a.togglePreHistoryHidden(this.chatId,!t.checked).then(()=>{e()})});const i=()=>{t.setValueSilently(r&&!s.pFlags.hidden_prehistory)};i(),d(i),e.content.append(t.label)}e.content.childElementCount&&this.scrollable.append(e.container)}if(G.a.hasRights(this.chatId,"delete_chat")){const e=new Kn({}),t=Object(B.a)("btn-primary btn-transparent danger",{icon:"delete",text:o?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});Object(l.b)(t,()=>{new Ot(h,void 0,e=>{const s=Object(gt.a)([t],!0);e.then(()=>{this.close()},()=>{s()})})},{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}r||this.listenerSetter.add(a.a)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{h===e&&(this.chatId=t.toChatId(),this._init())})}))}init(){return this._init()}}var Bt=s(111);class Nt extends H{init(){this.container.classList.add("edit-peer-container","edit-contact-container");const e=!E.a.isContact(this.peerId.toUserId());this.setTitle(e?"AddContactTitle":"Edit");{const t=new Kn({noDelimiter:!0}),s=[],n=document.createElement("div");if(n.classList.add("input-wrapper"),this.nameInputField=new O.b({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new O.b({label:"LastName",name:"contact-lastname",maxLength:70}),this.peerId){const t=E.a.getUser(this.peerId);e?(this.nameInputField.setDraftValue(t.first_name),this.lastNameInputField.setDraftValue(t.last_name)):(this.nameInputField.setOriginalValue(t.first_name),this.lastNameInputField.setOriginalValue(t.last_name))}if(n.append(this.nameInputField.container,this.lastNameInputField.container),s.push(this.nameInputField,this.lastNameInputField),this.editPeer=new Xe({peerId:this.peerId,inputFields:s,listenerSetter:this.listenerSetter,doNotEditAvatar:!0}),this.content.append(this.editPeer.nextBtn),this.peerId){const s=document.createElement("div");s.classList.add("avatar-edit"),s.append(this.editPeer.avatarElem);const r=new pt.a({text:"Notifications"});r.input.addEventListener("change",e=>{e.isTrusted&&i.a.togglePeerMute(this.peerId)}),this.listenerSetter.add(a.a)("notify_settings",e=>{if("notifyPeer"!==e.peer._)return;const t=o.a.getPeerId(e.peer.peer);if(this.peerId===t){const t=!Bt.a.isMuted(e.notify_settings);t!==r.checked&&(r.checked=t)}});const l=document.createElement("div");l.classList.add("profile-name"),l.append(new wt.a({peerId:this.peerId}).element);const c=document.createElement("div");if(c.classList.add("profile-subtitle"),c.append(Object(T.d)("EditContact.OriginalName")),t.content.append(s,l,c,n),e){const e=E.a.getUser(this.peerId),s=new Ze({icon:"phone",titleLangKey:e.phone?void 0:"MobileHidden",title:e.phone?E.a.formatUserPhone(e.phone):void 0,subtitleLangKey:e.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:e.phone?void 0:[new wt.a({peerId:this.peerId}).element]});t.content.append(s.container)}else{const e=new Ze({checkboxField:r}),s=!Bt.a.isPeerLocalMuted(this.peerId,!1);r.checked=s,t.content.append(e.container)}}else t.content.append(n);this.scrollable.append(t.container),Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0,E.a.addContact(this.peerId,this.nameInputField.value,this.lastNameInputField.value,E.a.getUser(this.peerId).phone).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}if(!e){const e=new Kn({}),t=Object(B.a)("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});Object(l.b)(t,()=>{new ut("popup-delete-contact",{peerId:this.peerId,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:Object(ht.a)([{langKey:"Delete",callback:()=>{const e=Object(gt.a)([t],!0);E.a.deleteContacts([this.peerId]).then(()=>{this.close()},()=>{e()})},isDanger:!0}])}).show()},{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}}}class Ut extends H{init(){this.container.classList.add("add-members-container"),this.nextBtn=Q({icon:"arrow_next"}),this.content.append(this.nextBtn),this.scrollable.container.remove(),this.nextBtn.addEventListener("click",()=>{const e=this.selector.getSelected().map(e=>e.toPeerId());if(this.skippable)this.takeOut(e),this.close();else{const t=this.takeOut(e);t instanceof Promise?this.attachToPromise(t):void 0===t&&this.close()}})}attachToPromise(e){const t=Object(ee.g)(this.nextBtn,"arrow_next");e.then(()=>{this.close()},()=>{t()})}open(e){const t=super.open();this.setTitle(e.title),this.peerType=e.type,this.takeOut=e.takeOut,this.skippable=e.skippable;const s="privacy"===this.peerType;return this.selector=new Mt({appendTo:this.content,onChange:this.skippable?null:e=>{this.nextBtn.classList.toggle("is-visible",!!e)},peerType:[s?"dialogs":"contacts"],placeholder:e.placeholder,exceptSelf:s,filterPeerTypeBy:s?["isAnyGroup","isUser"]:void 0}),e.selectedPeerIds&&this.selector.addInitial(e.selectedPeerIds),this.nextBtn.classList.add("tgico-arrow_next"),this.nextBtn.innerHTML="",this.nextBtn.disabled=!1,this.nextBtn.classList.toggle("is-visible",this.skippable),t}}var Ht=!ae.d&&!1,zt=s(129);function Vt(e){const t=document.createElement("span");return t.classList.add("badge-fake"),Object(T.b)(t,e?"ScamMessage":"FakeMessage"),t}function Kt(e){var t;const s=[],i=o.a.getPeer(e);return(null===(t=null==i?void 0:i.pFlags)||void 0===t?void 0:t.verified)&&s.push(function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 24 24"),e.setAttributeNS(null,"width","24"),e.setAttributeNS(null,"height","24"),e.classList.add("verified-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","use");t.setAttributeNS(null,"href","#verified-background"),t.classList.add("verified-background");const s=document.createElementNS("http://www.w3.org/2000/svg","use");return s.setAttributeNS(null,"href","#verified-check"),s.classList.add("verified-check"),e.append(t,s),e}()),(i.pFlags.fake||i.pFlags.scam)&&s.push(Vt(i.pFlags.scam)),s}const Gt=e=>e.touches?e.touches[0]:e,Wt=window;let qt=!1;a.a.addEventListener("context_menu_toggle",e=>{qt=e});class Qt{constructor(e){this.cursor="grabbing",this.cancelEvent=!0,this.listenerOptions=!1,this.hadMove=!1,this.xDown=null,this.yDown=null,this.reset=e=>{he.a?Wt.removeEventListener("touchmove",this.handleMove,{capture:!0}):(Wt.removeEventListener("mousemove",this.handleMove),this.setCursorTo.style.cursor=""),this.onReset&&this.hadMove&&this.onReset(),this.xDown=this.yDown=null,this.hadMove=!1},this.handleStart=e=>{const t=Gt(e);if(this.verifyTouchTarget&&!this.verifyTouchTarget(e))return this.reset();this.xDown=t.clientX,this.yDown=t.clientY,he.a?Wt.addEventListener("touchmove",this.handleMove,{passive:!1,capture:!0}):Wt.addEventListener("mousemove",this.handleMove,!1)},this.handleMove=e=>{if(null===this.xDown||null===this.yDown||qt)return void this.reset();this.cancelEvent&&Object(c.a)(e);const t=Gt(e),s=t.clientX,i=t.clientY,n=this.xDown-s,a=this.yDown-i;if(!this.hadMove){if(!n&&!a)return;this.hadMove=!0,he.a||this.setCursorTo.style.setProperty("cursor",this.cursor,"important"),this.onFirstSwipe&&this.onFirstSwipe()}const o=this.onSwipe(n,a,e);void 0!==o&&o&&this.reset()},Object(w.a)(this,e),this.setCursorTo=this.element,this.setListeners()}setListeners(){he.a?(this.element.addEventListener("touchstart",this.handleStart,this.listenerOptions),Wt.addEventListener("touchend",this.reset)):(this.element.addEventListener("mousedown",this.handleStart,this.listenerOptions),Wt.addEventListener("mouseup",this.reset))}removeListeners(){he.a?(this.element.removeEventListener("touchstart",this.handleStart,this.listenerOptions),Wt.removeEventListener("touchend",this.reset)):(this.element.removeEventListener("mousedown",this.handleStart,this.listenerOptions),Wt.removeEventListener("mouseup",this.reset))}setCursor(e){this.cursor=e,!he.a&&this.hadMove&&this.setCursorTo.style.setProperty("cursor",this.cursor,"important")}}var $t=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Yt{constructor(e){this.scrollable=e,this.processItem=e=>{const t=document.createElement("div");let s;t.classList.add(Yt.BASE_CLASS+"-avatar","media-container"),e&&(s="object"!=typeof e?r.a.getPhoto(e):e.action.photo);const i=new Image;i.classList.add("avatar-photo"),i.draggable=!1;const n=()=>{if(s){const e=Ps({container:t,photo:s,size:r.a.choosePhotoSize(s,420,420,!1),withoutPreloader:!0});[e.images.thumb,e.images.full].filter(Boolean).forEach(e=>{e.classList.add("avatar-photo")})}else{const e=o.a.getPeerPhoto(this.peerId);d.a.putAvatar(t,this.peerId,e,"photo_big",i)}};return this.avatars.childElementCount<=3?n():(this.intersectionObserver.observe(t),this.loadCallbacks.set(t,n)),this.avatars.append(t),this.addTab(),e},this.container=document.createElement("div"),this.container.classList.add(Yt.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(Yt.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(Yt.BASE_CLASS+"-gradient"),this.info=document.createElement("div"),this.info.classList.add(Yt.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(Yt.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add(Yt.BASE_CLASS+"-arrow","tgico-avatarprevious"),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add(Yt.BASE_CLASS+"-arrow",Yt.BASE_CLASS+"-arrow-next","tgico-avatarnext"),this.container.append(this.avatars,this.gradient,this.info,this.tabs,this.arrowPrevious,this.arrowNext),this.loadCallbacks=new Map,this.listenerSetter=new R.a;const t=()=>0===this.scrollable.scrollTop||(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.firstElementChild,position:"start"}),!1);let s=!1,i=!1;Object(l.b)(this.container,e=>$t(this,void 0,void 0,(function*(){if(i)return void Object(c.a)(e);if(s)return void(s=!1);if(!t())return;const n=this.container.getBoundingClientRect(),a=e.pageX,o=a-n.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||o>n.width*(1/3)&&o<n.width-n.width*(1/3)){const e=this.peerId,t=[];this.listLoader.previous.concat(this.listLoader.current,this.listLoader.next).forEach((e,s)=>{t.push({element:this.avatars.children[s],item:e})});const s=t.slice(0,this.listLoader.previous.length),n=t.slice(this.listLoader.previous.length+1),a=this.avatars.children[this.listLoader.previous.length];i=!0,mc(a,e,()=>e===this.peerId,this.listLoader.current,s,n),i=!1}else{const e=a>n.right-n.width/2;let t;this.avatars.classList.add("no-transition"),this.avatars.offsetLeft,t=0!==this.listLoader.index||e?this.listLoader.index===this.listLoader.count-1&&e?-(this.listLoader.count-1):e?1:-1:this.listLoader.count-1,this.listLoader.go(t),Object(Le.b)(()=>{this.avatars.classList.remove("no-transition")})}})),{listenerSetter:this.listenerSetter});const n=()=>{s=!0,document.body.addEventListener(he.a?"touchend":"click",e=>{s=!1},{once:!0})};let a=0,h=0,p=0,u=0;this.swipeHandler=new Qt({element:this.avatars,onSwipe:(e,t)=>{p=e;let s=h+e*-Yt.SCALE;return s>0?s=0:s<u&&(s=u),this.avatars.style.transform=Yt.TRANSLATE_TEMPLATE.replace("{x}",s+"px"),!1},verifyTouchTarget:e=>t()?!this.container.classList.contains("is-single")&&!i:(n(),Object(c.a)(e),!1),onFirstSwipe:()=>{const e=this.avatars.getBoundingClientRect();a=e.width,u=-a*(this.tabs.childElementCount-1),h=e.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=Yt.TRANSLATE_TEMPLATE.replace("{x}",h+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const e=Math.ceil(Math.abs(p)/(a/Yt.SCALE))*(p>=0?1:-1);n(),this.avatars.classList.remove("no-transition"),Object(Le.b)(()=>{this.listLoader.go(e),this.container.classList.remove("is-swiping")})}});this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&this.loadNearestToTarget(e.target)})})}setPeer(e){this.peerId=e;const t=o.a.getPeerPhoto(e);if(!t)return;const s=this.listLoader=new S({loadCount:50,loadMore:(t,a,o)=>{if(!a)return Promise.resolve({count:void 0,items:[]});if(e.isUser()){const s=t;return r.a.getUserPhotos(e,s,o).then(e=>({count:e.count,items:e.photos}))}{const t=[];return s.current||t.push(Promise.resolve(n.default.getChatFull(e.toChatId()))),t.push(i.a.getSearch({peerId:e,maxId:Number.MAX_SAFE_INTEGER,inputFilter:{_:"inputMessagesFilterChatPhotos"},limit:o,backLimit:0})),Promise.all(t).then(e=>{const t=e.pop();if(y(t),!s.current){const n=e[0],a=Object(Lt.a)(t.history,e=>e.action.photo.id===n.chat_photo.id);s.current=a||i.a.generateFakeAvatarMessage(this.peerId,n.chat_photo)}return{count:t.count,items:t.history}})}},processItem:this.processItem,onJump:(e,t)=>{const s=this.listLoader.index,i=100*Yt.SCALE*s;this.avatars.style.transform=Yt.TRANSLATE_TEMPLATE.replace("{x}",`-${i}%`);const n=this.tabs.querySelector(".active");n&&n.classList.remove("active");this.tabs.children[s].classList.add("active"),this.loadNearestToTarget(this.avatars.children[s])}});"userProfilePhoto"===t._&&(s.current=t.photo_id),this.processItem(s.current),s.load(!0)}addTab(){const e=document.createElement("div");e.classList.add(Yt.BASE_CLASS+"-tab"),this.tabs.append(e),1===this.tabs.childElementCount&&e.classList.add("active"),this.container.classList.toggle("is-single",this.tabs.childElementCount<=1)}loadNearestToTarget(e){const t=Array.from(e.parentElement.children),s=t.indexOf(e);t.slice(Math.max(0,s-3),Math.min(t.length,s+3)).forEach(e=>{const t=this.loadCallbacks.get(e);t&&(t(),this.loadCallbacks.delete(e),this.intersectionObserver.unobserve(e))})}cleanup(){this.listenerSetter.removeAll(),this.swipeHandler.removeListeners()}}Yt.BASE_CLASS="profile-avatars",Yt.SCALE=Ht?2:1,Yt.TRANSLATE_TEMPLATE=Ht?`translate3d({x}, 0, -1px) scale(${Yt.SCALE})`:"translate({x}, 0)";let Xt=(e,t)=>{Object(m.a)(t.title,e||""),t.container.style.display=e?"":"none"};class Jt{constructor(e,t,s=!0){this.scrollable=e,this.listenerSetter=t,this.isDialog=s,this.setPeerStatus=(e=!1)=>{const t=this.peerId;this.element.classList.toggle("is-me",t===a.a.myId),!t||a.a.myId===t&&this.isDialog||nc.setPeerStatus(this.peerId,this.subtitle,e,!0,()=>t===this.peerId,!this.isDialog)},Ht||this.scrollable.container.classList.add("no-parallax"),t||(this.listenerSetter=new R.a)}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content"),this.section=new Kn({noDelimiter:!0}),this.avatar=new fc,this.avatar.classList.add("profile-avatar","avatar-120"),this.avatar.isDialog=this.isDialog,this.avatar.attachClickEvent(),this.name=document.createElement("div"),this.name.classList.add("profile-name"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("profile-subtitle"),this.bio=new Ze({title:" ",subtitleLangKey:"UserBio",icon:"info",clickable:e=>{"A"!==e.target.tagName&&Promise.resolve(n.default.getProfileByPeerId(this.peerId)).then(e=>{tt(e.about),ot(T.c.format("BioCopied",!0))})}}),this.bio.title.classList.add("pre-wrap"),this.username=new Ze({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{tt("@"+o.a.getPeer(this.peerId).username),ot(T.c.format("UsernameCopied",!0))}}),this.phone=new Ze({title:" ",subtitleLangKey:"Phone",icon:"phone",clickable:()=>{tt("+"+E.a.getUser(this.peerId).phone),ot(T.c.format("PhoneCopied",!0))}}),this.link=new Ze({title:" ",subtitleLangKey:"SetUrlPlaceholder",icon:"link",clickable:()=>{tt(this.link.title.textContent),ot(T.c.format("LinkCopied",!0))}}),this.location=new Ze({title:" ",subtitleLangKey:"ChatLocation",icon:"location"}),this.section.content.append(this.phone.container,this.username.container,this.location.container,this.bio.container,this.link.container);const{listenerSetter:e}=this;this.isDialog&&(this.notifications=new Ze({checkboxField:new pt.a({toggle:!0}),titleLangKey:"Notifications",icon:"unmute"}),e.add(this.notifications.checkboxField.input)("change",e=>{e.isTrusted&&i.a.togglePeerMute(this.peerId)}),e.add(a.a)("dialog_notify_settings",e=>{if(this.peerId===e.peerId){const e=Bt.a.isPeerLocalMuted(this.peerId,!1);this.notifications.checkboxField.checked=!e}}),this.section.content.append(this.notifications.container)),this.element.append(this.section.container),Ht&&this.element.append(Wn()),e.add(a.a)("peer_typings",({peerId:e})=>{this.peerId===e&&this.setPeerStatus()}),e.add(a.a)("peer_bio_edit",e=>{e===this.peerId&&this.setMoreDetails(!0)}),e.add(a.a)("peer_title_edit",e=>{e===this.peerId&&this.fillUsername()}),e.add(a.a)("user_update",e=>{this.peerId===e.toPeerId()&&this.setPeerStatus()}),e.add(a.a)("contacts_update",e=>{if(this.peerId===e.toPeerId()){E.a.getUser(e).pFlags.self&&this.isDialog||this.fillUserPhone()}}),e.add(a.a)("avatar_update",e=>{this.peerId===e&&this.setAvatar()}),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4)}cleanupHTML(){[this.bio,this.phone,this.username,this.location,this.link].forEach(e=>{e.container.style.display="none"}),this.notifications&&(this.notifications.container.style.display="",this.notifications.checkboxField.checked=!0),this.setMoreDetailsTimeout&&(window.clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=0)}canBeDetailed(){return this.peerId!==a.a.myId||!this.isDialog}setAvatar(){if(this.canBeDetailed()){if(o.a.getPeerPhoto(this.peerId)){const e=this.avatars;return this.avatars=new Yt(this.scrollable),this.avatars.setPeer(this.peerId),this.avatars.info.append(this.name,this.subtitle),this.avatar.remove(),e?e.container.replaceWith(this.avatars.container):this.element.prepend(this.avatars.container),void(Ht&&this.scrollable.container.classList.add("parallax"))}}Ht&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars.cleanup(),this.avatars=void 0),this.avatar.updateWithOptions({peerId:this.peerId}),this.section.content.prepend(this.avatar,this.name,this.subtitle)}fillUsername(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=o.a.getPeerUsername(e);Xt(t,this.username)}}fillUserPhone(){const{peerId:e}=this;if(e.isUser()&&this.canBeDetailed()){const t=E.a.getUser(e);Xt(t.phone?E.a.formatUserPhone(t.phone):void 0,this.phone)}}fillNotifications(){const e=this.notifications;if(e)if(this.canBeDetailed()){const t=Bt.a.isPeerLocalMuted(this.peerId,!1);e.checkboxField.checked=!t}else Object(Le.b)(()=>{e.container.style.display="none"})}fillRows(){const e=this.peerId;this.fillUsername(),this.fillUserPhone(),this.fillNotifications(),this.setMoreDetails(),Object(k.a)(this.name,new wt.a({peerId:e,dialog:this.isDialog}).element),this.name.append(...Kt(e)),this.setPeerStatus(!0)}fillProfileElements(){this.cleaned&&(this.cleaned=!1,this.cleanupHTML(),this.setAvatar(),this.fillRows())}setMoreDetails(e){this.setMoreDetailsTimeout&&(window.clearTimeout(this.setMoreDetailsTimeout),this.setMoreDetailsTimeout=0);const t=this.peerId,s=this.threadId;t&&!o.a.isRestricted(t)&&this.canBeDetailed()&&Object(zt.a)(n.default.getProfileByPeerId(t,e),e=>{if(this.peerId!==t||this.threadId!==s||o.a.isRestricted(t))return;if(Xt(e.about?X.b.wrapRichText(e.about):void 0,this.bio),!t.isUser()){const s=G.a.getChat(t.toChatId());if(s.username)Xt("https://t.me/"+s.username,this.link);else{const t=e.exported_invite;t&&Xt(t.link,this.link)}}const i=e.location;"channelLocation"==(null==i?void 0:i._)&&Xt(i.address,this.location),this.setMoreDetailsTimeout=window.setTimeout(()=>this.setMoreDetails(!0),6e4)})}setPeer(e,t=0){this.peerId===e&&this.threadId===t||(this.init&&this.init(),this.peerId=e,this.threadId=t,this.cleaned=!0)}}class Zt extends H{constructor(e){super(e,!1),this.threadId=0,this.historiesStorage={}}init(){this.container.classList.add("shared-media-container","profile-container");const e=Object(B.a)("btn-icon sidebar-close-button",{noRipple:!0});this.closeBtn.replaceWith(e),this.closeBtn=e;const t=document.createElement("div");t.classList.add("animated-close-icon"),e.append(t);const s=document.createElement("div");s.className="transition slide-fade";const i=document.createElement("div");i.classList.add("transition-item"),this.title.append(Object(T.d)("Profile")),this.editBtn=N("edit"),i.append(this.title,this.editBtn);const n=document.createElement("div");n.classList.add("transition-item");const o=this.title.cloneNode();o.append(Object(T.d)("PeerInfo.SharedMedia")),n.append(o),s.append(i,n),this.header.append(s),this.profile=new Jt(this.scrollable),this.profile.init(),this.scrollable.append(this.profile.element);this.scrollable.onAdditionalScroll=()=>{const e=this.searchSuper.nav.getBoundingClientRect();if(!e.width)return;const t=e.top-1;r(t<=56)};const r=e=>{t.classList.toggle("state-back",e),this.searchSuper.container.classList.toggle("is-full-viewport",e),c(+e),e||this.searchSuper.cleanScrollPositions()},c=Object(_.a)(s,"slide-fade",400,null,!1);c(0),Object(l.b)(this.closeBtn,e=>{this.closeBtn.firstElementChild.classList.contains("state-back")?(this.scrollable.scrollIntoViewNew({element:this.scrollable.container.firstElementChild,position:"start"}),c(0),t.classList.remove("state-back")):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()}),Object(l.b)(this.editBtn,e=>{let t;t=this.peerId.isAnyChat()?new Rt(this.slider):new Nt(this.slider),t&&(t instanceof Rt?t.chatId=this.peerId.toChatId():t.peerId=this.peerId,t.open())}),a.a.addEventListener("contacts_update",e=>{this.peerId===e&&this.toggleEditBtn()}),a.a.addEventListener("chat_update",e=>{this.peerId===e.toPeerId(!0)&&this.toggleEditBtn()}),a.a.addEventListener("history_multiappend",e=>{for(const t in e)this.renderNewMessages(t.toPeerId(),Array.from(e[t]))}),a.a.addEventListener("history_delete",({peerId:e,msgs:t})=>{this.deleteDeletedMessages(e,Array.from(t))}),a.a.addEventListener("message_sent",({message:e})=>{this.renderNewMessages(e.peerId,[e.mid])}),this.searchSuper=new ui({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"PeerMedia.Members",type:"members"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:this.scrollable,onChangeTab:e=>{let t="members"===e.type&&a.a.settings.animationsEnabled?250:0;setTimeout(()=>{d.classList.toggle("is-hidden","members"!==e.type)},t)}}),this.searchSuper.scrollStartCallback=()=>{r(!0)},this.profile.element.append(this.searchSuper.container);const d=Q({icon:"addmember_filled"});this.content.append(d),d.addEventListener("click",()=>{const e=this.peerId,t=this.peerId.toChatId(),s=G.a.isChannel(t),i=(t,i)=>{let n,a,o,r,l;if(t.length>1)n="AddMembersAlertTitle",a=[Object(T.d)("Members",[t.length])],o="AddMembersAlertCountText",r=t.map(e=>{const t=document.createElement("b");return t.append(new wt.a({peerId:e}).element),t}),s||(l=[{text:"AddMembersForwardMessages",checked:!0}]);else{n="AddOneMemberAlertTitle",o="AddMembersAlertNamesText";const e=document.createElement("b");e.append(new wt.a({peerId:t[0]}).element),r=[e],s||(l=[{text:"AddOneMemberForwardMessages",textArgs:[new wt.a({peerId:t[0]}).element],checked:!0}])}r.push(new wt.a({peerId:e}).element),new ut("popup-add-members",{peerId:e,titleLangKey:n,descriptionLangKey:o,descriptionLangArgs:r,buttons:[{langKey:"Add",callback:i}],checkboxes:l}).show()},n=e=>{"USER_PRIVACY_RESTRICTED"===e.type&&rt({langPackKey:"InviteToGroupError"})};if(s){const e=new Ut(this.slider);e.open({type:"channel",skippable:!1,takeOut:s=>(i(s,()=>{const i=G.a.inviteToChannel(t,s);i.catch(n),e.attachToPromise(i)}),!1),title:"GroupAddMembers",placeholder:"SendMessageTo"})}else new Pt({peerTypes:["contacts"],placeholder:"Search",onSelect:e=>{setTimeout(()=>{i([e],s=>{G.a.addChatUser(t,e,s.size?void 0:0).catch(n)})},0)}})})}renderNewMessages(e,t){if(!this.init&&this.historiesStorage[e]){t=t.slice().reverse();for(const s of this.searchSuper.mediaTabs){const n=s.inputFilter,a=this.searchSuper.filterMessagesByType(t.map(t=>i.a.getMessageByPeer(e,t)),n);if(a.length){const t=this.historiesStorage[e][n];t&&t.unshift(...a.map(e=>({mid:e.mid,peerId:e.peerId}))),this.peerId===e&&-1!==this.searchSuper.usedFromHistory[n]&&(this.searchSuper.usedFromHistory[n]+=a.length,this.searchSuper.performSearchResult(a,s,!1))}}}}deleteDeletedMessages(e,t){if(!this.init&&this.historiesStorage[e]){for(const s of t)for(const t of this.searchSuper.mediaTabs){const i=t.inputFilter,n=this.historiesStorage[e][i];if(!n)continue;const a=n.findIndex(e=>e.mid===s);if(-1!==a&&(n.splice(a,1),this.peerId===e)){const t=this.searchSuper.tabs[i].querySelector(`[data-mid="${s}"][data-peer-id="${e}"]`);t&&(this.searchSuper.selection.isSelecting&&this.searchSuper.selection.toggleByElement(t),t.remove()),this.searchSuper.usedFromHistory[i]>=a+1&&this.searchSuper.usedFromHistory[i]--}}this.scrollable.onScroll()}}cleanupHTML(){this.profile.cleanupHTML(),this.editBtn.classList.add("hide"),this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",this.searchSuper.canViewMembers()&&G.a.hasRights(this.peerId.toChatId(),"invite_users"))}setLoadMutex(e){this.searchSuper.loadMutex=e}setPeer(e,t=0){var s;return(this.peerId!==e||this.threadId!==t)&&(this.peerId=e,this.threadId=t,this.peerChanged=!0,this.init&&(this.init(),this.init=null),this.searchSuper.setQuery({peerId:e,historyStorage:null!==(s=this.historiesStorage[e])&&void 0!==s?s:this.historiesStorage[e]={}}),this.profile.setPeer(e,t),!0)}fillProfileElements(){this.peerChanged&&(this.peerChanged=!1,this.cleanupHTML(),this.profile.fillProfileElements(),this.toggleEditBtn())}toggleEditBtn(){let e;e=this.peerId.isUser()?this.peerId!==a.a.myId&&E.a.isContact(this.peerId.toUserId()):G.a.hasRights(this.peerId.toChatId(),"change_info"),this.editBtn.classList.toggle("hide",!e)}loadSidebarMedia(e,t=!1){this.searchSuper.load(e,t)}onOpenAfterTimeout(){this.scrollable.onScroll()}}const es=new class extends K{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1,b.b.addEventListener("changeScreen",(e,t)=>{t===b.a.medium&&e!==b.a.mobile&&this.toggleSidebar(!1)}),b.b.addEventListener("resize",()=>{this.setColumnProportion()}),this.sharedMediaTab=new Zt(this)}onCloseTab(e,t,s){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,s)}setColumnProportion(){const e=this.sidebarEl.scrollWidth/this.sidebarEl.previousElementSibling.scrollWidth;document.documentElement.style.setProperty("--right-column-proportion",""+e)}toggleSidebar(e,t){const s=document.body.classList.contains("is-right-column-shown");let i;if(void 0!==e?e?s||(i=!0):s&&(i=!0):i=!0,!i)return Promise.resolve();s||this.historyTabIds.length||this.sharedMediaTab.open(),this.isColumnProportionSet||(this.setColumnProportion(),this.isColumnProportionSet=!0);const n=nc.selectTab(s?1:2,t);return document.body.classList.toggle("is-right-column-shown",e),n}};le.a.appSidebarRight=es;var ts=es;class ss extends H{init(){this.container.id="poll-results-container",this.container.classList.add("chatlist-container"),this.resultsDiv=document.createElement("div"),this.resultsDiv.classList.add("poll-results"),this.scrollable.append(this.resultsDiv)}open(e){const t=super.open(),s=$e.a.getPoll(e.media.poll.id);this.setTitle(s.poll.pFlags.quiz?"PollResults.Title.Quiz":"PollResults.Title.Poll");const i=document.createElement("h3");Object(m.a)(i,X.a.wrapEmojiText(s.poll.question));const n=s.results.results.map(e=>e.voters/s.results.total_voters*100);os(n);const a=document.createDocumentFragment();return s.results.results.forEach((t,i)=>{if(!t.voters)return;const o=document.createElement("hr"),r=s.poll.answers[i],l=document.createElement("div");l.classList.add("poll-results-answer");const c=document.createElement("div");Object(m.a)(c,X.a.wrapEmojiText(r.text));const d=document.createElement("div");d.innerText=Math.round(n[i])+"%",l.append(c,d);const h=_c.createChatList();h.classList.add("poll-results-voters"),_c.setListClickListener(h,()=>{ts.onCloseBtnClick()},void 0,!0),h.style.minHeight=50*Math.min(t.voters,4)+"px",a.append(o,l,h);let p,u=4,g=!1,b=t.voters-4;const v=()=>{g||(g=!0,$e.a.getVotes(e,r.option,p,u).then(e=>{e.votes.forEach(e=>{const{dom:t}=_c.addDialogNew({dialog:e.user_id.toPeerId(!1),container:h,drawStatus:!1,rippleEnabled:!1,meAsSaved:!1,avatarSize:32});t.lastMessageSpan.parentElement.remove()}),p&&(b-=e.votes.length,f.lastElementChild.replaceWith(Object(T.d)("PollResults.LoadMore",[Math.min(20,b)]))),p=e.next_offset,u=20,b&&e.votes.length||f.remove()}).finally(()=>{g=!1}))};if(v(),b<=0)return;const f=document.createElement("div");f.classList.add("poll-results-more","show-more","rp-overflow"),f.addEventListener("click",v),Object(te.a)(f);const y=document.createElement("div");y.classList.add("tgico-down"),f.append(y,Object(T.d)("PollResults.LoadMore",[Math.min(20,b)])),a.append(f)}),this.resultsDiv.append(i,a),ts.toggleSidebar(!0).then(()=>{}),t}}var is=s(74);class ns{constructor(e){this.lazyLoadQueue=e.lazyLoadQueue,this.avatarSize=e.avatarSize,this.container=document.createElement("div"),this.container.classList.add("stacked-avatars"),this.container.style.setProperty("--avatar-size",e.avatarSize+"px")}render(e,t){const s=this.container.children;(e=e.slice().reverse()).length>3&&(e=e.slice(-3)),e.forEach((e,i)=>{let n=s[i];n||(n=document.createElement("div"),n.classList.add("stacked-avatars-avatar-container"));let a=n.firstElementChild;a||(a=new fc,a.classList.add("avatar-"+this.avatarSize,"stacked-avatars-avatar"),a.updateOptions({isDialog:!1,loadPromises:t})),a.updateWithOptions({lazyLoadQueue:this.lazyLoadQueue,peerId:e}),a.parentNode||n.append(a),n.parentNode||this.container.append(n)}),Array.from(s).slice(e.length).forEach(e=>e.remove())}}let as=0;const os=e=>{const t=e.reduce((e,t)=>e+Math.round(t),0);if(t>100){const s=t-100,i=e.length;for(let t=0;t<s;++t){let t=-1,s=1;for(let n=0;n<i;++n){let i=e[n]%1;i>=.5&&i<s&&(s=i,t=n)}if(-1===t)return;e[t]-=s}}else if(t<100){const s=100-t,i=e.length;for(let t=0;t<s;++t){let t=-1,s=0;for(let n=0;n<i;++n){let i=e[n]%1;i<.5&&i>s&&(s=i,t=n)}if(-1===t)return;e[t]+=1-s}}};a.a.addEventListener("poll_update",({poll:e,results:t})=>{Array.from(document.querySelectorAll(`poll-element[poll-id="${e.id}"]`)).forEach(s=>{s.isClosed=!!e.pFlags.closed,s.performResults(t,e.chosenIndexes)})}),a.a.addEventListener("peer_changed",()=>{ls&&rs(ls,cs,ds)}),b.b.addEventListener("resize",()=>{hs.setMaxLength(),hs.resizePolls()}),b.b.addEventListener("changeScreen",()=>{hs.setMaxLength()});const rs=(e,t,s)=>{e.classList.remove("active"),clearTimeout(s),setTimeout(()=>{t(),e.remove(),ls===e&&cs===t&&ds===s&&(ls=cs=null,ds=0)},200)};let ls,cs,ds;class hs extends HTMLElement{constructor(){super(),this.isClosed=!1,this.isQuiz=!1,this.isRetracted=!1,this.isPublic=!1,this.isMultiple=!1,this.chosenIndexes=[],this.chosingIndexes=[],this.sentVote=!1}static setMaxLength(){const e=St.a.width<=360?St.a.width-120:b.b.active.poll.width;this.MAX_LENGTH=e+9+this.MAX_OFFSET+-13.7}static resizePolls(){if(!this.MAX_LENGTH)return;Array.from(document.querySelectorAll("poll-element.is-voted")).forEach(e=>{e.svgLines.forEach((t,s)=>{e.setLineProgress(s,1)})})}render(){as||(as=document.getElementById("poll-line").getTotalLength(),hs.setMaxLength());const e=this.message.media.poll.id,{poll:t,results:s}=$e.a.getPoll(e);let i;this.message.pFlags.is_scheduled&&this.classList.add("disable-hover"),t.pFlags&&(this.isPublic=!!t.pFlags.public_voters,this.isQuiz=!!t.pFlags.quiz,this.isClosed=!!t.pFlags.closed,this.isMultiple=!!t.pFlags.multiple_choice,this.isClosed?(i="Chat.Poll.Type.Closed",this.classList.add("is-closed")):i=this.isQuiz?this.isPublic?"Chat.Poll.Type.Quiz":"Chat.Poll.Type.AnonymousQuiz":this.isPublic?"Chat.Poll.Type.Public":"Chat.Poll.Type.Anonymous"),this.classList.toggle("is-multiple",this.isMultiple);const n=this.isMultiple?'<span class="poll-answer-selected tgico-check"></span>':"",a=t.answers.map((e,t)=>`\n <div class="poll-answer" data-index="${t}">\n <div class="circle-hover">\n <div class="animation-ring"></div>\n <svg class="progress-ring">\n <circle class="progress-ring__circle" cx="13" cy="13" r="9"></circle>\n </svg>\n ${n}\n </div>\n <div class="poll-answer-percents"></div>\n <div class="poll-answer-text"></div>\n <svg version="1.1" class="poll-line" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 485.9 35" xml:space="preserve">\n <use href="#poll-line"></use>\n </svg>\n <span class="poll-answer-selected tgico"></span>\n </div>\n `).join("");if(this.innerHTML='\n <div class="poll-title"></div>\n <div class="poll-desc">\n <div class="poll-type"></div>\n <div class="poll-avatars"></div>\n </div>\n '+a,Object(m.a)(this.firstElementChild,X.a.wrapEmojiText(t.question)),Array.from(this.querySelectorAll(".poll-answer-text")).forEach((e,s)=>{Object(m.a)(e,X.a.wrapEmojiText(t.answers[s].text))}),this.descDiv=this.firstElementChild.nextElementSibling,this.typeDiv=this.descDiv.firstElementChild,this.avatarsDiv=this.descDiv.lastElementChild,i&&this.typeDiv.append(Object(T.d)(i)),this.isQuiz&&(this.classList.add("is-quiz"),t.close_period&&t.close_date)){const e=document.createElement("div");e.classList.add("poll-time"),this.descDiv.append(e);const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.classList.add("poll-quiz-timer"),this.quizTimer=s;const i=2,n=7,a=2*Math.PI*n,o=document.createElementNS("http://www.w3.org/2000/svg","circle");o.classList.add("poll-quiz-timer-circle"),o.setAttributeNS(null,"cx","16"),o.setAttributeNS(null,"cy","16"),o.setAttributeNS(null,"r",""+n),o.setAttributeNS(null,"stroke-width",""+i),s.append(o),this.descDiv.append(s);const r=1e3*t.close_period,l=1e3*(t.close_date-Ye.a.serverTimeOffset);this.quizInterval=window.setInterval(()=>{const t=Date.now(),s=(l-t)/r,i=(l-t)/1e3+1|0;e.innerHTML=Te(i),i<=5&&(e.style.color="#ee545c",o.style.stroke="#ee545c"),o.style.strokeDashoffset=a+s*a,o.style.strokeDasharray=`${a} ${a}`,t>=l&&(clearInterval(this.quizInterval),e.innerHTML="",o.style.strokeDashoffset=a,this.quizInterval=0,setTimeout(()=>{$e.a.getResults(this.message)},3e3))},1e3)}this.answerDivs=Array.from(this.querySelectorAll(".poll-answer")),this.svgLines=Array.from(this.querySelectorAll(".poll-line")),this.numberDivs=Array.from(this.querySelectorAll(".poll-answer-percents"));const o=document.createElement("div");o.classList.add("poll-footer"),this.viewResults=document.createElement("div"),this.viewResults.className="poll-footer-button poll-view-results hide",this.viewResults.append(Object(T.d)("Chat.Poll.ViewResults")),this.votersCountDiv=document.createElement("div"),this.votersCountDiv.className="poll-votes-count",o.append(this.viewResults,this.votersCountDiv),this.append(o),this.viewResults.addEventListener("click",e=>{Object(c.a)(e),ts.isTabExists(ss)||new ss(ts).open(this.message)}),Object(te.a)(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append(Object(T.d)("Chat.Poll.SubmitVote")),Object(te.a)(this.sendVoteBtn),t.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),Object(l.b)(this.sendVoteBtn,e=>{Object(c.a)(e),this.chosingIndexes.length&&this.sendVotes(this.chosingIndexes).then(()=>{this.chosingIndexes.length=0,this.answerDivs.forEach(e=>{e.classList.remove("is-chosing")})})}),o.append(this.sendVoteBtn));const r=!(t.chosenIndexes.length||this.isClosed);r&&!this.isPublic||this.performResults(s,t.chosenIndexes,!1),r&&(this.setVotersCount(s),Object(l.b)(this,this.clickHandler))}initQuizHint(e){if(e.solution&&e.solution_entities){const t=document.createElement("div");if(t.classList.add("tgico-tip","poll-hint"),this.descDiv.append(t),Object(l.b)(t,s=>{Object(c.a)(s),t.classList.add("active"),((e,t,s)=>{ls&&rs(ls,cs,ds);const i=document.createElement("div");i.classList.add("quiz-hint");const n=document.createElement("div");n.classList.add("container","tgico");const a=document.createElement("div");a.classList.add("text"),n.append(a),i.append(n),Object(m.a)(a,X.a.wrapRichText(e,{entities:t})),nc.chat.bubbles.bubblesContainer.append(i),i.offsetLeft,i.classList.add("active"),ls=i,cs=s,ds=window.setTimeout(()=>{rs(i,s,ds)},he.a?5e3:7e3)})(e.solution,e.solution_entities,()=>{t.classList.remove("active")})}),this.sentVote){const s=e.results.find(e=>e.pFlags.correct);s&&!s.pFlags.chosen&&t.click()}}}clickHandler(e){const t=Object(Ce.a)(e.target,"poll-answer");if(!t)return;Object(c.a)(e);const s=+t.dataset.index;if(this.isMultiple){t.classList.toggle("is-chosing");const e=this.chosingIndexes.indexOf(s);-1!==e?this.chosingIndexes.splice(e,1):this.chosingIndexes.push(s)}else this.sendVotes([s])}sendVotes(e){if(this.sendVotePromise)return this.sendVotePromise;const t=this.answerDivs.filter((t,s)=>e.includes(s));return t.forEach(e=>{e.classList.add("is-voting")}),this.classList.add("disable-hover"),this.sentVote=!0,this.sendVotePromise=$e.a.sendVote(this.message,e).then(()=>{t.forEach(e=>{e.classList.remove("is-voting")}),this.classList.remove("disable-hover")}).catch(()=>{this.sentVote=!1}).finally(()=>{this.sendVotePromise=null})}performResults(e,t,s=!0){var i,n;if(a.a.settings.animationsEnabled||(s=!1),this.isQuiz&&((null===(i=e.results)||void 0===i?void 0:i.length)||this.isClosed)){this.answerDivs.forEach((t,s)=>{t.classList.toggle("is-correct",!!e.results[s].pFlags.correct)}),this.initQuizHint&&(this.initQuizHint(e),this.initQuizHint=null),this.quizInterval&&(clearInterval(this.quizInterval),this.quizInterval=0),(null===(n=this.quizTimer)||void 0===n?void 0:n.parentElement)&&this.quizTimer.remove();const t=this.descDiv.querySelector(".poll-time");t&&t.remove()}if(this.isClosed&&(this.classList.add("is-closed"),Object(k.a)(this.typeDiv,Object(T.d)("Chat.Poll.Type.Closed"))),(this.chosenIndexes.length!==t.length||this.isClosed)&&(this.isRetracted=this.chosenIndexes.length&&!t.length,this.chosenIndexes=t.slice(),this.isRetracted?Object(l.b)(this,this.clickHandler):Object(l.c)(this,this.clickHandler)),this.chosenIndexes.length||this.isRetracted||this.isClosed){const t=e.results.map(t=>e.total_voters?t.voters/e.total_voters*100:0);this.classList.toggle("no-transition",!s),s&&Object(is.a)(this,"",!this.isRetracted,340),Object(Le.b)(()=>{this.setResults(this.isRetracted?this.percents:t,this.chosenIndexes,s),this.percents=t,this.isRetracted=!1})}if(this.setVotersCount(e),this.isPublic){this.isMultiple||(this.viewResults.classList.toggle("hide",!e.total_voters||!this.chosenIndexes.length),this.votersCountDiv.classList.toggle("hide",!!this.chosenIndexes.length));const t=(e.recent_voters||[]).map(e=>e.toPeerId()),s=new ns({avatarSize:16});s.render(t),Object(k.a)(this.avatarsDiv,s.container)}if(this.isMultiple){const t=!!this.chosenIndexes.length,s=this.isClosed||t,i=!this.isPublic||!e.total_voters||!t&&!this.isClosed;this.sendVoteBtn.classList.toggle("hide",s),this.viewResults.classList.toggle("hide",i),this.votersCountDiv.classList.toggle("hide",!s||!i)}}setResults(e,t,s){this.svgLines.forEach(e=>e.style.display=""),this.answerDivs.forEach((e,s)=>{e.classList.toggle("is-chosen",t.includes(s))});const i=Math.max(...e);if(this.maxPercents=e.map(e=>e/i),this.isRetracted)this.svgLines.forEach((e,t)=>{this.setLineProgress(t,-1)});else{const e=()=>{this.svgLines.forEach((e,t)=>{this.setLineProgress(t,1)})};s?Object(Le.b)(e):e()}let n;e=e.slice(),os(e);const a=t=>{e.forEach((e,s)=>{const i=n(e,t);this.numberDivs[s].innerText=i+"%"})};if(this.isRetracted)if(n=(e,t)=>Math.round(e/10*t),s)for(let e=9,t=0;e>=0;--e,++t)setTimeout(()=>{a(e)},34*t);else a(0);else if(n=(e,t)=>Math.round(e/10*(t+1)),s)for(let e=0;e<10;++e)setTimeout(()=>{a(e)},34*e);else a(9);if(this.isRetracted){s&&this.classList.add("is-retracting"),this.classList.remove("is-voted");const e=()=>{this.svgLines.forEach(e=>e.style.display="none")};s?setTimeout(()=>{this.classList.remove("is-retracting"),e()},340):e()}else this.classList.add("is-voted")}setVotersCount(e){const t=e.total_voters||0;let s,i=[t];s=this.isClosed?this.isQuiz?t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesResultEmpty":t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesResultEmpty":this.isQuiz?t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesEmpty":t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesEmpty",Object(k.a)(this.votersCountDiv,Object(T.d)(s,i))}setLineProgress(e,t){const s=this.svgLines[e];-1===t?(s.style.strokeDasharray="",s.style.strokeDashoffset=""):(s.style.strokeDasharray=t*this.maxPercents[e]*hs.MAX_LENGTH+", 485.9",s.style.strokeDashoffset=""+t*hs.MAX_OFFSET)}}hs.MAX_OFFSET=-46.5,hs.MAX_LENGTH=0,customElements.define("poll-element",hs);var ps=s(99),us=s(141),gs=s(81),ms=s(103),bs=s(153),vs=s(151),fs=s(46),ys=s(88),ws=s(22),Ss=s(172);function Cs(e={}){const t=document.createElement("video");return e.pip||(t.disablePictureInPicture=!0),t.setAttribute("playsinline","true"),t}var Ls=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};let Is=0;function Ms({doc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:o,isOut:r,middleware:d,lazyLoadQueue:h,noInfo:p,group:u,onlyPreview:g,withoutPreloader:m,loadPromises:v,noPlayButton:f,size:y,searchContext:w,autoDownload:S}){var C,M;const E=null==S?void 0:S.video;let P=0===E;const k=!(i&&n),T=("video"!==e.type||e.size<=52428800&&!k)&&("gif"===e.type?a.a.settings.autoPlay.gifs:a.a.settings.autoPlay.videos);let x,A;if(!p){x=document.createElement("span"),x.classList.add("video-time"),t.append(x);let s=!1;"gif"!==e.type?(x.innerText=Te(e.duration,!1),f||"round"===e.type||(T&&!P?x.classList.add("tgico","can-autoplay"):s=!0)):(x.innerText="GIF",T||f||(s=!0,P=void 0)),s&&(A=document.createElement("span"),A.classList.add("video-play","tgico-largeplay","btn-circle","position-center"),t.append(A))}let O,j={};if("image/gif"===e.mime_type){const a=Ps({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:h,middleware:d,withoutPreloader:m,loadPromises:v,autoDownloadSize:E,size:y});return j.thumb=a,j.loadPromise=a.loadPromises.full,j}const _=Cs();if(_.classList.add("media-video"),_.muted=!0,"round"===e.type){const i=document.createElement("div");i.classList.add("media-round","z-depth-1"),i.dataset.mid=""+s.mid,i.dataset.peerId=""+s.peerId,i.message=s;const n=b.b.active.round,a=n.width/2,o=3.5,r=a-2*o;i.innerHTML=`<svg class="progress-ring" width="${n.width}" height="${n.width}" style="transform: rotate(-90deg);">\n <circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="${o}" cx="${a}" cy="${a}" r="${r}" fill="transparent"/>\n </svg>`;const d=i.firstElementChild.firstElementChild;Is||(Is=2*Math.PI*r),d.style.strokeDasharray=Is+" "+Is,d.style.strokeDashoffset=""+Is,x.classList.add("tgico");s.pFlags.media_unread&&i.classList.add("is-unread");const h=document.createElement("canvas");h.width=h.height=e.w,i.prepend(h,x),i.append(_),t.append(i);const p=h.getContext("2d"),u=()=>{const e=i.message,t=fe.addMedia(e,!P),s=()=>{(nc.chat.setPeerPromise||Promise.resolve()).finally(()=>{Object(ms.a)(t)||(t.removeEventListener("play",r),t.removeEventListener("timeupdate",o),t.removeEventListener("pause",u),t.removeEventListener("ended",g))})},n=()=>{p.drawImage(t,0,0);const e=Is-t.currentTime/t.duration*Is;return d.style.strokeDashoffset=""+e,!t.paused},a=()=>{t.duration&&(Object(ms.a)(t)?(t.paused&&n(),x.innerText=Te(t.duration-t.currentTime,!1)):s())},o=Ie(a),r=()=>{_.classList.add("hide"),i.classList.remove("is-paused"),Object(Pe.b)(n,h),O&&O.preloader&&O.preloader.classList.contains("manual")&&O.onClick()},u=()=>{Object(ms.a)(t)?i.classList.add("is-paused"):s()},g=()=>{_.classList.remove("hide"),i.classList.add("is-paused"),_.currentTime=0,x.innerText=Te(t.duration,!1),t.currentTime&&(t.currentTime=0)};t.addEventListener("play",r),t.addEventListener("timeupdate",o),t.addEventListener("pause",u),t.addEventListener("ended",g),Object(l.b)(h,s=>{if(Object(c.a)(s),O&&!O.detached&&O.onClick(),t.paused){const s=!!w;if(fe.setSearchContext(w||{peerId:Me.c,inputFilter:{_:"inputMessagesFilterEmpty"},useSearch:!1})){const[t,n]=s?Fe(i,e.mid):[];fe.setTargets({peerId:e.peerId,mid:e.mid},t,n)}t.play()}else t.pause()}),t.paused?t.duration&&t.currentTime!==t.duration&&t.currentTime>0?(n(),a(),_.classList.add("hide")):u():r()};s.pFlags.is_outgoing?(i.onLoad=u,i.dataset.isOutgoing="1"):u()}else _.autoplay=!0;let F;if(s){if(F=Ps({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:h,middleware:d,withoutPreloader:!0,loadPromises:v,autoDownloadSize:null==S?void 0:S.photo,size:y}),j.thumb=F,!T&&"gif"!==e.type||g)return j.loadPromise=F.loadPromises.full,j;if(o){const e=(F.images.thumb||F.images.full).parentElement;_.width=+e.getAttributeNS(null,"width"),_.height=+e.getAttributeNS(null,"height"),e.append(_)}}else{const t=L.a.getThumb(e,!1);t&&t.promise.then(()=>{_.poster=t.cacheContext.url})}!_.parentElement&&t&&((null==F?void 0:F.aspecter)||t).append(_);const D=ce.a.getCacheContext(e),R=!!(null===(C=null==s?void 0:s.media)||void 0===C?void 0:C.preloader);R?(O=s.media.preloader,O.attach(t,!1),P=void 0):D.downloaded||e.supportsStreaming||m?e.supportsStreaming&&(O=new ye.a({cancelable:!1,attachMethod:"prepend"})):O=new ye.a({attachMethod:"prepend"});const B=Object(ie.a)();if(_.addEventListener("error",e=>{4!==_.error.code&&console.error("Error "+_.error.code+"; details: "+_.error.message),O&&!R&&O.detach(),B.isFulfilled||B.resolve()},{once:!0}),Object(pe.e)(_).then(()=>{u&&I.a.addAnimation(_,u),O&&!R&&O.detach(),B.resolve()}),"video"===e.type){const e=Ie(()=>{_.videoWidth&&(x.innerText=Te(_.duration-_.currentTime,!1))});_.addEventListener("timeupdate",e),A&&_.addEventListener("timeupdate",()=>{us.a.mutateElement(A,()=>{A.remove()})},{once:!0})}_.muted=!0,_.loop=!0,_.autoplay=!0;let N=P&&(null===(M=null==F?void 0:F.preloader)||void 0===M?void 0:M.loadFunc);const U=()=>{O&&P&&!m&&(O.construct(),O.setManual());let i=Promise.resolve();if(O&&!R||m)if(D.downloaded||e.supportsStreaming)e.supportsStreaming&&(P?i=Promise.reject():!D.downloaded&&O&&(O.attach(t,!1,null),_.addEventListener(ae.g?"timeupdate":"canplay",()=>{O.detach()},{once:!0})));else{const s=i=L.a.downloadDoc(e,null==h?void 0:h.queueId,P);O&&O.attach(t,!1,s)}return!P&&N&&(N(),N=null),P=void 0,i.then(()=>{!d||d()?("round"===e.type&&fe.resolveWaitingForLoadMedia(s.peerId,s.mid,s.pFlags.is_scheduled),Object(ps.a)(_,D.url)):B.resolve()},()=>{}),{download:i,render:B}};return O&&!R&&O.setDownloadFunction(U),"gif"!==e.type||T?j.loadPromise=h?(h.push({div:t,load:()=>U().render}),Promise.resolve()):U().render:Object(l.b)(t,e=>{Object(c.a)(e),A.remove(),U()},{capture:!0,once:!0}),j}function Es({message:e,withTime:t,fontWeight:s,voiceAsMusic:n,showSender:o,searchContext:c,loadPromises:d,autoDownloadSize:h,lazyLoadQueue:p,sizeType:u}){var m,b;s||(s=500),u||(u="");const v=0===h,f=e.media.document||e.media.webpage.document,y=e.pFlags.is_outgoing&&(null===(m=e.media)||void 0===m?void 0:m.preloader);if("audio"===f.type||"voice"===f.type||"round"===f.type){const i=new De;return i.withTime=t,i.message=e,i.noAutoDownload=v,i.lazyLoadQueue=p,i.loadPromises=d,n&&(i.voiceAsMusic=n),c&&(i.searchContext=c),o&&(i.showSender=o),y&&(i.preloader=e.media.preloader),i.dataset.fontWeight=""+s,i.dataset.sizeType=u,i.render(),i}let w=f.file_name?f.file_name.split("."):"",S="";S=w.length>1&&Array.isArray(w)?Object(bs.a)(w.pop().split(" ",1)[0].toLowerCase()):"file";let C=document.createElement("div");C.classList.add("document","ext-"+S),C.dataset.docId=""+f.id;const I=document.createElement("div");I.classList.add("document-ico");const M=ce.a.getCacheContext(f);if((null===(b=f.thumbs)||void 0===b?void 0:b.length)||e.pFlags.is_outgoing&&M.url&&"photo"===f.type){C.classList.add("document-with-thumb");let t=[];if(e.pFlags.is_outgoing&&["photo","video"].includes(f.type))I.innerHTML=`<img src="${M.url}">`,t.push(I.firstElementChild);else{const e=Ps({photo:f,message:null,container:I,boxWidth:54,boxHeight:54,loadPromises:d,withoutPreloader:!0,lazyLoadQueue:p,size:r.a.choosePhotoSize(f,54,54,!0)});I.style.width=I.style.height="",e.images.thumb&&t.push(e.images.thumb),e.images.full&&t.push(e.images.full)}t.forEach(e=>e.classList.add("document-thumb"))}else I.innerText=S;let E=f.file_name?X.b.wrapPlainText(f.file_name):"Unknown.file";document.createElement("div").classList.add("document-description");const P=[Ee(f.size)];t&&P.push(Object(ne.d)(e.date)),o&&P.push(i.a.wrapSenderToPeer(e)),C.innerHTML=`\n ${M.downloaded&&!y||!e.mid?"":'<div class="document-download"></div>'}\n <div class="document-name"></div>\n <div class="document-size"></div>\n `;const k=C.querySelector(".document-name"),x=new we.a;x.dataset.fontWeight=""+s,x.dataset.sizeType=u,x.textContent=E,k.append(x),o&&k.append(i.a.wrapSentTime(e));if(C.querySelector(".document-size").append(...Object(T.g)(P," · ")),C.prepend(I),!y&&e.pFlags.is_outgoing&&!e.mid)return C;let A,O=null;const j=()=>{if(A){A.classList.add("downloaded");const e=A;setTimeout(()=>{e.remove()},200),A=null}O&&(O=null)},_=e=>{var t;const s=!e||e.isTrusted,i=L.a.getDoc(C.dataset.docId);let n;const o=nc.chat.bubbles?nc.chat.bubbles.lazyLoadQueue.queueId:void 0;if(s)if("pdf"===i.type){const e=L.a.downloading.has(i.id)||M.downloaded;n=L.a.downloadDoc(i,o),e&&n.then(()=>{setTimeout(()=>{const e=ce.a.getCacheContext(i).url;window.open(e)},a.a.settings.animationsEnabled?250:0)})}else n=g.has(i.mime_type)&&(null===(t=i.thumbs)||void 0===t?void 0:t.length)?L.a.downloadDoc(i,o):L.a.saveDocFile(i,o);else n=L.a.downloadDoc(i,o);return A&&(n.then(j),O.attach(A,!0,n)),{download:n}};return L.a.downloading.has(f.id)?(A=C.querySelector(".document-download"),O=new ye.a,O.attach(A,!1,L.a.downloading.get(f.id))):M.downloaded&&!y||(A=C.querySelector(".document-download"),O=e.media.preloader,O?(O.attach(A),e.media.promise.then(j)):(O=new ye.a,O.construct(),O.setManual(),O.attach(A),O.setDownloadFunction(_),void 0!==h&&h>=f.size&&Object(l.d)(O.preloader))),Object(l.b)(C,e=>{O?O.onClick(e):_(e)}),C}function Ps({photo:e,message:t,container:s,boxWidth:i,boxHeight:n,withTail:o,isOut:l,lazyLoadQueue:c,middleware:d,size:h,withoutPreloader:p,loadPromises:u,autoDownloadSize:g,noBlur:m,noThumb:v,noFadeIn:f,blurAfter:y}){var w;if(!e.sizes&&!e.thumbs)return i&&n&&!h&&"document"===e._&&r.a.setAttachmentSize(e,s,i,n,void 0,t),{loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};let S=0===g;h||(void 0===i&&(i=b.b.active.regular.width),void 0===n&&(n=b.b.active.regular.height)),s.classList.add("media-container");let C,I,M,E=s,P=!0,k=Promise.resolve();const T="document"===e._&&"image/gif"===e.mime_type&&!h;if(I=new Image,i&&n&&!h){const a=r.a.setAttachmentSize(e,s,i,n,void 0,t,void 0,T?{_:"photoSize",w:e.w,h:e.h,size:e.size,type:"full"}:void 0);if(h=a.photoSize,P=a.isFit,M=ce.a.getCacheContext(e,h.type),!P){E=document.createElement("div"),E.classList.add("media-container-aspecter"),E.style.width=a.size.width+"px",E.style.height=a.size.height+"px";const i=r.a.getStrippedThumbIfNeeded(e,M,!m,!0);if(i){k=i.loadPromise;const e=i.image;e.classList.add("media-photo"),s.append(e)}else{Ps({container:s,message:t,photo:e,boxWidth:0,boxHeight:0,size:h,lazyLoadQueue:c,isOut:l,loadPromises:u,middleware:d,withoutPreloader:p,withTail:o,autoDownloadSize:g,noBlur:m,noThumb:!0,blurAfter:!0}).images.full.classList.add("media-photo","thumbnail")}s.classList.add("media-container-fitted"),s.append(E)}}else h||(h=r.a.choosePhotoSize(e,i,n,!0)),M=ce.a.getCacheContext(e,null==h?void 0:h.type);if(!v){const t=r.a.getStrippedThumbIfNeeded(e,M,!m);t&&(k=Promise.all([k,t.loadPromise]),C=t.image,C.classList.add("media-photo"),E.append(C))}I.classList.add("media-photo");const x=(C||!M.downloaded)&&a.a.settings.animationsEnabled&&!f;let A;(null===(w=null==t?void 0:t.media)||void 0===w?void 0:w.preloader)&&!p?(A=t.media.preloader,A.attach(s),S=void 0):M.downloaded||(A=new ye.a({attachMethod:"prepend"}));const O=e=>ks(s,I,e,x,E,C),j=()=>{if(d&&!d())return Promise.resolve();if(y){const e=Object(vs.a)(M.url,12);return e.promise.then(()=>O(e.canvas.toDataURL()))}return O(M.url)};let _;const F=h.w>=150&&h.h>=150||S,D=()=>{S&&!p&&A&&(A.construct(),A.setManual());const t=T&&!h?L.a.downloadDoc(e,null==c?void 0:c.queueId):r.a.preloadPhoto(e,h,null==c?void 0:c.queueId,S);A&&!M.downloaded&&!p&&F&&A.attach(s,!1,t),S=void 0;const i=t.then(j);return i.catch(()=>{}),{download:t,render:i}};return A&&A.setDownloadFunction(D),M.downloaded?k=_=D().render:c?c.push({div:s,load:()=>D().download}):_=D().render,u&&k&&u.push(k),{loadPromises:{thumb:k,full:_||Promise.resolve()},images:{thumb:C,full:I},preloader:A,aspecter:E}}function ks(e,t,s,i,n=e,a){return i&&t.classList.add("fade-in"),new Promise(o=>{Object(ps.a)(t,s,()=>{us.a.mutateElement(e,()=>{n.append(t),Object(Le.b)(()=>{o()}),i&&t.addEventListener("animationend",()=>{us.a.mutate(()=>{t.classList.remove("fade-in"),a&&a.remove()})},{once:!0})})})})}function Ts({size:e,doc:t,middleware:s,target:i,side:n,skipRatio:a,play:o}){const r=document.createElement("div");r.classList.add("emoji-animation"),r.style.width=e+"px",r.style.height=e+"px";const l=xs({div:r,doc:t,middleware:s,withThumb:!1,needFadeIn:!1,loop:!1,width:e,height:e,play:o,group:"none",skipRatio:a}).then(e=>(Object(ys.a)(e),e.addEventListener("enterFrame",t=>{t===e.maxFrame&&(e.remove(),r.remove(),nc.chat.bubbles.scrollable.container.removeEventListener("scroll",g))}),Ss.a&&e.addEventListener("firstFrame",()=>{navigator.vibrate(100)},{once:!0}),e)),c=e=>{const t=Math.random()*e*2;return t>e?-t%e:t},d=c(16),h=c(4),p=e/8*("right"===n?1:-1),u=()=>{if(!Object(ms.a)(i))return;const t=i.getBoundingClientRect(),s=("right"===n?t.right:t.left)+("center"===n?(t.width-e)/2:("right"===n?-e:0)+p+d),a=t.top+(t.height-e)/2+("center"===n?0:h);r.style.top=a+"px",r.style.left=s+"px"},g=Ie(u);return nc.chat.bubbles.scrollable.container.addEventListener("scroll",g),u(),nc.emojiAnimationContainer.append(r),{animationDiv:r,stickerPromise:l}}function xs({doc:e,div:t,middleware:s,lazyLoadQueue:n,group:o,play:d,onlyThumb:h,emoji:p,width:u,height:g,withThumb:m,loop:b,loadPromises:f,needFadeIn:y,needUpscale:w,skipRatio:S,static:C}){var M;const E=e.sticker;if(1===E&&(C=!0),u||(u=p?void 0:200),g||(g=p?void 0:200),2===E&&oe.a.loadLottieWorkers(),!E)throw console.error("wrong doc for wrapSticker!",e),new Error("wrong doc for wrapSticker!");let P;if(t.dataset.docId=""+e.id,t.classList.add("media-sticker-wrapper"),C&&1!==E){const t=r.a.choosePhotoSize(e,u,g,!1);P=ce.a.getCacheContext(e,t.type)}else P=ce.a.getCacheContext(e);const k=p?Object(se.d)(p):-1,T=P.downloaded&&!y,x=!C&&(2===E||3===E),A=x;let O=Object(ie.a)(),j=!1;if(((null===(M=e.thumbs)||void 0===M?void 0:M.length)||e.stickerCachedThumbs)&&!t.firstElementChild&&(!T||A||h)&&!1!==m){let i,a=e.stickerCachedThumbs&&e.stickerCachedThumbs[k]||e.thumbs[0];const o=()=>{t.childElementCount||(i.classList.add("media-sticker","thumbnail"),us.a.mutateElement(t,()=>{t.append(i),O.resolve()}))};if("url"in a)i=new Image,Object(ps.a)(i,a.url,o),j=!0;else if("bytes"in a){if("photoPathSize"===a._)if(a.bytes.length){const s=r.a.getPathFromPhotoPathSize(a),i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.classList.add("rlottie-vector","media-sticker","thumbnail"),i.setAttributeNS(null,"viewBox",`0 0 ${e.w||512} ${e.h||512}`);const n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttributeNS(null,"d",s),i.append(n),t.append(i)}else a=e.thumbs.find(e=>{var t;return null===(t=e.bytes)||void 0===t?void 0:t.length})||a;a&&"photoPathSize"!==a._&&k<=0&&(i=new Image,fs.a||e.pFlags.stickerThumbConverted||P.url?(Object(ps.a)(i,r.a.getPreviewURLFromThumb(e,a,!0),o),j=!0):re.a.convert(""+e.id,a.bytes).then(n=>{a.bytes=n,e.pFlags.stickerThumbConverted=!0,s&&!s()||t.childElementCount||Object(ps.a)(i,r.a.getPreviewURLFromThumb(e,a,!0),o)}).catch(()=>{}))}else if((2===E&&k<=0||3===E)&&(m||h)){i=new Image;const r=()=>{if(t.childElementCount||s&&!s())return;const n=()=>{t.childElementCount||s&&!s()||Object(ps.a)(i,P.url,o)};return P.url?(n(),Promise.resolve()):L.a.getThumbURL(e,a).promise.then(n)};if(n&&h)return n.push({div:t,load:r}),Promise.resolve();r(),a.url&&(j=!0)}}if(f&&j&&f.push(O),h)return Promise.resolve();const _=()=>Ls(this,void 0,void 0,(function*(){if(!s||s()){if(2===E&&!C)return yield L.a.downloadDoc(e,null==n?void 0:n.queueId).then(n=>Ls(this,void 0,void 0,(function*(){if(s&&!s())throw new Error("wrapSticker 2 middleware");let r=yield oe.a.loadAnimationWorker({container:t,loop:b&&!p,autoplay:d,animationData:n,width:u,height:g,name:"doc"+e.id,needUpscale:w,skipRatio:S,toneIndex:k},o,s);if(r.addEventListener("firstFrame",()=>{const s=t.firstElementChild;!1!==y&&(y=(y||!s||"svg"===s.tagName)&&a.a.settings.animationsEnabled);const i=()=>{s&&s!==r.canvas&&s.remove()};y?us.a.mutate(()=>{r.canvas.classList.add("fade-in"),s&&s.classList.add("fade-out"),r.canvas.addEventListener("animationend",()=>{us.a.mutate(()=>{r.canvas.classList.remove("fade-in"),i()})},{once:!0})}):s&&us.a.mutate(i),!1!==m&&L.a.saveLottiePreview(e,r.canvas,k)},{once:!0}),p){const e={a:[],v:1};let n;gs.a.preloadAnimatedEmojiStickerAnimation(p),Object(l.b)(t,a=>Ls(this,void 0,void 0,(function*(){Object(c.a)(a);const o=oe.a.getAnimation(t);if(o.paused){const e=gs.a.getAnimatedEmojiSoundDocument(p);if(e){const s=document.createElement("audio");s.style.display="none",t.parentElement.append(s);try{yield L.a.downloadDoc(e);const t=ce.a.getCacheContext(e);s.src=t.url,s.play(),yield Object(pe.e)(s,void 0,!0),s.addEventListener("ended",()=>{s.src="",s.remove()},{once:!0})}catch(e){}}o.autoplay=!0,o.restart()}if(!nc.chat.peerId.isUser())return;const r=gs.a.getAnimatedEmojiSticker(p,!0);if(!r)return;const l=Object(Ce.a)(t,"bubble"),d=l.classList.contains("is-out"),{animationDiv:h}=Ts({doc:r,middleware:s,side:d?"right":"left",size:280,target:t,play:!0});l&&(d?h.classList.add("is-out"):h.classList.add("is-in")),n||(n=Object(ws.a)(()=>{if(!e.a.length)return;const s=e.a[0].t;e.a.forEach(e=>{e.t=(e.t-s)/1e3});const n=Object(Ce.a)(t,"bubble");i.a.setTyping(nc.chat.peerId,{_:"sendMessageEmojiInteraction",msg_id:v.a.getServerMessageId(+n.dataset.mid),emoticon:p,interaction:{_:"dataJSON",data:JSON.stringify(e)}},!0),e.a.length=0},1e3,!1)),a.isTrusted&&(e.a.push({i:1,t:Date.now()}),n())})))}return r})));if(C||3===E){let i;C?i=new Image:(i=Cs(),i.muted=!0,d&&(i.autoplay=!0,i.loop=!0));const l=t.firstElementChild!==i&&t.firstElementChild;return!1!==y&&(y=(y||!T||(C?l:!l||"svg"===l.tagName))&&a.a.settings.animationsEnabled),i.classList.add("media-sticker"),y&&i.classList.add("fade-in"),new Promise((a,c)=>{const d=()=>{if(s&&!s())return a();const n=()=>{us.a.mutateElement(t,()=>{if(t.append(i),l&&l.classList.add("fade-out"),3===E&&!L.a.isSavingLottiePreview(e,k)){Object(ys.a)(i);const t=document.createElement("canvas");t.width=u*window.devicePixelRatio,t.height=g*window.devicePixelRatio;t.getContext("2d").drawImage(i,0,0,t.width,t.height),L.a.saveLottiePreview(e,t,k)}3===E&&o&&I.a.addAnimation(i,o),a(),y&&i.addEventListener("animationend",()=>{i.classList.remove("fade-in"),l&&l.remove()},{once:!0})})};C?Object(ps.a)(i,P.url,n):(i.src=P.url,Object(pe.e)(i).then(n))};if(P.url)d();else{let t;if(2===E&&C){const s=r.a.choosePhotoSize(e,u,g,!1);t=L.a.getThumbURL(e,s).promise}else t=L.a.downloadDoc(e,null==n?void 0:n.queueId);t.then(d,a)}})}}})),F=!n||T&&!x?_():(n.push({div:t,load:_}),Promise.resolve());return T&&C&&(O=F,f&&f.push(O)),F}function As({set:e,lazyLoadQueue:t,container:s,group:i,autoplay:n,width:a,height:o}){var r;return Ls(this,void 0,void 0,(function*(){if(null===(r=e.thumbs)||void 0===r?void 0:r.length)return s.classList.add("media-sticker-wrapper"),void t.push({div:s,load:()=>{const t=gs.a.getStickerSetThumbDownloadOptions(e),r=ce.a.download(t);if(e.pFlags.animated&&!e.pFlags.videos)return r.then(t=>{oe.a.loadAnimationWorker({container:s,loop:!0,autoplay:n,animationData:t,width:a,height:o,needUpscale:!0,name:"setThumb"+e.id},i)});{let t;return e.pFlags.videos?(t=Cs(),t.autoplay=!0,t.muted=!0,t.loop=!0):t=new Image,t.classList.add("media-sticker"),r.then(e=>{Object(ps.a)(t,URL.createObjectURL(e),()=>{s.append(t)})})}}});const l=gs.a.getStickerSet(e),c=yield l;"documentEmpty"!==c.documents[0]._&&xs({doc:c.documents[0],div:s,group:i,lazyLoadQueue:t})}))}function Os({doc:e,row:t,size:s}){const i=t.media,n=t.createMedia("small");i&&n.classList.add("hide");const a=i?[]:void 0,o="small"===s?32:48,r=xs({div:n,doc:e,width:o,height:o,loadPromises:a});return a&&Promise.all(a).then(()=>{n.classList.remove("hide"),i.remove()}),r}function js(e,t,s){const i=new Ue("reply");return i.fill(e,t,s),i.container}function _s(e){const t=new qe(e.items,e.maxWidth,e.minWidth,e.spacing,e.maxHeight).layout(),s=t.find(e=>e.sides&Ke),i=s.geometry.width+s.geometry.x,n=t.find(e=>e.sides&Ge),a=n.geometry.height+n.geometry.y,o=e.container;o.style.width=i+"px",o.style.height=a+"px";const r=o.children;t.forEach(({geometry:t,sides:s},n)=>{let l;if(l=r[n],l||(l=document.createElement("div"),o.append(l)),l.classList.add("album-item","grouped-item"),l.style.width=t.width/i*100+"%",l.style.height=t.height/a*100+"%",l.style.top=t.y/a*100+"%",l.style.left=t.x/i*100+"%",s&We&&s&Ve&&(l.style.borderTopLeftRadius="inherit"),s&We&&s&Ge&&(l.style.borderBottomLeftRadius="inherit"),s&Ke&&s&Ve&&(l.style.borderTopRightRadius="inherit"),s&Ke&&s&Ge&&(l.style.borderBottomRightRadius="inherit"),e.forMedia){const e=document.createElement("div");e.classList.add("album-item-media"),l.append(e)}})}function Fs({groupId:e,attachmentDiv:t,middleware:s,uploading:n,lazyLoadQueue:a,isOut:o,chat:l,loadPromises:c,autoDownload:d}){const h=[],p=i.a.getMidsByAlbum(e);for(const e of p){const t=l.getMessage(e),s=t.media.photo||t.media.document,i="photo"===s._?r.a.choosePhotoSize(s,480,480):{w:s.w,h:s.h};h.push({size:i,media:s,message:t})}_s({container:t,items:h.map(e=>({w:e.size.w,h:e.size.h})),maxWidth:b.b.active.album.width,minWidth:100,spacing:2,forMedia:!0}),h.forEach((e,i)=>{const{size:n,media:r,message:l}=e,h=t.children[i];h.dataset.mid=""+l.mid,h.dataset.peerId=""+l.peerId;const p=h.firstElementChild;"photo"===r._?Ps({photo:r,message:l,container:p,boxWidth:0,boxHeight:0,isOut:o,lazyLoadQueue:a,middleware:s,size:n,loadPromises:c,autoDownloadSize:d.photo}):Ms({doc:l.media.document,container:p,message:l,boxWidth:0,boxHeight:0,withTail:!1,isOut:o,lazyLoadQueue:a,middleware:s,loadPromises:c,autoDownload:d})})}b.b.addEventListener("changeScreen",(e,t)=>{if(t===b.a.mobile||e===b.a.mobile){const e=Array.from(document.querySelectorAll(".media-round .progress-ring")),t=b.b.active.round.width,s=t/2,i=s-7;Is=2*Math.PI*i,e.forEach(e=>{e.setAttributeNS(null,"width",""+t),e.setAttributeNS(null,"height",""+t);const n=e.firstElementChild;n.setAttributeNS(null,"cx",""+s),n.setAttributeNS(null,"cy",""+s),n.setAttributeNS(null,"r",""+i),n.style.strokeDasharray=Is+" "+Is,n.style.strokeDashoffset=""+Is})}}),a.a.addEventListener("download_start",e=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${e}"]`)).forEach(e=>{e.querySelector(".preloader-container.manual")&&Object(l.d)(e)})});var Ds=s(93),Rs=s(113),Bs=s(95);function Ns(e,t,s,i){return void 0===i&&(i=e.parentElement===t?Object(Bs.a)(e):-1),i!==s&&(-1!==i&&i<s&&(s+=1),s?t.childElementCount>s?t.insertBefore(e,t.children[s]):t.append(e):t.prepend(e),!0)}var Us=s(144);class Hs{constructor(e){this.updateElementWith=e=>e(),this.updateListWith=e=>e(!0),this.middleware=Object(Rs.a)(),Object(w.a)(this,e),this.elements=new Map,this.sorted=[]}clear(){this.middleware.clean(),this.elements.clear(),this.sorted.length=0}_updateList(){this.elements.forEach(e=>{this.update(e.id,!0)}),this.onSort&&this.sorted.forEach((e,t)=>{this.onSort(e,t)})}updateList(e){const t=this.middleware.get();this.updateListWith(s=>{if(!t()||void 0!==s&&!s)return e(!1);this._updateList(),e(!0)})}has(e){return this.elements.has(e)}get(e){return this.elements.get(e)}getAll(){return this.elements}add(e,t=!1,s,i=t){let n=this.get(e);if(n)return n;const a={id:e,index:0};return n=this.onElementCreate(a,t),this.elements.set(e,n),this.update(e,i,n,s),n}delete(e,t){const s=this.elements.get(e);if(!s)return!1;this.elements.delete(e);const i=this.sorted.indexOf(s);if(-1!==i&&this.sorted.splice(i,1),this.onDelete)if(t)this.onDelete(s);else{const e=this.middleware.get();this.updateElementWith(()=>{e()&&this.onDelete(s)})}return!0}update(e,t=!1,s=this.get(e),i){if(!s)return;s.index=this.getIndex(s),this.onUpdate&&this.onUpdate(s);const n=Object(Us.a)(this.sorted,s,"index");if(!t&&this.onSort){const e=this.middleware.get();(i||this.updateElementWith)(()=>{e()&&this.onSort(s,n)})}}}var zs=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Vs extends Hs{constructor(e={}){let t;super({getIndex:e.getIndex||(e=>E.a.getUserStatusForSort(e.id)),onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onUpdate:e.onUpdate||(e=>{const t=E.a.getUserStatusString(e.id);Object(k.a)(e.dom.lastMessageSpan,t)}),onSort:(e,t)=>{const s=e.dom.listEl.parentElement!==this.list;Ns(e.dom.listEl,this.list,t),s&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:e=>{const{dom:t}=_c.addDialogNew({dialog:e.id,container:!1,drawStatus:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});return e.dom=t,e},updateElementWith:Le.b,updateListWith:e=>zs(this,void 0,void 0,(function*(){return Object(ms.a)(this.list)?(yield Object(Ds.c)(),Object(ms.a)(this.list)?void e(!0):e(!1)):e(!1)}))}),this.avatarSize=48,this.rippleEnabled=!0,this.autonomous=!0,Object(w.a)(this,e),this.list=_c.createChatList(this.createChatListOptions);const s=()=>{t=window.setTimeout(()=>{this.updateList(e=>{e&&s()})},Vs.SORT_INTERVAL)};s()}}Vs.SORT_INTERVAL=3e4;var Ks=s(169);function Gs(e){let t=!1;return new Qt(Object.assign(Object.assign({},e),{verifyTouchTarget:t=>!Object(Ce.a)(t.target,"progress-line")&&!Object(Ks.a)(t)&&(!e.verifyTouchTarget||e.verifyTouchTarget(t)),onSwipe:(s,i,n)=>{if(!t&&Math.abs(i)>20)return!0;if(Math.abs(s)>Math.abs(i))Object(c.a)(n),t=!0;else if(!t&&Math.abs(i)>Math.abs(s))return!0;return e.onSwipe(s,i,n)},onReset:()=>{t=!1,e.onReset&&e.onReset()},cancelEvent:!1}))}function Ws(e){return Gs(Object.assign(Object.assign({},e),{onSwipe:(t,s,i)=>{if(Math.abs(t)>50)return e.onSwipe(t,s,i),Object(ee.b)(),!0}}))}var qs=s(121);const Qs=e=>{if(e.element)return e.element;const{icon:t,text:s,onClick:i,checkboxField:n,noCheckboxClickListener:a}=e,o=document.createElement("div");o.className="btn-menu-item rp-overflow"+(t?" tgico-"+t:""),Object(te.a)(o);let r=e.textElement;r||(r=e.textElement=s?Object(T.d)(s,e.textArgs):document.createElement("span"),e.regularText&&(r.innerHTML=e.regularText)),r.classList.add("btn-menu-item-text"),o.append(r);const d=!!n||!!e.keepOpen;return i&&Object(l.b)(o,e=>{Object(c.a)(e);!1!==i(e)&&(d||Object(ee.c)(),n&&!a&&(n.checked="radio"===n.input.type||!n.checked))},e.options),n&&o.append(n.label),e.element=o};var $s=(e,t)=>{const s=document.createElement("div");s.classList.add("btn-menu"),t&&e.forEach(e=>{e.options?e.options.listenerSetter=t:e.options={listenerSetter:t}});const i=e.map(Qs);return s.append(...i),s},Ys=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Xs extends Pt{constructor(e,t,s=!1){super({peerTypes:["dialogs","contacts"],onSelect:s?t:s=>Ys(this,void 0,void 0,(function*(){if(t){const e=t(s);e instanceof Promise&&(yield e)}nc.setInnerPeer({peerId:s}),nc.chat.input.initMessagesForward(e)})),placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})}}class Js{constructor(e,t,s,n){const r=new wt.a({peerId:e}).element;t=t.slice();const l=(a,o)=>{n&&n(),"scheduled"===s?i.a.deleteScheduledMessages(e,t):i.a.deleteMessages(e,t,!!a.size||o)};let c,d,h,p,u,g=[];if(1===t.length?c="DeleteSingleMessagesTitle":(c="DeleteMessagesTitle",d=[Object(T.d)("messages",[t.length])]),h=o.a.isMegagroup(e)?1===t.length?"AreYouSureDeleteSingleMessageMega":"AreYouSureDeleteFewMessagesMega":1===t.length?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",u=[{langKey:"Delete",isDanger:!0,callback:l}],e===a.a.myId||"scheduled"===s);else if(e.isUser())g.push({text:"DeleteMessagesOptionAlso",textArgs:[r]});else{const s=G.a.getChat(e.toChatId()),n=G.a.hasRights(e.toChatId(),"delete_messages");if("chat"===s._){const s=n?t.slice():t.filter(t=>i.a.getMessageByPeer(e,t).fromId===a.a.myId);s.length&&(s.length===t.length?g.push({text:"DeleteForAll"}):(g.push({text:"DeleteMessagesOption"}),h="DeleteMessagesTextGroup",p=[Object(T.d)("messages",[s.length])]))}else u[0].callback=e=>l(e,!0)}Object(ht.a)(u);new ut("popup-delete-chat",{peerId:e,titleLangKey:c,titleLangArgs:d,descriptionLangKey:h,descriptionLangArgs:p,buttons:u,checkboxes:g}).show()}}var Zs=s(159);class ei{constructor(e,t,s){let n,a,o=[];n=`Send Message${t.length>1?"s":""} Now`,a=t.length>1?"Send "+t.length+" messages now?":"Send message now?";o.push({langKey:"Send",callback:()=>{s&&s(),i.a.sendScheduledMessages(e,t)}});new ut("popup-delete-chat",{peerId:e,title:n,description:a,buttons:o}).show()}}var ti=s(38);function si(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}var ii=s(116);const ni=e=>[...e.values()].reduce((e,t)=>e+t.size,0);class ai extends D.a{constructor(e){if(super(!1),this.selectedMids=new Map,this.isSelecting=!1,this.cancelSelection=e=>{e&&(this.doNotAnimate=!0),this.onCancelSelection&&this.onCancelSelection(),this.selectedMids.clear(),this.toggleSelection(),si(),e&&(this.doNotAnimate=void 0)},Object(w.a)(this,e),this.navigationType="multiselect-"+Object(st.b)(),he.a)return this.listenerSetter.add(this.listenElement)("touchend",()=>{this.isSelecting&&(this.selectedText=window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:"")}),void Object(ee.a)(this.listenElement,e=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;document.body.classList.add("no-select"),this.listenElement.addEventListener("touchend",e=>{Object(c.a)(e),document.body.classList.remove("no-select")},{once:!0,capture:!0}),si();const t=this.getElementFromTarget(e.target);t&&this.toggleByElement(t)},this.listenerSetter);const t=(e,t)=>{if(e===t)return[];const s=e.getBoundingClientRect(),i=t.getBoundingClientRect(),n=(s.top-i.top||s.left-i.left)<0,a=Object(Ce.a)(e,this.lookupBetweenParentClassName);if(!a)return[];const o=Array.from(a.querySelectorAll(this.lookupBetweenElementsQuery));let r=o.indexOf(e),l=o.indexOf(t);n||([l,r]=[r,l]);return o.slice(r+1,l)};this.listenerSetter.add(this.listenElement)("mousedown",e=>{const s=Object(Ce.a)(e.target,this.targetLookupClassName);if(0!==e.button)return;if(this.verifyTarget&&!this.verifyTarget(e,s))return;const i=new Map;let n,a=s;const o=(e,s=!0)=>{const r=+e.dataset.mid;if(!r||!e.dataset.peerId)return;const l=e.dataset.peerId.toPeerId();Object(ms.a)(a)||(a=e);let c=i.get(l);if(c||i.set(l,c=new Set),!c.has(r)){const d=this.isMidSelected(l,r);if(void 0===n&&(n=!d),c.add(r),n&&!d||!n&&d){const n=ni(i);if(this.toggleByElement&&s){n<2&&Object(ii.a)(e,a)&&(a=e);const s=t(a,e);s.length&&s.forEach(e=>{o(e,!1)})}if(this.selectedMids.size)this.toggleByElement&&this.toggleByElement(e);else if(2===n&&this.toggleByMid)for(const[e,t]of i)for(const s of t)this.toggleByMid(e,s)}}};let r=!1;const d=e=>{r||(si(),r=!0);const t=this.getElementFromTarget(e.target);if(t)return this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(e,t,n)?(this.listenerSetter.removeManual(this.listenElement,"mousemove",d),void this.listenerSetter.removeManual(document,"mouseup",h,p)):void o(t)},h=e=>{i.size&&Object(l.b)(window,c.a,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",d),si()},p={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",d),this.listenerSetter.add(document)("mouseup",h,p)})}isElementShouldBeSelected(e){return this.isMidSelected(e.dataset.peerId.toPeerId(),+e.dataset.mid)}appendCheckbox(e,t){e.prepend(t.label)}toggleElementCheckbox(e,t){const s=!!this.getCheckboxInputFromElement(e);if(t){if(s)return!1;const t=new pt.a({name:e.dataset.mid,round:!0});this.isSelecting&&this.isElementShouldBeSelected(e)&&(t.input.checked=!0,e.classList.add("is-selected")),this.appendCheckbox(e,t)}else s&&this.getCheckboxInputFromElement(e).parentElement.remove();return!0}getCheckboxInputFromElement(e){var t;return"LABEL"===(null===(t=e.firstElementChild)||void 0===t?void 0:t.tagName)&&e.firstElementChild.firstElementChild}updateContainer(e=!1){const t=this.selectedMids.size;if(!t&&!e)return;let s=!t,i=!t,n=!t;for(const[e,t]of this.selectedMids){const n=this.isScheduled?this.appMessagesManager.getScheduledMessagesStorage(e):this.appMessagesManager.getMessagesStorage(e);for(const e of t){const t=this.appMessagesManager.getMessageFromStorage(n,e);if(s||(s=!this.appMessagesManager.canForward(t)),i||(i=!this.appMessagesManager.canDeleteMessage(t)),s&&i)break}if(s&&i)break}this.onUpdateContainer&&this.onUpdateContainer(s,i,n)}toggleSelection(e=!0,t=!1){const s=this.isSelecting,i=this.selectedMids.size;if(this.isSelecting=!!i||t,s===this.isSelecting)return!1;this.dispatchEvent("toggle",this.isSelecting),he.a||(this.listenElement.classList.toggle("no-select",this.isSelecting),s&&si()),Object(ti.a)();const n=!!i||t;return this.onToggleSelection&&this.onToggleSelection(n,!this.doNotAnimate),ae.f||(n?F.a.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):F.a.removeByType(this.navigationType)),t&&this.updateContainer(t),!0}cleanup(){this.doNotAnimate=!0,this.selectedMids.clear(),this.toggleSelection(!1),this.doNotAnimate=void 0}updateElementSelection(e,t){this.toggleElementCheckbox(e,!0);this.getCheckboxInputFromElement(e).checked=t,this.toggleSelection(),this.updateContainer(),Object(is.a)(e,"is-selected",t,200)}isMidSelected(e,t){const s=this.selectedMids.get(e);return null==s?void 0:s.has(t)}length(){return ni(this.selectedMids)}toggleMid(e,t,s){let i=this.selectedMids.get(e);if(s||void 0===s&&(null==i?void 0:i.has(t)))i&&(i.delete(t),i.size||this.selectedMids.delete(e));else{if(a.a.config.forwarded_count_max-this.length()-1<0)return ot(T.c.format("Chat.Selection.LimitToast",!0)),!1;i||(i=new Set,this.selectedMids.set(e,i)),i.add(t)}return!0}deleteSelectedMids(e,t){const s=this.selectedMids.get(e);s&&(t.forEach(e=>{s.delete(e)}),s.size||this.selectedMids.delete(e),this.updateContainer(),this.toggleSelection())}}class oi extends ai{constructor(e,t){super({appMessagesManager:t,listenElement:e.container,listenerSetter:new R.a,verifyTarget:(e,t)=>!!t&&this.isSelecting,getElementFromTarget:e=>Object(Ce.a)(e,"search-super-item"),targetLookupClassName:"search-super-item",lookupBetweenParentClassName:"tabs-tab",lookupBetweenElementsQuery:".search-super-item"}),this.searchSuper=e,this.toggleByElement=e=>{const t=+e.dataset.mid,s=e.dataset.peerId.toPeerId();this.toggleMid(s,t)&&this.updateElementSelection(e,this.isMidSelected(s,t))},this.toggleByMid=(e,t)=>{const s=this.searchSuper.mediaTab.contentTab.querySelector(`.search-super-item[data-peer-id="${e}"][data-mid="${t}"]`);this.toggleByElement(s)},this.onUpdateContainer=(e,t,s)=>{const i=this.length();Object(k.a)(this.selectionCountEl,Object(T.d)("messages",[i])),this.selectionGotoBtn.classList.toggle("hide",1!==i),this.selectionForwardBtn.classList.toggle("hide",e),this.selectionDeleteBtn&&this.selectionDeleteBtn.classList.toggle("hide",t)},this.onToggleSelection=(e,t)=>{if(Object(is.a)(this.searchSuper.navScrollableContainer,"is-selecting",e,t?200:0,()=>{this.isSelecting||(this.selectionContainer.remove(),this.selectionContainer=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0)}),Object(is.a)(this.searchSuper.container,"is-selecting",e,200),this.isSelecting&&!this.selectionContainer){const e="search-super-selection";this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add(e+"-container");const t=N(`close ${e}-cancel`,{noRipple:!0});this.listenerSetter.add(t)("click",()=>this.cancelSelection(),{once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add(e+"-count"),this.selectionGotoBtn=N(`message ${e}-goto`);const s={listenerSetter:this.listenerSetter};Object(l.b)(this.selectionGotoBtn,()=>{const e=[...this.selectedMids.keys()][0],t=[...this.selectedMids.get(e)][0];this.cancelSelection(),a.a.dispatchEvent("history_focus",{peerId:e,mid:t})},s),this.selectionForwardBtn=N(`forward ${e}-forward`),Object(l.b)(this.selectionForwardBtn,()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s).sort((e,t)=>e-t);new Xs(e,()=>{this.cancelSelection()})},s),this.isPrivate&&(this.selectionDeleteBtn=N(`delete danger ${e}-delete`),Object(l.b)(this.selectionDeleteBtn,()=>{const e=[...this.selectedMids.keys()][0];new Js(e,[...this.selectedMids.get(e)],"chat",()=>{this.cancelSelection()})},s)),this.selectionContainer.append(...[t,this.selectionCountEl,this.selectionGotoBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean));const i=this.selectionContainer;i.style.opacity="0",this.searchSuper.navScrollableContainer.append(i),i.offsetLeft,i.style.opacity=""}},this.isPrivate=!e.showSender}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e){Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach(e=>{this.toggleElementCheckbox(e,this.isSelecting)})}return s}}class ri extends ai{constructor(e,t,s,i){super({appMessagesManager:i,listenElement:t.bubblesContainer,listenerSetter:t.listenerSetter,getElementFromTarget:e=>Object(Ce.a)(e,"grouped-item")||Object(Ce.a)(e,"bubble"),verifyTarget:(e,t)=>!(!this.selectedMids.size&&!e.target.classList.contains("bubble")&&!e.target.classList.contains("document-selection")&&t),verifyMouseMoveTarget:(e,t,s)=>!(e.target!==t&&!e.target.classList.contains("document-selection")&&void 0===s&&!this.selectedMids.size),verifyTouchLongPress:()=>!this.chat.input.recording,targetLookupClassName:"bubble",lookupBetweenParentClassName:"bubbles-inner",lookupBetweenElementsQuery:".bubble:not(.is-multiple-documents), .grouped-item",isScheduled:"scheduled"===e.type}),this.chat=e,this.bubbles=t,this.input=s,this.toggleByElement=e=>{if(!this.canSelectBubble(e))return;const t=+e.dataset.mid;if(e.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(e)){const e=this.selectedMids.get(this.bubbles.peerId);if(e){this.chat.getMidsByMid(t).forEach(t=>e.delete(t))}}return void this.bubbles.getBubbleGroupedItems(e).forEach(this.toggleByElement)}if(!this.toggleMid(this.bubbles.peerId,t))return;if(e.classList.contains("grouped-item")){const s=Object(Ce.a)(e,"bubble"),i=this.isGroupedBubbleSelected(s),n=this.isGroupedMidsSelected(t);(n||i)&&this.updateElementSelection(s,n)}this.updateElementSelection(e,this.isMidSelected(this.bubbles.peerId,t))},this.toggleByMid=(e,t)=>{const s=this.bubbles.getMountedBubble(t);s&&this.toggleByElement(s.bubble)},this.onToggleSelection=(e,t)=>{const{needTranslateX:s,widthFrom:i,widthTo:n}=this.chat.input.center(t);Object(is.a)(this.listenElement,"is-selecting",e,t?200:0,()=>{this.isSelecting||(this.selectionInputWrapper.remove(),this.selectionInputWrapper=this.selectionContainer=this.selectionSendNowBtn=this.selectionForwardBtn=this.selectionDeleteBtn=this.selectionLeft=this.selectionRight=null,this.selectedText=void 0)});const a=i<n?void 0:2*s;if(this.isSelecting){if(!this.selectionContainer){this.selectionInputWrapper=document.createElement("div"),this.selectionInputWrapper.classList.add("chat-input-wrapper","selection-wrapper"),this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add("selection-container");const e={listenerSetter:this.listenerSetter},t=N("close",{noRipple:!0});Object(l.b)(t,()=>this.cancelSelection(),{once:!0,listenerSetter:this.listenerSetter}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add("selection-container-count"),"scheduled"===this.chat.type?(this.selectionSendNowBtn=Object(B.a)("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append(Object(T.d)("MessageScheduleSend")),Object(l.b)(this.selectionSendNowBtn,()=>{new ei(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],()=>{this.cancelSelection()})},e)):(this.selectionForwardBtn=Object(B.a)("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append(Object(T.d)("Forward")),Object(l.b)(this.selectionForwardBtn,()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s).sort((e,t)=>e-t);new Xs(e,()=>{this.cancelSelection()})},e)),this.selectionDeleteBtn=Object(B.a)("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append(Object(T.d)("Delete")),Object(l.b)(this.selectionDeleteBtn,()=>{new Js(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],this.chat.type,()=>{this.cancelSelection()})},e);const s=this.selectionLeft=document.createElement("div");s.classList.add("selection-container-left"),s.append(t,this.selectionCountEl);const i=this.selectionRight=document.createElement("div");i.classList.add("selection-container-right"),i.append(...[this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),void 0!==a&&(s.style.transform=`translateX(${-a}px)`,i.style.transform=`translateX(${a}px)`),this.selectionContainer.append(s,i),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.inputContainer.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity="",s.style.transform="",i.style.transform=""}}else this.selectionLeft&&void 0!==a&&(this.selectionLeft.style.transform=`translateX(-${a}px)`,this.selectionRight.style.transform=`translateX(${a}px)`)},this.onUpdateContainer=(e,t,s)=>{Object(k.a)(this.selectionCountEl,Object(T.d)("messages",[this.length()])),this.selectionSendNowBtn&&this.selectionSendNowBtn.toggleAttribute("disabled",s),this.selectionForwardBtn&&this.selectionForwardBtn.toggleAttribute("disabled",e),this.selectionDeleteBtn.toggleAttribute("disabled",t)},this.onCancelSelection=()=>{for(const[e,t]of this.selectedMids)for(const e of t){const t=this.bubbles.getMountedBubble(e);t&&this.toggleByElement(t.bubble)}}}appendCheckbox(e,t){t.label.classList.add("bubble-select-checkbox"),e.classList.contains("document-container")?e.querySelector(".document, audio-element").append(t.label):super.appendCheckbox(e,t)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e)for(const e in this.bubbles.bubbles){const t=this.bubbles.bubbles[e];this.toggleElementCheckbox(t,this.isSelecting)}return s}toggleElementCheckbox(e,t){if(!this.canSelectBubble(e))return;const s=super.toggleElementCheckbox(e,t);if(s){e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach(e=>this.toggleElementCheckbox(e,t))}return s}isElementShouldBeSelected(e){const t=e.classList.contains("is-grouped");return super.isElementShouldBeSelected(e)&&(!t||this.isGroupedMidsSelected(+e.dataset.mid))}isGroupedBubbleSelected(e){const t=this.getCheckboxInputFromElement(e);return null==t?void 0:t.checked}isGroupedMidsSelected(e){const t=this.chat.getMidsByMid(e),s=t.filter(e=>this.isMidSelected(this.bubbles.peerId,e));return t.length===s.length}getCheckboxInputFromElement(e){return e.classList.contains("document-container")?e.querySelector("label input"):super.getCheckboxInputFromElement(e)}canSelectBubble(e){return!(e.classList.contains("service")||e.classList.contains("is-outgoing")||e.classList.contains("bubble-first")||e.classList.contains("avoid-selection"))}}var li=s(149),ci=s(183),di=s(158),hi=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class pi{constructor(e,t){this.attachTo=e,this.searchSuper=t,this.onGotoClick=()=>{a.a.dispatchEvent("history_focus",{peerId:this.peerId,mid:this.mid,threadId:this.searchSuper.searchContext.threadId})},this.onForwardClick=()=>{this.searchSuper.selection.isSelecting?Object(l.d)(this.searchSuper.selection.selectionForwardBtn):new Xs({[this.peerId]:[this.mid]})},this.onSelectClick=()=>{this.searchSuper.selection.toggleByElement(this.target)},this.onClearSelectionClick=()=>{this.searchSuper.selection.cancelSelection()},this.onDeleteClick=()=>{this.searchSuper.selection.isSelecting?Object(l.d)(this.searchSuper.selection.selectionDeleteBtn):new Js(this.peerId,[this.mid],"chat")};const s=e=>{let s;this.init&&(this.init(),this.init=null);try{s=Object(Ce.a)(e.target,"search-super-item")}catch(e){}if(s){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),this.target=s,this.peerId=s.dataset.peerId.toPeerId(),this.mid=+s.dataset.mid,this.isSelected=t.selection.isMidSelected(this.peerId,this.mid),this.buttons.forEach(e=>{let t;t=!(this.isSelected&&!e.withSelection)&&(!e.verify||e.verify()),e.element.classList.toggle("hide",!t)}),s.classList.add("menu-open"),Object(ee.e)(e,this.element),Object(ee.d)(this.element,()=>{s.classList.remove("menu-open")})}};he.a||Object(ee.a)(e,s)}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>i.a.canForward(i.a.getMessageByPeer(this.peerId,this.mid))},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.isSelected&&!this.searchSuper.selection.selectionForwardBtn.classList.contains("hide"),withSelection:!0},{icon:"message",text:"Message.Context.Goto",onClick:this.onGotoClick,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,withSelection:!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>i.a.canDeleteMessage(i.a.getMessageByPeer(this.peerId,this.mid))},{icon:"delete danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.searchSuper.selection.selectionDeleteBtn.classList.contains("hide"),withSelection:!0}],this.element=$s(this.buttons),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class ui{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new Z.d,this.middleware=Object(Rs.a)(),this.historyStorage={},this.usedFromHistory={},this.urlsToRevoke=[],this.loadMutex=Promise.resolve(),this.nextRates={},this.loadPromises={},this.loaded={},this.loadedChats=!1,this.firstLoad=!0,this.log=Object(Y.b)("SEARCH-SUPER"),this.monthContainers={},this.mediaTabsMap=new Map,this.asChatList=!1,this.groupByMonth=!0,this.hideEmptyTabs=!0,this.showSender=!1,this.onTransitionStart=()=>{this.container.classList.add("sliding")},this.onTransitionEnd=()=>{this.container.classList.remove("sliding")},Object(w.a)(this,e),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.searchContextMenu=new pi(this.container,this),this.selection=new oi(this,i.a);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=this.navScrollable=new P.a(t);s.container.classList.add("search-super-nav-scrollable");const n=this.nav=document.createElement("nav");n.classList.add("search-super-tabs","menu-horizontal-div"),this.tabsMenu=n,s.container.append(n);for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const s=document.createElement("span"),i=document.createElement("i");s.append(Object(T.d)(e.name)),s.append(i),t.append(s),Object(te.a)(t),this.tabsMenu.append(t),this.mediaTabsMap.set(e.type,e),e.menuTab=t}let a;this.tabsContainer=document.createElement("div"),this.tabsContainer.classList.add("search-super-tabs-container","tabs-container"),he.a&&Ws({element:this.tabsContainer,onSwipe:(e,t,s)=>{const i=this.selectTab.prevId(),n=Array.from(this.tabsMenu.children);let o;if(e>0){for(let e=i+1;e<n.length;++e)if(!n[e].classList.contains("hide")){o=e;break}}else for(let e=i-1;e>=0;--e)if(!n[e].classList.contains("hide")){o=e;break}void 0!==o&&(a=function(e){const t=e=>{Object(c.a)(e)};let s=2;const i=()=>{--s||e.removeEventListener("touchmove",t,{capture:!0})};return e.addEventListener("touchmove",t,{capture:!0,passive:!1}),e.addEventListener("touchend",i,{once:!0}),i}(this.tabsContainer),this.selectTab(o))}});for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("search-super-container-"+e.type,"tabs-tab");const s=document.createElement("div");s.classList.add("search-super-content-"+e.type),t.append(s),this.tabsContainer.append(t),this.tabs[e.inputFilter]=s,e.contentTab=s}this.container.append(t,this.tabsContainer),this.searchGroupMedia=new x(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&!this.loaded[this.mediaTab.inputFilter]&&this.load(!0)},this.selectTab=Object(J.a)(this.tabsMenu,this.tabsContainer,(e,t,s)=>{if(this.prevTabId===e&&!this.skipScroll)return void this.scrollable.scrollIntoViewNew({element:this.container,position:"start",startCallback:this.scrollStartCallback});const i=this.mediaTabs[e];this.onChangeTab&&this.onChangeTab(i);const n=this.mediaTab;if(this.mediaTab=i,-1!==this.prevTabId&&s&&this.onTransitionStart(),this.skipScroll)this.skipScroll=!1;else{const e=this.container.offsetTop;let t=this.scrollable.scrollTop;if(t<e&&(this.scrollable.scrollIntoViewNew({element:this.container,position:"start",startCallback:this.scrollStartCallback}),t=e),n.scroll={scrollTop:t,scrollHeight:this.scrollable.scrollHeight},void 0===i.scroll){const e=this.container.getBoundingClientRect(),s=this.container.parentElement.getBoundingClientRect(),n=e.y-s.y;t>n&&(i.scroll={scrollTop:n,scrollHeight:0})}if(i.scroll){const e=n.scroll.scrollTop-i.scroll.scrollTop;e&&(i.contentTab.style.transform=`translateY(${e}px)`)}}-1===this.prevTabId||i.contentTab.childElementCount||this.load(!0),this.prevTabId=e},()=>{this.scrollable.onScroll(),void 0!==this.mediaTab.scroll&&(this.mediaTab.contentTab.style.transform="",this.scrollable.scrollTop=this.mediaTab.scroll.scrollTop),a&&(a(),a=void 0),this.onTransitionEnd()},void 0,s),Object(l.b)(this.tabsContainer,e=>{this.selection.isSelecting&&(Object(c.a)(e),this.selection.toggleByElement(Object(Ce.a)(e.target,"search-super-item")))},{capture:!0,passive:!1});const o=(e,t,s,n)=>{const a=Object(Ce.a)(n.target,e);if(!a)return;const o=+a.dataset.mid;if(!o)return void this.log.warn("no messageId by click on target:",a);const r=a.dataset.peerId.toPeerId(),l=Array.from(this.tabs[s].querySelectorAll("."+t)).map(t=>{const s=Object(Ce.a)(t,e);return{element:t,mid:+s.dataset.mid,peerId:s.dataset.peerId.toPeerId()}}),c=l.findIndex(e=>e.mid===o&&e.peerId===r),d=i.a.getMessageByPeer(r,o);(new cc).setSearchContext(this.copySearchContext(s)).openMedia(d,l[c].element,0,!1,l.slice(0,c),l.slice(c+1))};Object(l.b)(this.tabs.inputMessagesFilterPhotoVideo,o.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo")),Object(l.b)(this.tabs.inputMessagesFilterDocument,o.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument")),this.mediaTab=this.mediaTabs[0],Object(Ds.a)(()=>{this.lazyLoadQueue.lock()},()=>{this.lazyLoadQueue.unlockAndRefresh()})}filterMessagesByType(e,t){return i.a.filterMessagesByInputFilter(t,e,e.length)}processEmptyFilter({message:e,searchGroup:t}){const{dialog:s,dom:i}=_c.addDialogNew({dialog:e.peerId,container:t.list,drawStatus:!1,avatarSize:54});_c.setLastMessage(s,e,i,this.searchContext.query)}processPhotoVideoFilter({message:e,promises:t,middleware:s,elemsToAppend:n}){const a=i.a.getMediaFromMessage(e),o=document.createElement("div");let l;o.classList.add("grid-item");const c=r.a.choosePhotoSize(a,200,200);l="photo"!==a._?Ms({doc:a,message:e,container:o,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,size:c}).thumb:Ps({photo:a,message:e,container:o,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,withoutPreloader:!0,noBlur:!0,size:c}),[l.images.thumb,l.images.full].filter(Boolean).forEach(e=>{e.classList.add("grid-item-media")}),t.push(l.loadPromises.thumb),n.push({element:o,message:e})}processDocumentFilter({message:e,elemsToAppend:t,inputFilter:s}){const n=i.a.getMediaFromMessage(e),a=this.showSender||["voice","round"].includes(n.type),o=Es({message:e,withTime:!a,fontWeight:400,voiceAsMusic:!0,showSender:a,searchContext:this.copySearchContext(s),lazyLoadQueue:this.lazyLoadQueue,autoDownloadSize:0});["audio","voice","round"].includes(n.type)&&o.classList.add("audio-48"),t.push({element:o,message:e})}processUrlFilter({message:e,promises:t,middleware:s,elemsToAppend:n}){var a;let o=null===(a=e.media)||void 0===a?void 0:a.webpage;if(!o){const t=e.totalEntities?e.totalEntities.find(e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._):null;let s,i,n;if(t)n=e.message.slice(t.offset,t.offset+t.length);else{const t=X.b.matchUrl(e.message);if(!t)return;s=t[0]}s="messageEntityTextUrl"===(null==t?void 0:t._)?t.url:s||n,i=s;const a=e.message===s;s.match(/^(ftp|http|https):\/\//)||(i="https://"+s,s=s.includes("@")?s:"https://"+s),i=new URL(i).hostname,o={_:"webPage",url:s,display_url:i,id:"",hash:0},a||(o.description=e.message)}let l=document.createElement("div");if(l.classList.add("preview","row-media"),o.photo){Ps({container:l,message:null,photo:o.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:s,size:r.a.choosePhotoSize(o.photo,60,60,!1),loadPromises:t,noBlur:!0})}else l.classList.add("empty"),Object(m.a)(l,X.b.getAbbreviation(o.title||o.display_url||o.description||o.url,!0));let c=di.a.wrapTitle(o);const d=di.a.wrapDescription(o),h=Object(Zs.a)(X.b.wrapRichText(o.url||"")).firstElementChild;if(h instanceof HTMLAnchorElement)try{h.innerText=decodeURIComponent(h.href)}catch(e){}d.firstChild&&d.append("\n"),d.append(h),this.showSender&&d.append("\n",i.a.wrapSenderToPeer(e)),c.textContent||c.append(X.b.wrapPlainText(o.display_url.split("/",1)[0]));const p=new Ze({title:c,titleRight:i.a.wrapSentTime(e),subtitle:d,havePadding:!0,clickable:!0,noRipple:!0});p.container.append(l),p.container.innerText.trim().length&&n.push({element:p.container,message:e})}performSearchResult(e,t,s=!0){return hi(this,void 0,void 0,(function*(){const i=[],n=t.contentTab,a=[],o=this.middleware.get();let r,l=t.inputFilter;yield Object(Ds.c)(),"inputMessagesFilterPhotoVideo"===l&&this.searchContext.query.trim()?(l="inputMessagesFilterEmpty",r=this.searchGroupMedia,n.append(r.container)):"inputMessagesFilterEmpty"===l&&(r=this.searchGroups.messages);const c={elemsToAppend:i,inputFilter:l,message:void 0,middleware:o,promises:a,searchGroup:r};let d;switch(l){case"inputMessagesFilterEmpty":d=this.processEmptyFilter;break;case"inputMessagesFilterPhotoVideo":d=this.processPhotoVideoFilter;break;case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":d=this.processDocumentFilter;break;case"inputMessagesFilterUrl":d=this.processUrlFilter}if(d){d=d.bind(this);for(const t of e)try{c.message=t,d(c)}catch(e){this.log.error("error rendering filter",l,c,t,e)}}if(r&&r.list.childElementCount&&r.setActive(),this.loadMutex&&a.push(this.loadMutex),!a.length||(yield Promise.all(a),o())){if(i.length){const e=s?"append":"prepend";i.forEach(t=>{const{element:s,message:i}=t,n=this.getMonthContainerByTimestamp(this.groupByMonth?i.date:0,l);s.classList.add("search-super-item"),s.dataset.mid=""+i.mid,s.dataset.peerId=""+i.peerId,n.items[e](s),this.selection.isSelecting&&this.selection.toggleElementCheckbox(s,!0)})}this.afterPerforming("inputMessagesFilterEmpty"===l?1:e.length,n)}}))}afterPerforming(e,t){if(t){const s=t.parentElement;if(Array.from(s.children).slice(1).forEach(e=>{e.remove()}),!e&&!t.childElementCount){const e=document.createElement("div");e.innerText="Nothing interesting here yet...",e.classList.add("position-center","text-center","content-empty","no-select"),s.append(e)}}}loadChats(){const e=new Set,t=this.middleware.get();for(let e in this.searchGroups){const t=this.searchGroups[e];this.tabs.inputMessagesFilterEmpty.append(t.container),t.clear()}const s=this.searchContext.query;if(s){const r=(t,i,r=!1)=>{t.forEach(t=>{if(e.has(t))return;e.add(t);const l=o.a.getPeer(t),{dom:c}=_c.addDialogNew({dialog:t,container:i.list,drawStatus:!1,avatarSize:48,autonomous:i.autonomous});if(r&&(l.participants_count||l.participants)){const e=new RegExp(`(${Object(ci.a)(s)}|${Object(ci.a)(Object(bs.b)(s))})`,"gi");c.titleSpan.innerHTML=c.titleSpan.innerHTML.replace(e,"<i>$1</i>"),c.lastMessageSpan.append(n.default.getChatMembersString(t.toChatId()))}else if(t===a.a.myId)c.lastMessageSpan.append(Object(T.d)("Presence.YourChat"));else{let e=o.a.getPeerUsername(t);if(e)e="@"+e;else{const s=E.a.getUser(t);s&&s.phone&&(e="+"+Object(qs.a)(s.phone).formatted)}c.lastMessageSpan.innerHTML="<i>"+e+"</i>"}}),i.toggle()},c=e=>{if(t())return e};return Promise.all([E.a.getContactsPeerIds(s,!0).then(c).then(e=>{e&&r(e,this.searchGroups.contacts,!0)}),E.a.searchContacts(s,20).then(c).then(e=>{if(e&&(r(e.my_results,this.searchGroups.contacts,!0),r(e.results,this.searchGroups.globalContacts),this.searchGroups.globalContacts.container.classList.add("is-short"),this.searchGroups.globalContacts.nameEl.lastElementChild!==this.searchGroups.globalContacts.nameEl.firstElementChild&&this.searchGroups.globalContacts.nameEl.lastElementChild.remove(),this.searchGroups.globalContacts.list.childElementCount>3)){const e=document.createElement("div");e.classList.add("search-group__show-more");const t=new T.c.IntlElement({key:"Separator.ShowMore"});e.append(t.element),this.searchGroups.globalContacts.nameEl.append(e),Object(l.b)(e,()=>{const e=this.searchGroups.globalContacts.container.classList.toggle("is-short");t.key=e?"Separator.ShowMore":"Separator.ShowLess",t.update()})}}),i.a.getConversations(s,0,20,0).promise.then(c).then(e=>{e&&r(e.dialogs.map(e=>e.peerId),this.searchGroups.contacts,!0)})])}if(this.searchContext.peerId||this.searchContext.minDate)return Promise.resolve();{const e=(e=!0)=>M.c.getState().then(s=>{t()&&(this.searchGroups.recent.list.innerHTML="",s.recentSearch.slice(0,20).forEach(e=>{let{dialog:t,dom:s}=_c.addDialogNew({dialog:e,container:this.searchGroups.recent.list,drawStatus:!1,meAsSaved:!0,avatarSize:48,autonomous:!0});s.lastMessageSpan.append(e.isUser()?E.a.getUserStatusString(e):n.default.getChatMembersString(e.toChatId()))}),s.recentSearch.length?e&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())});return Promise.all([E.a.getTopPeers("correspondents").then(e=>{if(!t())return;const s=e.findIndex(e=>e.id===a.a.myId);-1!==s&&(e=e.slice()).splice(s,1),e.length&&e.forEach(e=>{_c.addDialogNew({dialog:e.id,container:this.searchGroups.people.list,drawStatus:!1,onlyFirstName:!0,avatarSize:54,autonomous:!1})}),this.searchGroups.people.setActive()}),e()])}}loadMembers(e){const t=this.searchContext.peerId.toChatId(),s=this.middleware.get();let i;const a=t=>hi(this,void 0,void 0,(function*(){this.loadMutex&&(yield this.loadMutex,!s())||(this.membersList||(this.membersList=new Vs({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1}),Object(l.b)(this.membersList.list,e=>{const t=Object(bt.a)(e.target,"LI");if(!t)return;const s=t.dataset.peerId.toPeerId();let i=Promise.resolve();b.b.isMobile&&(i=ts.toggleSidebar(!1)),i.then(()=>{nc.setInnerPeer({peerId:s})})}),e.contentTab.append(this.membersList.list),this.afterPerforming(1,e.contentTab)),t.forEach(e=>{const t=G.a.getParticipantPeerId(e);if(t.isAnyChat())return;E.a.getUser(t).pFlags.deleted||this.membersList.add(t)}))}));if(G.a.isChannel(t)){const o=this.membersList?200:50;i=n.default.getChannelParticipants(t,void 0,o,this.nextRates[e.inputFilter]).then(t=>{if(!s())return;let i=e.contentTab.firstElementChild;return this.nextRates[e.inputFilter]=(i?i.childElementCount:0)+t.participants.length,t.participants.length<o&&(this.loaded[e.inputFilter]=!0),a(t.participants)})}else i=Promise.resolve(n.default.getChatFull(t)).then(t=>{if(!s())return;this.loaded[e.inputFilter]=!0;const i=t.participants;return"chatParticipantsForbidden"!==i._?a(i.participants):void 0});return this.loadPromises[e.inputFilter]=i.finally(()=>{s()&&(this.loadPromises[e.inputFilter]=null)})}loadType(e,t,s,n){var a,o;const r=e.inputFilter;if(this.loadPromises[r])return this.loadPromises[r];if("members"===e.type)return this.loadMembers(e);const l=null!==(a=this.historyStorage[r])&&void 0!==a?a:this.historyStorage[r]=[];if(!("inputMessagesFilterEmpty"!==r||l.length||(this.loadedChats||(this.loadChats(),this.loadedChats=!0),this.searchContext.query.trim()||this.searchContext.peerId||this.searchContext.minDate)))return this.loaded[r]=!0,Promise.resolve();const c="load ["+r+"]: ";if(l.length&&this.usedFromHistory[r]<l.length&&!t){let t=[],n=Math.max(0,this.usedFromHistory[r]),a=0;do{let e=l.slice(n,n+s);n+=e.length,a+=e.length,t.push(...this.filterMessagesByType(e.map(e=>i.a.getMessageByPeer(e.peerId,e.mid)),r))}while(a<s&&n<l.length);return this.usedFromHistory[r]=n,this.performSearchResult(t,e).finally(()=>{setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}let d=l.length?l[l.length-1].mid:0;return this.loadPromises[r]=i.a.getSearch(Object.assign(Object.assign({},this.searchContext),{inputFilter:{_:r},maxId:d,limit:s,nextRate:null!==(o=this.nextRates[r])&&void 0!==o?o:this.nextRates[r]=0})).then(i=>{if(l.push(...i.history.map(e=>({mid:e.mid,peerId:e.peerId}))),this.log(c+"search house of glass",r,i),n())return(i.history.length<s||void 0!==this.searchContext.folderId&&!i.next_rate||i.history.length===i.count)&&(this.loaded[r]=!0),this.nextRates[r]=i.next_rate,t?Promise.resolve():(this.usedFromHistory[r]=l.length,this.loaded[r]||(this.loadPromises[r]||Promise.resolve()).then(()=>{setTimeout(()=>{if(n()&&this.mediaTab===e){const e=this.load(!0,!0);e&&e.then(()=>{n()&&setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}},0)}),this.performSearchResult(this.filterMessagesByType(i.history,r),e))}).catch(e=>{this.log.error("load error:",e)}).finally(()=>{this.loadPromises[r]=null})}load(e=!1,t=!1){return hi(this,void 0,void 0,(function*(){const s=this.searchContext.peerId;this.log("load",e,s,this.loadPromises);const n=this.middleware.get();if(this.firstLoad){if(this.hideEmptyTabs){const e=this.mediaTabs.filter(e=>"inputMessagesFilterEmpty"!==e.inputFilter),t=e.map(e=>({_:e.inputFilter})),a=yield i.a.getSearchCounters(s,t);if(!n())return;if(this.loadMutex&&(yield this.loadMutex,!n()))return;let o,r=0;e.forEach(e=>{const t=a.find(t=>t.filter._===e.inputFilter);e.menuTab.classList.toggle("hide",!t.count),e.menuTab.classList.remove("active"),t.count&&void 0===o&&(o=e),t.count&&++r});const l=this.mediaTabsMap.get("members"),c=this.canViewMembers();l.menuTab.classList.toggle("hide",!c),c&&(o=l),this.container.classList.toggle("hide",!o),this.container.parentElement.classList.toggle("search-empty",!o),o&&(this.skipScroll=!0,this.selectTab(this.mediaTabs.indexOf(o),!1),o.menuTab.classList.add("active"),this.navScrollableContainer.classList.toggle("hide",r<=1))}this.firstLoad=!1}let a=e?[this.mediaTab]:this.mediaTabs.filter(e=>e!==this.mediaTab);if(a=a.filter(e=>{const t=e.inputFilter;return!this.loaded[t]||this.historyStorage[t]&&this.usedFromHistory[t]<this.historyStorage[t].length}),s.isUser()&&Object(Lt.a)(a,e=>"members"===e.type),!a.length)return;const o=t?50:Math.round(3*(St.a.height/130|0)*1.25),r=a.map(e=>this.loadType(e,t,o,n));return Promise.all(r).catch(e=>{this.log.error("Load error all promises:",e)})}))}getMonthContainerByTimestamp(e,t){var s;const i=new Date(1e3*e);i.setHours(0,0,0),i.setDate(1);const n=i.getTime(),a=null!==(s=this.monthContainers[t])&&void 0!==s?s:this.monthContainers[t]={};if(!(n in a)){const e=document.createElement("div");e.className="search-super-month";const s=document.createElement("div");s.classList.add("search-super-month-name");const o={month:"long"};i.getFullYear()!==(new Date).getFullYear()&&(o.year="numeric");const r=new T.c.IntlDateElement({date:i,options:o}).element;s.append(r),e.append(s);const l=document.createElement("div");l.classList.add("search-super-month-items"),e.append(s,l);const c=Object(li.a)(a,"desc");let d=0;for(;d<c.length;++d){if(n>c[d])break}a[n]={container:e,items:l},Ns(e,this.tabs[t],d)}return a[n]}canViewMembers(){return this.searchContext.peerId.isAnyChat()&&!G.a.isBroadcast(this.searchContext.peerId.toChatId())&&G.a.hasRights(this.searchContext.peerId.toChatId(),"view_participants")}cleanup(){this.loadPromises={},this.loaded={},this.loadedChats=!1,this.nextRates={},this.firstLoad=!0,this.lazyLoadQueue.clear(),this.mediaTabs.forEach(e=>{this.usedFromHistory[e.inputFilter]=-1}),this.selection.isSelecting&&this.selection.cancelSelection(),this.middleware.clean(),this.cleanScrollPositions(),this.membersList=void 0}cleanScrollPositions(){this.mediaTabs.forEach(e=>{e.scroll=void 0})}cleanupHTML(e=!1){this.urlsToRevoke.length&&(this.urlsToRevoke.forEach(e=>{URL.revokeObjectURL(e)}),this.urlsToRevoke.length=0),this.mediaTabs.forEach(e=>{if(e.contentTab.innerHTML="",this.hideEmptyTabs&&(this.container.classList.add("hide"),this.container.parentElement.classList.add("search-empty")),"chats"!==e.type&&!this.historyStorage[e.inputFilter]){const t=e.contentTab.parentElement;t.querySelector(".preloader")||Object(ee.f)(t,!0);const s=t.querySelector(".content-empty");s&&s.remove()}}),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollTop=0}copySearchContext(e){const t=Object(ue.a)(this.searchContext);return t.inputFilter={_:e},t.nextRate=this.nextRates[e],t}setQuery({peerId:e,query:t,threadId:s,historyStorage:i,folderId:n,minDate:a,maxDate:o}){this.searchContext={peerId:e,query:t||"",inputFilter:{_:this.mediaTab.inputFilter},threadId:s,folderId:n,minDate:a,maxDate:o},this.historyStorage=null!=i?i:{},this.cleanup()}}const gi=(e,t,s,i)=>{((null==s?void 0:s.listenerSetter)?s.listenerSetter.add(e):e.addEventListener.bind(e))(l.a,s=>{if(!e.classList.contains("btn-menu-toggle"))return!1;const n=e.querySelector(".btn-menu");Object(c.a)(s),e.classList.contains("menu-open")?Object(ee.c)():(t&&t(s),Object(ee.d)(n,i))})};var mi,bi=(e={},t,s,i,n)=>{var a;e.asDiv=!0;const o=null!==(a=e.container)&&void 0!==a?a:N("more",e);o.classList.add("btn-menu-toggle");const r=$s(s,e.listenerSetter);return r.classList.add(t),gi(o,i,e,n),o.append(r),o},vi=s(80),fi=s(173);!function(e){e[e.Everybody=2]="Everybody",e[e.Contacts=1]="Contacts",e[e.Nobody=0]="Nobody"}(mi||(mi={}));const yi=new class{constructor(){this.privacy={},a.a.addMultipleEventsListeners({updatePrivacy:e=>{const t=e.key._;this.privacy[t]=e.rules,a.a.dispatchEvent("privacy_update",e)}})}setPrivacy(e,t){return ct.a.invokeApi("account.setPrivacy",{key:{_:e},rules:t}).then(s=>(E.a.saveApiUsers(s.users),G.a.saveApiChats(s.chats),vi.a.processLocalUpdate({_:"updatePrivacy",key:{_:Object(fi.a)(e)},rules:t.map(e=>{const t={};return Object.assign(t,e),t._=Object(fi.a)(t._),t})}),s.rules))}getPrivacy(e){const t=Object(fi.a)(e),s=this.privacy[t];return s?Promise.resolve(s):this.privacy[t]=ct.a.invokeApi("account.getPrivacy",{key:{_:e}}).then(e=>(E.a.saveApiUsers(e.users),G.a.saveApiChats(e.chats),this.privacy[t]=e.rules))}getPrivacyRulesDetails(e){const t=[];let s={users:[],chats:[]},i={users:[],chats:[]};return e.forEach(e=>{switch(e._){case"privacyValueAllowAll":t.push(2);break;case"privacyValueDisallowAll":t.push(0);break;case"privacyValueAllowContacts":t.push(1);break;case"privacyValueAllowChatParticipants":s.chats.push(...e.chats);break;case"privacyValueAllowUsers":s.users.push(...e.users);break;case"privacyValueDisallowChatParticipants":i.chats.push(...e.chats);break;case"privacyValueDisallowUsers":i.users.push(...e.users)}}),{type:t[0],disallowPeers:i,allowPeers:s}}};le.a.appPrivacyManager=yi;var wi=yi;class Si{constructor(e){this.options=e,this.onRadioChange=e=>{e=+e,this.type=e;const t=this.options.captions[this.type],s=this.radioSection.caption;t?t instanceof HTMLElement?Object(k.a)(s,t):Object(T.b)(s,t):s.innerHTML="",s.classList.toggle("hide",!t),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===mi.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===mi.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(e)},e.captions&&e.captions.reverse(),this.radioSection=new Kn({name:e.title,caption:!0}),this.radioRows=new Map;let t=[{type:mi.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:mi.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:mi.Nobody,langKey:"PrivacySettingsController.Nobody"}];e.skipTypes&&(t=t.filter(t=>!e.skipTypes.includes(t.type)));const s=Object(st.b)();t.forEach(({type:e,langKey:t})=>{const i=new Ze({radioField:new nt({langKey:t,name:s,value:""+e})});this.radioRows.set(e,i)});const i=et([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(i),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const t=Gn(e.appendTo,"PrivacyExceptions","PrivacySettingsController.PeerInfo");this.exceptions=new Map([["disallow",{titleLangKey:e.exceptionTexts[0],key:"disallow",row:null,icon:"deleteuser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}],["allow",{titleLangKey:e.exceptionTexts[1],key:"allow",row:null,icon:"adduser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}]]),this.exceptions.forEach(s=>{s.row=new Ze(s),s.row.container.addEventListener("click",()=>{n.then(()=>{const t=this.peerIds[s.key];new Ut(e.tab.slider).open({type:"privacy",skippable:!0,title:s.titleLangKey,placeholder:"PrivacyModal.Search.Placeholder",takeOut:e=>{t.length=0,t.push(...e),s.row.subtitle.innerHTML="",s.row.subtitle.append(...this.generateStr(this.splitPeersByType(e)))},selectedPeerIds:t})})}),t.append(s.row.container)})}const n=wi.getPrivacy(e.inputKey).then(t=>{const s=wi.getPrivacyRulesDetails(t);this.setRadio(s.type),this.exceptions&&(this.peerIds={},["allow","disallow"].forEach(e=>{const t=[],i="allow"===e?s.allowPeers:s.disallowPeers;t.push(...i.users.map(e=>e.toPeerId())),t.push(...i.chats.map(e=>e.toPeerId(!0))),this.peerIds[e]=t;const n=this.exceptions.get(e).row.subtitle;n.innerHTML="",n.append(...this.generateStr(i))})),e.tab.eventListener.addEventListener("destroy",()=>{const t=[];switch(this.type){case mi.Everybody:t.push({_:"inputPrivacyValueAllowAll"});break;case mi.Contacts:t.push({_:"inputPrivacyValueAllowContacts"});break;case mi.Nobody:t.push({_:"inputPrivacyValueDisallowAll"})}this.exceptions&&[["allow","inputPrivacyValueAllowChatParticipants","inputPrivacyValueAllowUsers"],["disallow","inputPrivacyValueDisallowChatParticipants","inputPrivacyValueDisallowUsers"]].forEach(([e,s,i],n)=>{if(this.exceptions.get(e).row.container.classList.contains("hide"))return;const a=this.peerIds[e];if(a){const e=this.splitPeersByType(a);e.chats.length&&t.push({_:s,chats:e.chats}),e.users.length&&t.push({_:i,users:e.users.map(e=>E.a.getUserInput(e))})}}),wi.setPrivacy(e.inputKey,t)},{once:!0})})}setRadio(e){const t=this.radioRows.get(e);this.onRadioChange(e),t.radioField.input.checked=!0}splitPeersByType(e){const t={users:[],chats:[]};return e.forEach(e=>{t[e.isAnyChat()?"chats":"users"].push(e.isAnyChat()?e.toChatId():e)}),t}generateStr(e){return e.users.length||e.chats.length?Object(T.f)([e.users.length?Object(T.d)("Users",[e.users.length]):null,e.chats.length?Object(T.d)("Chats",[e.chats.length]):null].filter(Boolean),!1):[Object(T.d)("PrivacySettingsController.AddUsers")]}}class Ci extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e=document.createElement("div");e.append(Object(T.d)("PrivacyPhoneInfo"),document.createElement("br"),document.createElement("br"),Object(T.d)("PrivacyPhoneInfo4"),document.createElement("br"),function(e={}){const t=document.createElement("a");if(t.classList.add("anchor-copy"),e.mePath){const s="https://t.me/"+e.mePath;t.href=t.innerText=s}return Object(l.b)(t,e=>{Object(c.a)(e),tt(t.href),rt({langPackKey:"LinkCopied"})}),t}({mePath:"+380509144504"}));const t=new Si({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:[e,e,""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:e=>{s.setRadio(mi.Everybody),s.radioSection.container.classList.toggle("hide",e!==mi.Nobody)}}),s=new Si({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:["PrivacyPhoneInfo3","PrivacyPhoneInfo3",""],noExceptions:!0,skipTypes:[mi.Nobody]});this.scrollable.container.insertBefore(s.radioSection.container,t.radioSection.container.nextSibling)}}var Li=s(94);class Ii extends H{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new Kn({caption:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t=gs.a.getAnimatedEmojiSticker("🥳"),s=document.createElement("div");t?xs({doc:t,div:s,loop:!0,play:!0,width:160,height:160}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=Object(B.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});Object(l.b)(a,e=>{this.close()}),this.slider.sliceTabsUntilTab(_n,this),n.append(a),i.append(n),this.scrollable.container.append(e.container)}}var Mi=s(132);function Ei(e){return!ae.f||!e}class Pi extends H{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email-confirmation"),this.setTitle("TwoStepAuth.RecoveryTitle");const e=new Kn({caption:!0,noDelimiter:!0});Object(T.b)(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t=gs.a.getAnimatedEmojiSticker("📬"),s=document.createElement("div");t?xs({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"📬"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.codeInputField=new Mi.a({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:e=>{d(!0),Li.a.confirmPasswordEmail(""+e).then(e=>{c()}).catch(e=>{switch(e.type){case"CODE_INVALID":a.input.classList.add("error"),Object(k.a)(a.label,Object(T.d)("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),Object(k.a)(a.label,Object(T.d)("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",e)}d(!1)})}}),o=Object(B.a)("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),r=Object(B.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),c=()=>{new Ii(this.slider).open()},d=e=>{Object(gt.a)([a.input,o,r],e)};Object(l.b)(o,e=>{d(!0),Li.a.cancelPasswordEmail().then(e=>{this.slider.sliceTabsUntilTab(ki,this),this.close()},()=>{d(!1)})}),Object(l.b)(r,e=>{d(!0);const t=Object(ee.f)(r);Li.a.resendPasswordEmail().then(e=>{t.remove(),d(!1)})}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){Ei(this.isFirst)&&this.codeInputField.input.focus()}}class ki extends H{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new Kn({caption:!0,noDelimiter:!0}),t=gs.a.getAnimatedEmojiSticker("💌"),s=document.createElement("div");t?xs({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"💌"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.inputField=new O.b({name:"recovery-email",label:"RecoveryEmail",plainText:!0});a.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(c.a)(e),h()}),a.input.addEventListener("input",e=>{a.input.classList.remove("error")});const o=Object(B.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(B.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),d=()=>{new Ii(this.slider).open()},h=()=>{const e=a.value.trim(),t=X.b.matchEmail(e);if(!t||t[0].length!==e.length)return void a.input.classList.add("error");p(!0);const s=Object(ee.f)(o);Li.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:e}).then(e=>{d()},t=>{if(t.type.includes("EMAIL_UNCONFIRMED")){const s=+t.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],i=new Pi(this.slider);i.state=this.state,i.email=e,i.length=s,i.open()}else console.log("password set error",t);p(!1),s.remove()})};Object(l.b)(o,h);const p=e=>{e?(o.setAttribute("disabled","true"),r.setAttribute("disabled","true")):(o.removeAttribute("disabled"),r.removeAttribute("disabled"))};Object(l.b)(r,e=>{new ut("popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{p(!0),Object(ee.f)(r),Li.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then(()=>{d()},e=>{p(!1)})},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){Ei(this.isFirst)&&this.inputField.input.focus()}}var Ti=s(122),xi=s(108),Ai=s(131);class Oi extends H{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new Kn({noDelimiter:!0}),t=gs.a.getAnimatedEmojiSticker("💡"),s=document.createElement("div");t?xs({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"💡"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=document.createElement("div");i.classList.add("input-wrapper");const n=this.inputField=new O.b({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(c.a)(e),n.value?d():h()});const a=(e,t)=>{e&&Object(c.a)(e);const s=t?n.value:void 0;if(s&&this.newPassword===s)return void ot(T.c.format("PasswordAsHintError",!0));const i=new ki(this.slider);i.state=this.state,i.plainPassword=this.plainPassword,i.newPassword=this.newPassword,i.hint=s,i.open()},o=Object(B.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(B.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),d=e=>a(e,!0),h=e=>a(e,!1);Object(l.b)(o,d),Object(l.b)(r,h),i.append(n.container,o,r),e.content.append(i),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class ji extends H{init(){this.container.classList.add("two-step-verification","two-step-verification-enter-password","two-step-verification-re-enter-password"),this.setTitle("PleaseReEnterPassword");const e=new Kn({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new xi.a({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new Ai.a(s,157),n=Object(B.a)("btn-primary btn-color-primary",{text:"Continue"});t.append(s.container,n),e.content.append(i.container,t),this.scrollable.container.append(e.container),s.input.addEventListener("keypress",e=>{if(s.input.classList.contains("error")&&s.setState(O.a.Neutral),"Enter"===e.key)return o()});const a=()=>this.newPassword===s.value||(s.setError(),!1),o=e=>{if(e&&Object(c.a)(e),!a())return;const t=new Oi(this.slider);t.state=this.state,t.plainPassword=this.plainPassword,t.newPassword=this.newPassword,t.open()};return Object(l.b)(n,o),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class _i extends H{constructor(){super(...arguments),this.isFirst=!0}init(){const e=!this.state.pFlags.has_password||this.plainPassword;this.container.classList.add("two-step-verification","two-step-verification-enter-password"),this.setTitle(e?"PleaseEnterFirstPassword":"PleaseEnterCurrentPassword");const t=new Kn({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new xi.a({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?X.b.wrapEmojiText(this.state.hint):void 0}),n=new Ti.a(i,157),a=Object(B.a)("btn-primary btn-color-primary"),o=new T.c.IntlElement({key:"Continue"});a.append(o.element),s.append(i.container,a),t.content.append(n.container,s),this.scrollable.container.append(t.container),i.input.addEventListener("keypress",e=>{if(i.input.classList.contains("error")&&(i.input.classList.remove("error"),o.key="Continue",o.update()),"Enter"===e.key)return d()});const r=()=>!!i.value.length||(i.input.classList.add("error"),!1);let d;if(e)d=e=>{if(e&&Object(c.a)(e),!r())return;const t=new ji(this.slider);t.state=this.state,t.newPassword=i.value,t.plainPassword=this.plainPassword,t.open()};else{let e,t=()=>(e||(e=window.setInterval(t,1e4)),Li.a.getState().then(e=>{this.state=e,this.state.hint?Object(m.a)(i.label,X.b.wrapEmojiText(this.state.hint)):Object(k.a)(i.label,Object(T.d)("LoginPassword"))}));d=s=>{if(!r())return void Object(c.a)(s);a.setAttribute("disabled","true"),o.key="PleaseWait",o.update();const l=Object(ee.f)(a),d=i.value;Li.a.check(i.value,this.state).then(t=>{if(console.log(t),"auth.authorization"===t._){clearInterval(e),n&&n.remove();const t=new Fi(this.slider);t.state=this.state,t.plainPassword=d,t.open(),this.slider.removeTabFromHistory(this)}},e=>{a.removeAttribute("disabled"),i.input.classList.add("error"),e.type,o.key="TwoStepAuth.InvalidPassword",o.update(),l.remove(),i.select(),t()})},t()}return Object(l.b)(a,d),n.load()}onOpenAfterTimeout(){Ei(this.isFirst)&&this.passwordInputField.input.focus()}}class Fi extends H{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new Kn({caption:!0,noDelimiter:!0}),t=gs.a.getAnimatedEmojiSticker("🔐"),s=document.createElement("div");t?xs({doc:t,div:s,loop:!1,play:!0,width:168,height:168,emoji:"🔐"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement();if(this.state.pFlags.has_password){Object(T.b)(e.caption,"TwoStepAuth.GenericHelp");const t=Object(B.a)("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),s=Object(B.a)("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),n=Object(B.a)("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});Object(l.b)(t,()=>{const e=new _i(this.slider);e.state=this.state,e.plainPassword=this.plainPassword,e.open()}),Object(l.b)(s,()=>{new ut("popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{Li.a.updateSettings({currentPassword:this.plainPassword}).then(()=>{this.slider.sliceTabsUntilTab(_n,this),this.close()})},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()}),Object(l.b)(n,()=>{const e=new ki(this.slider);e.state=this.state,e.hint=this.state.hint,e.plainPassword=this.plainPassword,e.newPassword=this.plainPassword,e.isFirst=!0,e.open()}),i.append(t,s,n)}else{Object(T.b)(e.caption,"TwoStepAuth.SetPasswordHelp");const t=document.createElement("div");t.classList.add("input-wrapper");const s=Object(B.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});t.append(s),i.append(t),Object(l.b)(s,e=>{const t=new _i(this.slider);t.state=this.state,t.open()})}this.scrollable.container.append(e.container)}}class Di extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const e="PrivacySettingsController.LastSeenDescription";new Si({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable})}}class Ri extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new Si({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[mi.Nobody]})}}class Bi extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new Si({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}class Ni extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new Si({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[mi.Nobody]})}}class Ui extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new Si({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable});{const e="PrivacySettingsController.P2p.Desc";new Si({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}}class Hi extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=e=>{const t=new Ze({title:[e.app_name,e.app_version].join(" "),subtitle:[e.ip,e.country].join(" - "),clickable:!0,titleRight:e.pFlags.current?void 0:Object(ne.c)(new Date(1e3*Math.max(e.date_active,e.date_created)))});t.container.dataset.hash=""+e.hash;const s=document.createElement("div");return s.classList.add("row-midtitle"),s.innerHTML=[e.device_model,e.system_version||e.platform].filter(Boolean).join(", "),t.subtitle.parentElement.insertBefore(s,t.subtitle),t},t=this.authorizations.slice();{const n=new Kn({name:"CurrentSession",caption:"ClearOtherSessionsHelp"}),a=Object(Lt.a)(t,e=>e.pFlags.current),o=e(a);if(n.content.append(o.container),t.length){const e=Object(B.a)("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});Object(l.b)(e,t=>{new ut("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const t=Object(gt.a)([e],!0);ct.a.invokeApi("auth.resetAuthorizations").then(t=>{e.remove(),s.container.remove()},i).finally(()=>{t()})}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()}),n.content.append(e)}this.scrollable.append(n.container)}if(!t.length)return;const s=new Kn({name:"OtherSessions",caption:"SessionsListInfo"});t.forEach(t=>{s.content.append(e(t).container)}),this.scrollable.append(s.container);const i=e=>{"FRESH_RESET_AUTHORISATION_FORBIDDEN"===e.type&&ot(T.c.format("RecentSessions.Error.FreshReset",!0))};let n;const a=()=>{const e=n.dataset.hash;new ut("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{ct.a.invokeApi("account.resetAuthorization",{hash:e}).then(e=>{e&&n.remove()},i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},o=this.menuElement=$s([{icon:"stop",text:"Terminate",onClick:a}]);o.id="active-sessions-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Object(ee.a)(this.scrollable.container,e=>{n=Object(Ce.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(ee.e)(e,o),Object(ee.d)(o))}),Object(l.b)(this.scrollable.container,e=>{n=Object(Ce.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&a()})}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}class zi extends H{init(){this.header.classList.add("with-border"),this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");const e=new Kn({caption:"BlockedUsersInfo"});e.caption.parentElement.prepend(e.caption),this.scrollable.append(e.container);const t=Q({icon:"add",className:"is-visible"});this.content.append(t),Object(l.b)(t,e=>{new Pt({peerTypes:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:e=>{E.a.toggleBlock(e,!0)}})},{listenerSetter:this.listenerSetter});const s=_c.createChatList();this.scrollable.container.classList.add("chatlist-container"),e.content.append(s);const i=(e,t)=>{const{dom:i}=_c.addDialogNew({dialog:e,container:s,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:t}),n=E.a.getUser(e);n.pFlags.bot?i.lastMessageSpan.append("@"+n.username):n.phone?i.lastMessageSpan.innerHTML=E.a.formatUserPhone(n.phone):i.lastMessageSpan.append(n.username?"@"+n.username:E.a.getUserStatusString(e))};for(const e of this.peerIds)i(e,!0);let n;const o=this.menuElement=$s([{icon:"lockoff",text:"Unblock",onClick:()=>{const e=n.dataset.peerId.toPeerId();E.a.toggleBlock(e,!1)},options:{listenerSetter:this.listenerSetter}}]);o.id="blocked-users-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Object(ee.a)(this.scrollable.container,e=>{n=Object(bt.a)(e.target,"LI"),n&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(ee.e)(e,o),Object(ee.d)(o))},this.listenerSetter),this.listenerSetter.add(a.a)("peer_block",e=>{const{peerId:t,blocked:n}=e,a=s.querySelector(`[data-peer-id="${t}"]`);n?a||i(t,!1):a&&a.remove()});let r=!1;this.scrollable.onScrolledBottom=()=>{r||(r=!0,E.a.getBlocked(s.childElementCount,50).then(e=>{for(const t of e.peerIds)i(t,!0);(e.peerIds.length<50||s.childElementCount===e.count)&&(this.scrollable.onScrolledBottom=null),this.scrollable.checkForTriggers()}).finally(()=>{r=!1}))}}onOpenAfterTimeout(){this.scrollable.onScroll()}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}var Vi=s(134);function Ki(e){return e="input"+(e=e[0].toUpperCase()+e.slice(1))}class Gi extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("dont-u-dare-block-me"),this.setTitle("PrivacySettings");{const e=new Kn({noDelimiter:!0,caption:"SessionsInfo"});let t;const s=new Ze({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:"Loading",clickable:()=>{const e=new zi(this.slider);e.peerIds=t,e.open()}});let i;s.freezed=!0;const n=new Ze({icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:"Loading",clickable:e=>{let t;i.pFlags.has_password?t=new _i(this.slider):i.email_unconfirmed_pattern?(t=new Pi(this.slider),t.email=i.email_unconfirmed_pattern,t.length=6,t.isFirst=!0,Li.a.resendPasswordEmail()):t=new Fi(this.slider),t.state=i,t.open()}});n.freezed=!0;const o=this.activeSessionsRow=new Ze({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:"Loading",clickable:()=>{const e=new Hi(this.slider);e.authorizations=this.authorizations,e.eventListener.addEventListener("destroy",()=>{this.updateActiveSessions()},{once:!0}),e.open()}});o.freezed=!0,e.content.append(s.container,n.container,o.container),this.scrollable.append(e.container);const r=e=>{e?Object(k.a)(s.subtitle,Object(T.d)("PrivacySettingsController.UserCount",[e])):Object(k.a)(s.subtitle,Object(T.d)("BlockedEmpty",[e]))};this.listenerSetter.add(a.a)("peer_block",()=>{l()});const l=()=>{E.a.getBlocked().then(e=>{s.freezed=!1,r(e.count),t=e.peerIds})};l(),Li.a.getState().then(e=>{i=e,Object(k.a)(n.subtitle,Object(T.d)(e.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),n.freezed=!1}),this.updateActiveSessions()}{const e=new Kn({name:"PrivacyTitle",caption:"GroupsAndChannelsHelp"});e.content.classList.add("privacy-navigation-container");const t={},s=t.inputPrivacyKeyPhoneNumber=new Ze({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:"Loading",clickable:()=>{new Ci(this.slider).open()}}),i=t.inputPrivacyKeyStatusTimestamp=new Ze({titleLangKey:"LastSeenTitle",subtitleLangKey:"Loading",clickable:()=>{new Di(this.slider).open()}}),n=t.inputPrivacyKeyProfilePhoto=new Ze({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:"Loading",clickable:()=>{new Ri(this.slider).open()}}),o=t.inputPrivacyKeyPhoneCall=new Ze({titleLangKey:"WhoCanCallMe",subtitleLangKey:"Loading",clickable:()=>{new Ui(this.slider).open()}}),r=t.inputPrivacyKeyForwards=new Ze({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:"Loading",clickable:()=>{new Bi(this.slider).open()}}),l=t.inputPrivacyKeyChatInvite=new Ze({titleLangKey:"WhoCanAddMe",subtitleLangKey:"Loading",clickable:()=>{new Ni(this.slider).open()}}),c=e=>{const s=t[e];s&&wi.getPrivacy(e).then(e=>{const t=wi.getPrivacyRulesDetails(e),i=t.type===mi.Everybody?"PrivacySettingsController.Everbody":t.type===mi.Contacts?"PrivacySettingsController.MyContacts":"PrivacySettingsController.Nobody",n=t.disallowPeers.users.length+t.disallowPeers.chats.length,a=t.allowPeers.users.length+t.allowPeers.chats.length;s.subtitle.innerHTML="";const o=Object(T.d)(i);s.subtitle.append(o),(n||a)&&s.subtitle.append(` (${[-n,a?"+"+a:0].filter(Boolean).join(", ")})`)})};e.content.append(s.container,i.container,n.container,o.container,r.container,l.container),this.scrollable.append(e.container);for(const e in t)c(e);a.a.addEventListener("privacy_update",e=>{c(Ki(e.key._))})}const e=[];{const t=new Kn({name:"Privacy.SensitiveContent"});t.container.classList.add("hide"),e.push(ct.a.invokeApi("account.getContentSettings").then(e=>{if(!e.pFlags.sensitive_can_change)return;const s=e.pFlags.sensitive_enabled,i=new Ze({checkboxField:new pt.a({text:"PrivacyAndSecurity.SensitiveText",checked:s}),subtitleLangKey:"PrivacyAndSecurity.SensitiveDesc",noCheckboxSubtitle:!0});t.content.append(i.container),t.container.classList.remove("hide"),this.eventListener.addEventListener("destroy",()=>{const e=i.checkboxField.checked;e!==s&&ct.a.invokeApi("account.setContentSettings",{sensitive_enabled:e})},{once:!0})})),this.scrollable.append(t.container)}{const e=new Kn({name:"FilterChats"}),t=()=>{new ut("popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const e=Object(gt.a)([s],!0);Vi.a.clearAllDrafts().then(()=>{e()})},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},s=Object(B.a)("btn-primary btn-transparent",{icon:"delete",text:"PrivacyDeleteCloudDrafts"});this.listenerSetter.add(s)("click",t),e.content.append(s),this.scrollable.append(e.container)}return Promise.all(e)}updateActiveSessions(){ct.a.invokeApi("account.getAuthorizations").then(e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,Object(T.b)(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])})}}function Wi(e){const t=e.getContext("2d"),s=new Array(4).fill(0),i=t.getImageData(0,0,e.width,e.height).data;for(let e=0;e<i.length;e+=4)s[0]+=i[e],s[1]+=i[e+1],s[2]+=i[e+2],s[3]+=i[e+3];const n=i.length/4,a=new Uint8ClampedArray(4);return a[0]=s[0]/n,a[1]=s[1]/n,a[2]=s[2]/n,a[3]=s[3]/n,a}function qi(e,t,s,i=1){e/=255,t/=255,s/=255;const n=Math.max(e,t,s),a=Math.min(e,t,s);let o,r,l=(n+a)/2;if(n===a)o=r=0;else{let i=n-a;switch(r=l>.5?i/(2-n-a):i/(n+a),n){case e:o=(t-s)/i+(t<s?6:0);break;case t:o=(s-e)/i+2;break;case s:o=(e-t)/i+4}o/=6}return{h:360*o,s:100*r,l:100*l,a:i}}function Qi(e,t,s,i){let n,a,o;if(e/=360,s/=100,0===(t/=100))n=a=o=s;else{const i=function(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+(t-e)*(2/3-s)*6:e},r=s<.5?s*(1+t):s+t-s*t,l=2*s-r;n=i(l,r,e+1/3),a=i(l,r,e),o=i(l,r,e-1/3)}return[Math.round(255*n),Math.round(255*a),Math.round(255*o),Math.round(255*i)]}function $i(e){const t=[],s="#"===e[0]?1:0;if(e.length===5+s&&(e=(s?"#":"")+"0"+e.slice(s)),e.length===3+s)for(let i=s;i<e.length;++i)t.push(parseInt(e[i]+e[i],16));else if(e.length===4+s){for(let i=s;i<e.length-1;++i)t.push(parseInt(e[i]+e[i],16));t.push(parseInt(e[e.length-1],16))}else for(let i=s;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return t}function Yi(e){return $i(e.slice(0,7))}function Xi(e){return"#"+e.map(e=>("0"+e.toString(16)).slice(-2)).join("")}function Ji(e){return Xi(function(e){const t=e.slice(5,-1).split(", "),s=+t.pop(),i=t.map(e=>e.endsWith("%")?+e.slice(0,-1):+e);return Qi(i[0],i[1],i[2],s)}(e))}function Zi(e){let{h:t,s:s,l:i}=qi(e[0],e[1],e[2]);s>0&&(s=Math.min(100,s+5+.1*(100-s))),i=Math.max(0,.65*i);return`hsla(${t}, ${s}%, ${i}%, .4)`}class en{constructor(){this._width=50,this._height=50,this._tails=90,this._scrollTails=50,this._curve=[0,.25,.5,.75,1,1.5,2,2.5,3,3.5,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,18.3,18.6,18.9,19.2,19.5,19.8,20.1,20.4,20.7,21,21.3,21.6,21.9,22.2,22.5,22.8,23.1,23.4,23.7,24,24.3,24.6,24.9,25.2,25.5,25.8,26.1,26.3,26.4,26.5,26.6,26.7,26.8,26.9,27],this._positions=[{x:.8,y:.1},{x:.6,y:.2},{x:.35,y:.25},{x:.25,y:.6},{x:.2,y:.9},{x:.4,y:.8},{x:.65,y:.75},{x:.75,y:.4}],this._phases=this._positions.length,this.onWheel=e=>{this._animatingToNextPosition||(this._scrollDelta+=e.deltaY,void 0===this._onWheelRAF&&(this._onWheelRAF=requestAnimationFrame(this.drawOnWheel)))},this.drawOnWheel=()=>{let e=this._scrollDelta/this._scrollTails;if(this._scrollDelta%=this._scrollTails,e=e>0?Math.floor(e):Math.ceil(e),e){this.changeTail(e);const t=this.curPosition(this._phase,this._tail);this.drawGradient(t)}this._onWheelRAF=void 0},this.drawNextPositionAnimated=()=>{const e=this._frames,t=e.shift();t&&this.drawImageData(t);const s=e.length;return s||(this._animatingToNextPosition=void 0),!!s};const e=this._tails/this._curve[this._curve.length-1];for(let t=0,s=this._curve.length;t<s;++t)this._curve[t]=this._curve[t]*e;this._incrementalCurve=this._curve.map((e,t,s)=>{var i;return e-(null!==(i=s[t-1])&&void 0!==i?i:0)})}hexToRgb(e){const t=Yi(e);return{r:t[0],g:t[1],b:t[2]}}getPositions(e){const t=this._positions.slice();for(;e>0;)t.push(t.shift()),--e;const s=[];for(let e=0;e<t.length;e+=2)s.push(t[e]);return s}getNextPositions(e,t,s){const i=this.getPositions(e);if(!s[0]&&1===s.length)return[i];const n=this.getPositions(++e%this._phases).map((e,s)=>({x:(e.x-i[s].x)/t,y:(e.y-i[s].y)/t}));return s.map(e=>n.map((t,s)=>({x:i[s].x+t.x*e,y:i[s].y+t.y*e})))}curPosition(e,t){return this.getNextPositions(e,this._tails,[t])[0]}changeTail(e){for(this._tail+=e;this._tail>=this._tails;)this._tail-=this._tails,++this._phase>=this._phases&&(this._phase-=this._phases);for(;this._tail<0;)this._tail+=this._tails,--this._phase<0&&(this._phase+=this._phases)}getGradientImageData(e){const t=this._hctx.createImageData(this._width,this._height),s=t.data;let i=0;for(let t=0;t<this._height;++t){const n=t/this._height-.5,a=n*n;for(let t=0;t<this._width;++t){const o=t/this._width-.5,r=.35*Math.sqrt(o*o+a),l=r*r*.8*8,c=Math.sin(l),d=Math.cos(l),h=Math.max(0,Math.min(1,.5+o*d-n*c)),p=Math.max(0,Math.min(1,.5+o*c+n*d));let u=0,g=0,m=0,b=0;for(let t=0;t<this._colors.length;t++){const s=h-e[t].x,i=p-e[t].y;let n=Math.max(0,.9-Math.sqrt(s*s+i*i));n*=n*n*n,u+=n,g+=n*this._colors[t].r/255,m+=n*this._colors[t].g/255,b+=n*this._colors[t].b/255}s[i++]=g/u*255,s[i++]=m/u*255,s[i++]=b/u*255,s[i++]=255}}return t}drawImageData(e){this._hctx.putImageData(e,0,0),this._ctx.drawImage(this._hc,0,0,this._width,this._height)}drawGradient(e){this.drawImageData(this.getGradientImageData(e))}init(e){this._frames=[],this._phase=0,this._tail=0,this._scrollDelta=0,void 0!==this._onWheelRAF&&(cancelAnimationFrame(this._onWheelRAF),this._onWheelRAF=void 0);const t=e.getAttribute("data-colors").split(",").reverse();this._colors=t.map(e=>this.hexToRgb(e)),this._hc||(this._hc=document.createElement("canvas"),this._hc.width=this._width,this._hc.height=this._height,this._hctx=this._hc.getContext("2d")),this._canvas=e,this._ctx=this._canvas.getContext("2d"),this.update()}update(){if(this._colors.length<2){const e=this._colors[0];return this._ctx.fillStyle=`rgb(${e.r}, ${e.g}, ${e.b})`,void this._ctx.fillRect(0,0,this._width,this._height)}const e=this.curPosition(this._phase,this._tail);this.drawGradient(e)}toNextPosition(){var e;if(this._colors.length<2)return;const t=this._tail,s=this._tails;let i;const n=[];for(let a=0,o=this._incrementalCurve.length;a<o;++a){const o=this._incrementalCurve[a];let r=(null!==(e=n[a-1])&&void 0!==e?e:t)+o;+r.toFixed(2)>s&&void 0===i&&(i=a,r%=s),n.push(r)}[n.slice(0,i),void 0!==i?n.slice(i):[]].forEach((e,t,i)=>{const n=e[e.length-1];if(void 0!==n&&n>s&&(e[e.length-1]=+n.toFixed(2)),this._tail=null!=n?n:0,!e.length)return;const a=this.getNextPositions(this._phase,s,e);t!==i.length-1&&++this._phase>=this._phases&&(this._phase-=this._phases);const o=a.map(e=>this.getGradientImageData(e));this._frames.push(...o)}),this._animatingToNextPosition=!0,Object(Pe.a)(this.drawNextPositionAnimated)}scrollAnimate(e){this._colors.length<2&&e||(e&&!this._addedScrollListener?(document.addEventListener("wheel",this.onWheel),this._addedScrollListener=!0):!e&&this._addedScrollListener&&(document.removeEventListener("wheel",this.onWheel),this._addedScrollListener=!1))}cleanup(){this.scrollAnimate(!1)}static createCanvas(e){const t=document.createElement("canvas");return t.width=50,t.height=50,void 0!==e&&(t.dataset.colors=e),t}static create(e){const t=this.createCanvas(e),s=new en;return s.init(t),{gradientRenderer:s,canvas:t}}}class tn{constructor(){this.hue=0,this.saturation=100,this.lightness=50,this.alpha=1,this.elements={},this.onGrabStart=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor="grabbing"},this.onGrabEnd=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor=""},this.container=document.createElement("div"),this.container.classList.add(tn.BASE_CLASS);const e=`\n <svg class="${tn.BASE_CLASS+"-box"}" viewBox="0 0 380 198">\n <defs>\n <linearGradient id="color-picker-saturation" x1="0%" y1="0%" x2="100%" y2="0%">\n <stop offset="0%" stop-color="#fff"></stop>\n <stop offset="100%" stop-color="hsl(0,100%,50%)"></stop>\n </linearGradient>\n <linearGradient id="color-picker-brightness" x1="0%" y1="0%" x2="0%" y2="100%">\n <stop offset="0%" stop-color="rgba(0,0,0,0)"></stop>\n <stop offset="100%" stop-color="#000"></stop>\n </linearGradient>\n <pattern id="color-picker-pattern" width="100%" height="100%">\n <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-saturation)"></rect>\n <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-brightness)"></rect>\n </pattern>\n </defs>\n <rect rx="10" ry="10" x="0" y="0" width="380" height="198" fill="url(#color-picker-pattern)"></rect>\n <svg class="${tn.BASE_CLASS+"-dragger"} ${tn.BASE_CLASS+"-box-dragger"}" x="0" y="0">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n <div class="${tn.BASE_CLASS+"-sliders"}">\n <svg class="${tn.BASE_CLASS+"-color-slider"}" viewBox="0 0 380 24">\n <defs>\n <linearGradient id="hue" x1="100%" y1="0%" x2="0%" y2="0%">\n <stop offset="0%" stop-color="#f00"></stop>\n <stop offset="16.666%" stop-color="#f0f"></stop>\n <stop offset="33.333%" stop-color="#00f"></stop>\n <stop offset="50%" stop-color="#0ff"></stop>\n <stop offset="66.666%" stop-color="#0f0"></stop>\n <stop offset="83.333%" stop-color="#ff0"></stop>\n <stop offset="100%" stop-color="#f00"></stop>\n </linearGradient>\n </defs>\n <rect rx="4" ry="4" x="0" y="9" width="380" height="8" fill="url(#hue)"></rect>\n <svg class="${tn.BASE_CLASS+"-dragger"} ${tn.BASE_CLASS+"-color-slider-dragger"}" x="0" y="13">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n </div>\n `;this.container.innerHTML=e,this.elements.box=this.container.firstElementChild,this.elements.boxDragger=this.elements.box.lastElementChild,this.elements.saturation=this.elements.box.firstElementChild.firstElementChild,this.elements.sliders=this.elements.box.nextElementSibling,this.elements.hue=this.elements.sliders.firstElementChild,this.elements.hueDragger=this.elements.hue.lastElementChild,this.hexInputField=new O.b({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new O.b({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=tn.BASE_CLASS+"-inputs",t.append(this.hexInputField.container,this.rgbInputField.container),this.container.append(t),this.hexInputField.input.addEventListener("input",()=>{let e=this.hexInputField.value.replace(/#/g,"").slice(0,6);const t=e.match(/([a-fA-F\d]+)/),s=t&&t[0].length===e.length&&[6].includes(e.length);this.hexInputField.setState(s?O.a.Neutral:O.a.Error),e="#"+e,this.hexInputField.setValueSilently(e),s&&this.setColor(e,!1,!0)});const s=/^(?:rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(?:\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(?:([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$/;this.rgbInputField.input.addEventListener("input",()=>{const e=this.rgbInputField.value.match(s);this.rgbInputField.setState(e?O.a.Neutral:O.a.Error),e&&this.setColor(qi(+e[1],+e[2],+e[3]),!0,!1)}),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){xe(this.elements.box,()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()},e=>{this.saturationHandler(e.x,e.y)},()=>{this.onGrabEnd()})}attachHueListeners(){xe(this.elements.hue,()=>{this.onGrabStart(),this.hueRect=this.elements.hue.getBoundingClientRect()},e=>{this.hueHandler(e.x)},()=>{this.onGrabEnd()})}setColor(e,t=!0,s=!0){if(void 0===e)e={h:0,s:100,l:50,a:1};else if("string"==typeof e)if("#"===e[0])e=function(e){const t=$i(e);return qi(t[0],t[1],t[2],t[3])}(e);else{const t=e.match(/[.?\d]+/g);e=qi(+t[0],+t[1],+t[2],void 0===t[3]?1:+t[3])}this.boxRect=this.elements.box.getBoundingClientRect();const i=this.boxRect.width/100*e.s,n=100-e.l/(100-e.s/2)*100,a=this.boxRect.height/100*n;this.saturationHandler(this.boxRect.left+i,this.boxRect.top+a,!1),this.hueRect=this.elements.hue.getBoundingClientRect();const o=e.h/360,r=this.hueRect.left+this.hueRect.width*o;this.hueHandler(r,!1),this.hue=e.h,this.saturation=e.s,this.lightness=e.l,this.alpha=e.a,this.updatePicker(t,s)}getCurrentColor(){const e=Qi(this.hue,this.saturation,this.lightness,this.alpha),t=Xi(e),s=t.slice(0,-2);return{hsl:`hsl(${this.hue}, ${this.saturation}%, ${this.lightness}%)`,rgb:`rgb(${e[0]}, ${e[1]}, ${e[2]})`,hex:s,hsla:`hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha})`,rgba:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`,hexa:t,rgbaArray:e}}updatePicker(e=!0,t=!0){const s=this.getCurrentColor();this.elements.boxDragger.setAttributeNS(null,"fill",s.hex),e&&(this.hexInputField.setValueSilently(s.hex),this.hexInputField.setState(O.a.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(O.a.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const s=Object(ke.a)(e-this.hueRect.left,0,this.hueRect.width)/this.hueRect.width;this.hue=Math.round(360*s);const i=`hsla(${this.hue}, 100%, 50%, ${this.alpha})`;this.elements.hueDragger.setAttributeNS(null,"x",100*s+"%"),this.elements.hueDragger.setAttributeNS(null,"fill",i),this.elements.saturation.lastElementChild.setAttributeNS(null,"stop-color",i),t&&this.updatePicker()}saturationHandler(e,t,s=!0){const i=this.boxRect.width,n=this.boxRect.height,a=Object(ke.a)(e-this.boxRect.left,0,i)/i*100,o=Object(ke.a)(t-this.boxRect.top,0,n)/n*100,r=this.elements.boxDragger;r.setAttributeNS(null,"x",a+"%"),r.setAttributeNS(null,"y",o+"%");const l=Object(ke.a)(a,0,100),c=100-l/2,d=100-Object(ke.a)(o,0,100),h=Object(ke.a)(d/100*c,0,100);this.saturation=l,this.lightness=h,s&&this.updatePicker()}}tn.BASE_CLASS="color-picker";class sn extends H{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const t=$i(e),s=this.theme.background,i=Zi(t);s.id="2",s.intensity=0,s.slug="",s.color=e.toLowerCase(),s.highlightningColor=i,M.c.pushToState("settings",a.a.settings),nc.applyCurrentTheme(void 0,void 0,!0),this.setActive()}},this.onColorChange=e=>{this.applyColor(e.hex,!1)}}init(){this.header.classList.add("with-border"),this.container.classList.add("background-container","background-color-container"),this.setTitle("SetColor"),this.theme=a.a.getTheme();const e=new Kn({});this.colorPicker=new tn,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=new Kn({}),s=this.grid=document.createElement("div");s.classList.add("grid");["#E6EBEE","#B2CEE1","#008DD0","#C6E7CB","#C4E1A6","#60B16E","#CCD0AF","#A6A997","#7A7072","#FDD7AF","#FDB76E","#DD8851"].forEach(e=>{const t=document.createElement("div");t.classList.add("grid-item"),t.dataset.color=e.toLowerCase();const i=document.createElement("div");i.classList.add("grid-item-media"),i.style.backgroundColor=e,t.append(i),s.append(t)}),Object(l.b)(s,e=>{const t=Object(Ce.a)(e.target,"grid-item");if(!t||t.classList.contains("active"))return;const s=t.dataset.color;s&&this.applyColor(s)},{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container),this.applyColor=Object(ws.a)(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),t=this.theme.background,s=t.color?this.grid.querySelector(`.grid-item[data-color="${t.color}"]`):null;e!==s&&(e&&e.classList.remove("active"),s&&s.classList.add("active"))}onOpen(){setTimeout(()=>{const e=this.theme.background,t=(e.color||"").split(",")[0],s=!!t&&!e.slug;s&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(t||"#cccccc"),s||(this.colorPicker.onChange=this.onColorChange)},0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}let nn=0;class an extends H{constructor(){super(...arguments),this.tempId=0,this.clicked=new Set,this.wallpapersByElement=new Map,this.elementsByKey=new Map,this.onUploadClick=()=>{Object(pe.f)("image/x-png,image/png,image/jpeg").then(e=>{const t="wallpaper-upload-"+ ++nn,s={_:"photoSize",h:0,w:0,location:{},size:e.size,type:"full"};let i={_:"document",access_hash:"",attributes:[],dc_id:0,file_reference:[],id:t,mime_type:e.type,size:e.size,date:Date.now()/1e3,pFlags:{},thumbs:[s],file_name:e.name};i=L.a.saveDoc(i);const n=ce.a.getCacheContext(i);n.downloaded=e.size,n.url=URL.createObjectURL(e);let a={_:"wallPaper",access_hash:"",document:i,id:t,slug:t,pFlags:{}};const o=ce.a.upload(e,e.name),r=Object(ie.a)();r.addNotifyListener=o.addNotifyListener,r.cancel=o.cancel,o.then(t=>{ct.a.invokeApi("account.uploadWallPaper",{file:t,mime_type:e.type,settings:{_:"wallPaperSettings"}}).then(e=>{const t=e.document,s=ce.a.getCacheContext(t);Object.assign(s,n),a=e,a.document=L.a.saveDoc(a.document),this.setBackgroundDocument(a).then(r.resolve,r.reject)},r.reject)},r.reject);const l=this.getWallpaperKey(a);r.then(()=>{this.clicked.delete(l)},e=>{d.remove()});const c=new ye.a({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),d=this.addWallPaper(a,!1);this.clicked.add(l),c.attach(d,!1,r)})},this.onResetClick=()=>{const e=M.b.settings.themes.find(e=>e.name===this.theme.name);e&&(++this.tempId,this.theme.background=Object(ue.a)(e.background),M.c.pushToState("settings",a.a.settings),nc.applyCurrentTheme(void 0,void 0,!0),this.blurCheckboxField.setValueSilently(this.theme.background.blur))},this.onGridClick=e=>{const t=Object(Ce.a)(e.target,"grid-item");if(!t)return;const s=this.wallpapersByElement.get(t);if("wallPaperNoFile"===s._)return void this.setBackgroundDocument(s);const i=this.getWallpaperKey(s);if(this.clicked.has(i))return;this.clicked.add(i);const n=s.document,a=new ye.a({cancelable:!0,tryAgainOnFail:!1}),o=()=>{const e=this.setBackgroundDocument(s);ce.a.getCacheContext(n).url&&!this.theme.background.blur||a.attach(t,!0,e)};a.construct(),Object(l.b)(t,e=>{a.preloader.parentElement?(a.onClick(e),a.detach()):o()},{listenerSetter:this.listenerSetter}),o()},this.saveToCache=(e,t)=>{fetch(t).then(t=>{ce.a.cacheStorage.save("backgrounds/"+e,t)})},this.setBackgroundDocument=e=>{let t=++this.tempId;const s=()=>t===this.tempId,i=e.document,n=Object(ie.a)();let o;return i?(o=L.a.downloadDoc(i,nc.chat.bubbles?nc.chat.bubbles.lazyLoadQueue.queueId:0),n.addNotifyListener=o.addNotifyListener,n.cancel=o.cancel):o=Promise.resolve(),o.then(()=>{if(!s())return void n.resolve();const t=this.theme.background,o=i=>{let o;if(i&&!this.theme.background.color)o=function(e){const t=document.createElement("img");return new Promise(s=>{Object(ps.a)(t,e,()=>{const e=document.createElement("canvas"),i=t.naturalWidth/t.naturalHeight;1===i?(e.width=50,e.height=e.width/i):i>1?(e.height=50,e.width=e.height/i):e.width=e.height=50;e.getContext("2d").drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,e.width,e.height),s(Wi(e))})})}(i);else{const{canvas:t}=en.create(this.getColorsFromWallpaper(e));o=Promise.resolve(Wi(t))}o.then(o=>{var r,l,c;if(!s())return void n.resolve();const d=Zi(Array.from(o)),h=null!==(r=e.slug)&&void 0!==r?r:"";t.id=e.id,t.intensity=null!==(c=null===(l=e.settings)||void 0===l?void 0:l.intensity)&&void 0!==c?c:0,t.color=this.getColorsFromWallpaper(e),t.slug=h,t.highlightningColor=d,M.c.pushToState("settings",a.a.settings),h&&this.saveToCache(h,i),nc.applyCurrentTheme(h,i,!0).then(n.resolve)})};if(!i)return void o();const r=ce.a.getCacheContext(i);t.blur?setTimeout(()=>{const{canvas:e,promise:t}=Object(vs.a)(r.url,12,4);t.then(()=>{s()?o(e.toDataURL()):n.resolve()})},200):o(r.url)}),n},this.setActive=()=>{const e=this.grid.querySelector(".active"),t=this.elementsByKey.get(this.getWallpaperKeyFromTheme(this.theme));e!==t&&(e&&e.classList.remove("active"),t&&t.classList.add("active"))}}init(){this.header.classList.add("with-border"),this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground"),this.theme=a.a.getTheme();{const e=Gn(this.scrollable),s=Object(B.a)("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),i=Object(B.a)("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),n=Object(B.a)("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});Object(l.b)(s,this.onUploadClick,{listenerSetter:this.listenerSetter}),Object(l.b)(i,()=>{new sn(this.slider).open()},{listenerSetter:this.listenerSetter}),Object(l.b)(n,this.onResetClick,{listenerSetter:this.listenerSetter});const o=this.blurCheckboxField=new pt.a({text:"ChatBackground.Blur",name:"blur",checked:this.theme.background.blur,withRipple:!0});this.listenerSetter.add(o.input)("change",()=>{this.theme.background.blur=o.input.checked,M.c.pushToState("settings",a.a.settings),setTimeout(()=>{const e=t.querySelector(".active");if(!e)return;const s=this.wallpapersByElement.get(e);s.pFlags.pattern||"wallPaperNoFile"===s._||this.setBackgroundDocument(s)},100)}),e.append(s,i,n,o.label)}a.a.addEventListener("background_change",this.setActive),ct.a.invokeApiHashable({method:"account.getWallPapers"}).then(e=>{e.wallpapers.forEach(e=>{this.addWallPaper(e)})});const e=Gn(this.scrollable),t=this.grid=document.createElement("div");t.classList.add("grid"),Object(l.b)(t,this.onGridClick,{listenerSetter:this.listenerSetter}),e.append(t)}getColorsFromWallpaper(e){return e.settings?[e.settings.background_color,e.settings.second_background_color,e.settings.third_background_color,e.settings.fourth_background_color].filter(Boolean).map(e=>"#"+e.toString(16)).join(","):""}getWallpaperKey(e){return""+e.id}getWallpaperKeyFromTheme(e){return""+e.background.id}addWallPaper(e,t=!0){var s;const i=this.getColorsFromWallpaper(e),n="wallPaper"===e._;if(n&&e.pFlags.pattern&&!i)return;const a=!!e.pFlags.dark,o=n?e.document=L.a.saveDoc(e.document):void 0,l=document.createElement("div");l.classList.add("grid-item"),l.dataset.id=""+e.id;const c=this.getWallpaperKey(e);this.wallpapersByElement.set(l,e),this.elementsByKey.set(c,l);const d=document.createElement("div");let h,p;if(d.classList.add("grid-item-media"),n?(p=r.a.choosePhotoSize(o,200,200),h=Ps({photo:o,message:null,container:d,withoutPreloader:!0,size:p,noFadeIn:e.pFlags.pattern}),(h.loadPromises.thumb||h.loadPromises.full).then(()=>{us.a.mutate(()=>{l.append(d)})}),e.pFlags.pattern&&(d.classList.add("is-pattern"),a?(h.images.full.style.display="none",h.images.thumb&&(h.images.thumb.style.display="none")):(null===(s=e.settings)||void 0===s?void 0:s.intensity)&&(h.images.full.style.opacity=""+Math.abs(e.settings.intensity)/100))):l.append(d),e.settings&&void 0!==e.settings.background_color){const{canvas:t}=en.create(i);if(t.classList.add("background-colors-canvas"),a&&n){const s=ce.a.getCacheContext(o,p.type);h.loadPromises.full.then(()=>{t.style.webkitMaskImage=`url(${s.url})`,t.style.opacity=""+Math.abs(e.settings.intensity)/100,d.append(t)})}else d.append(t)}return this.getWallpaperKeyFromTheme(this.theme)===c&&l.classList.add("active"),this.grid[t?"append":"prepend"](l),l}}class on extends ht.b{constructor(e){super("popup-stickers",null,{closable:!0,overlayClosable:!0,body:!0}),this.stickerSetInput=e,this.onStickersClick=e=>{const t=Object(Ce.a)(e.target,"sticker-set-sticker");if(!t)return;const s=t.dataset.docId;nc.chat.input.sendMessageWithDocument(s)?this.hide():console.warn("got no doc by id:",s)},this.h6=document.createElement("h6"),this.h6.append(Object(T.d)("Loading")),this.header.append(this.h6),this.addEventListener("close",()=>{I.a.setOnlyOnePlayableGroup("")});const t=document.createElement("div");t.classList.add("sticker-set"),this.stickersDiv=document.createElement("div"),this.stickersDiv.classList.add("sticker-set-stickers","is-loading"),Object(l.b)(this.stickersDiv,this.onStickersClick,{listenerSetter:this.listenerSetter}),Object(ee.f)(this.stickersDiv,!0),this.stickersFooter=document.createElement("div"),this.stickersFooter.classList.add("sticker-set-footer"),t.append(this.stickersDiv);const s=Object(B.a)("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.stickersFooter.append(s),this.body.append(t);new P.b(this.body);this.body.append(this.stickersFooter),this.loadStickerSet()}loadStickerSet(){return gs.a.getStickerSet(this.stickerSetInput).then(e=>{if(!e)return rt({langPackKey:"StickerSet.DontExist"}),void this.hide();let t;this.set=e.set,I.a.setOnlyOnePlayableGroup("STICKERS-POPUP"),Object(m.a)(this.h6,X.a.wrapEmojiText(e.set.title)),this.stickersFooter.classList.toggle("add",!e.set.installed_date),e.set.installed_date?(t=Object(B.a)("btn-primary btn-primary-transparent danger",{noRipple:!0}),t.append(Object(T.d)("RemoveStickersCount",[Object(T.d)("Stickers",[e.set.count])]))):(t=Object(B.a)("btn-primary btn-color-primary",{noRipple:!0}),t.append(Object(T.d)("AddStickersCount",[Object(T.d)("Stickers",[e.set.count])]))),this.stickersFooter.textContent="",this.stickersFooter.append(t),Object(l.b)(t,()=>{const e=Object(gt.a)([t],!0);gs.a.toggleStickerSet(this.set).then(()=>{this.hide()}).catch(()=>{e()})});const s=new Z.d;this.stickersDiv.classList.remove("is-loading"),this.stickersDiv.innerHTML="";for(let t of e.documents){if("documentEmpty"===t._)continue;const e=document.createElement("div");e.classList.add("sticker-set-sticker");const i=b.b.active.esgSticker.width;xs({doc:t,div:e,lazyLoadQueue:s,group:"STICKERS-POPUP",play:!0,loop:!0,width:i,height:i}),this.stickersDiv.append(e)}})}}var rn,ln=s(29);function cn(e,t=!0){return function(e,t,s=!0){const i=e;let n;return s||(e=Se.a),function s(){e(),n=ln.a.setTimeout(s,t())}(),e=i,()=>{clearTimeout(n)}}(e,()=>1e3*(60-(new Date).getSeconds()),t)}var dn=!!(null===(rn=null===navigator||void 0===navigator?void 0:navigator.geolocation)||void 0===rn?void 0:rn.getCurrentPosition)&&!1;class hn extends H{init(){return this.header.classList.add("with-border"),this.setTitle("DoubleTapSetting"),this.container.classList.add("quick-reaction-container"),Promise.all([jt.a.getQuickReaction(),jt.a.getAvailableReactions()]).then(([e,t])=>{t=t.filter(e=>!e.pFlags.inactive);const s=new Kn,i=t.map(t=>{const s=new nt({name:"quick-reaction",text:t.title,value:t.reaction,alignRight:!0}),i=new Ze({radioField:s,havePadding:!0});return s.main.classList.add("quick-reaction-title"),Os({row:i,doc:t.static_icon,size:"small"}),t===e&&s.setValueSilently(!0),i}),n=et(i,e=>{jt.a.setDefaultReaction(e)});s.content.append(n),this.scrollable.append(s.container)})}}class pn{constructor(e,t,s,i,n,a=!0){const o="range-setting-selector";this.container=document.createElement("div"),this.container.classList.add(o);const r=document.createElement("div");r.classList.add(o+"-details");const l=document.createElement("div");l.classList.add(o+"-name"),Object(T.b)(l,e);const c=this.valueContainer=document.createElement("div");c.classList.add(o+"-value"),a&&(c.innerHTML=""+s),r.append(l,c),this.range=new Ae({step:t,min:i,max:n},s),this.range.setListeners(),this.range.setHandlers({onScrub:e=>{this.onChange&&this.onChange(e),a&&(c.innerText=""+e)}}),this.container.append(r,this.range.container)}}class un extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("general-settings-container"),this.setTitle("General");const e=Gn.bind(null,this.scrollable);{const t=e("Settings"),s=new pn("TextSize",1,a.a.settings.messagesTextSize,12,20);s.onChange=e=>{M.c.setByKey("settings.messagesTextSize",e)};const i=Object(B.a)("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"});Object(l.b)(i,()=>{new an(this.slider).open()});const n=new pt.a({text:"EnableAnimations",name:"animations",stateKey:"settings.animationsEnabled",withRipple:!0});t.append(s.container,i,n.label)}{const t=e("General.Keyboard"),s=document.createElement("form"),i="send-shortcut",n="settings.sendShortcut",a=new Ze({radioField:new nt({langKey:"General.SendShortcut.Enter",name:i,value:"enter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),o=new Ze({radioField:new nt({name:i,value:"ctrlEnter",stateKey:n}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});Object(T.b)(o.radioField.main,"General.SendShortcut.CtrlEnter",[ae.b?"⌘":"Ctrl"]),s.append(a.container,o.container),t.append(s)}if(dn){const t=e("DistanceUnitsTitle"),s=document.createElement("form"),i="distance-unit",n="settings.distanceUnit",a=new Ze({radioField:new nt({langKey:"DistanceUnitsKilometers",name:i,value:"kilometers",stateKey:n})}),o=new Ze({radioField:new nt({langKey:"DistanceUnitsMiles",name:i,value:"miles",stateKey:n})});s.append(a.container,o.container),t.append(s)}{const t=e("General.TimeFormat"),s=document.createElement("form"),i="time-format",n="settings.timeFormat",a=[["h12","General.TimeFormat.h12"],["h23","General.TimeFormat.h23"]],o=a.map(([e,t])=>new Ze({radioField:new nt({langKey:t,name:i,value:e,stateKey:n})})),r=cn(()=>{const e=new Date;a.forEach(([t],s)=>{const i=e.toLocaleTimeString("en-us-u-hc-"+t,{hour:"2-digit",minute:"2-digit"});o[s].subtitle.textContent=i})});this.eventListener.addEventListener("destroy",r),s.append(...o.map(e=>e.container)),t.append(s)}{const t=e("Emoji"),s=new pt.a({text:"GeneralSettings.EmojiPrediction",name:"suggest-emoji",stateKey:"settings.emoji.suggest",withRipple:!0}),i=new pt.a({text:"GeneralSettings.BigEmoji",name:"emoji-big",stateKey:"settings.emoji.big",withRipple:!0});t.append(s.label,i.label)}{const e=new Kn({name:"Telegram.InstalledStickerPacksController",caption:"StickersBotInfo"}),t=new Ze({titleLangKey:"DoubleTapSetting",havePadding:!0,clickable:()=>{new hn(this.slider).open()}}),s=()=>{Promise.resolve(jt.a.getQuickReaction()).then(e=>{Os({row:t,doc:e.static_icon,size:"small"})})};s(),this.listenerSetter.add(a.a)("quick_reaction",s);const i=new pt.a({text:"Stickers.SuggestStickers",name:"suggest",stateKey:"settings.stickers.suggest",withRipple:!0}),n=new pt.a({text:"InstalledStickers.LoopAnimated",name:"loop",stateKey:"settings.stickers.loop",withRipple:!0}),o={},r=e.generateContentElement(),l=new Z.d,c=(e,t="append")=>{const s=new Ze({title:X.b.wrapEmojiText(e.title),subtitleLangKey:"Stickers",subtitleLangArgs:[e.count],havePadding:!0,clickable:()=>{new on({id:e.id,access_hash:e.access_hash}).show()}});o[e.id]=s;const i=document.createElement("div");i.classList.add("row-media"),As({set:e,container:i,group:"GENERAL-SETTINGS",lazyLoadQueue:l,width:48,height:48,autoplay:!0}),s.container.append(i),r[t](s.container)};gs.a.getAllStickers().then(e=>{Object(ys.a)(e);for(const t of e.sets)c(t)}),this.listenerSetter.add(a.a)("stickers_installed",e=>{const t=e;o[t.id]||c(t,"prepend")}),this.listenerSetter.add(a.a)("stickers_deleted",e=>{const t=e;o[t.id]&&(o[t.id].container.remove(),delete o[t.id])}),e.content.append(t.container,i.label,n.label),this.scrollable.append(e.container)}}onOpen(){this.init&&(this.init(),this.init=null)}}var gn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class mn extends H{init(){return gn(this,void 0,void 0,(function*(){this.container.classList.add("edit-profile-container"),this.setTitle("EditAccount.Title");const e=[];{const t=Gn(this.scrollable,void 0,"Bio.Description"),s=document.createElement("div");s.classList.add("input-wrapper"),this.firstNameInputField=new O.b({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new O.b({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new O.b({label:"EditProfile.BioLabel",name:"bio",maxLength:70}),s.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container);const i=document.createElement("div");i.classList.add("caption"),Object(T.e)({element:i,key:"Bio.Description"}),e.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.editPeer=new Xe({peerId:a.a.myId,inputFields:e,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),t.append(this.editPeer.avatarEdit.container,s)}{const t=new Kn({name:"EditAccount.Username",caption:!0}),s=document.createElement("div");s.classList.add("input-wrapper"),this.usernameInputField=new dt({label:"EditProfile.Username.Label",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange(),this.setProfileUrl()},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"}),s.append(this.usernameInputField.container);const i=t.caption;i.append(Object(T.d)("UsernameSettings.ChangeDescription")),i.append(document.createElement("br"),document.createElement("br"));const n=this.profileUrlContainer=document.createElement("div");n.classList.add("profile-url-container");const a=this.profileUrlAnchor=document.createElement("a");a.classList.add("profile-url"),a.href="#",a.target="_blank",n.append(Object(T.d)("UsernameHelpLink",[a])),i.append(n),e.push(this.usernameInputField),t.content.append(s),this.scrollable.append(t.container)}Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;let e=[];e.push(n.default.updateProfile(this.firstNameInputField.value,this.lastNameInputField.value,this.bioInputField.value).then(()=>{this.close()},e=>{console.error("updateProfile error:",e)})),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then(e=>n.default.uploadProfilePhoto(e))),this.usernameInputField.isValidToChange()&&e.push(E.a.updateUsername(this.usernameInputField.value)),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter});const t=E.a.getSelf(),s=yield n.default.getProfile(t.id,!0);this.firstNameInputField.setOriginalValue(t.first_name,!0),this.lastNameInputField.setOriginalValue(t.last_name,!0),this.bioInputField.setOriginalValue(s.about,!0),this.usernameInputField.setOriginalValue(t.username,!0),this.setProfileUrl(),this.editPeer.handleChange()}))}setProfileUrl(){if(this.usernameInputField.input.classList.contains("error")||!this.usernameInputField.value.length)this.profileUrlContainer.style.display="none";else{this.profileUrlContainer.style.display="";let e="https://t.me/"+this.usernameInputField.value;this.profileUrlAnchor.innerText=e,this.profileUrlAnchor.href=e}}}var bn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class vn extends H{constructor(){super(...arguments),this.renderResults=e=>bn(this,void 0,void 0,(function*(){yield E.a.getContacts(),e.forEach(e=>{const{dom:t}=_c.addDialogNew({dialog:e,container:this.selector.scrollable,drawStatus:!1,rippleEnabled:!0,avatarSize:46}),s=this.selector.selected.has(e);t.containerEl.append(this.checkbox(s));const i=[];this.dialogsByFilters.forEach((t,s)=>{if(t.has(e)){const e=document.createElement("span");Object(m.a)(e,X.b.wrapEmojiText(s.title)),i.push(e)}});Object(T.f)(i,!1).forEach(e=>{t.lastMessageSpan.append(e)})})})),this.onSelectChange=e=>{"included"===this.type&&(this.confirmBtn.style.display=e?"":"none")}}init(){return this.content.remove(),this.container.classList.add("included-chatlist-container"),this.confirmBtn=N("check btn-confirm blue",{noRipple:!0}),this.confirmBtn.style.display="none",this.header.append(this.confirmBtn),this.confirmBtn.addEventListener("click",()=>{const e=this.selector.getSelected();if("included"===this.type)for(const e in this.filter.pFlags)0!==e.indexOf("exclude_")&&delete this.filter.pFlags[e];else for(const e in this.filter.pFlags)0===e.indexOf("exclude_")&&delete this.filter.pFlags[e];const t=[];for(const s of e)s.isPeerId()?t.push(s.toPeerId()):this.filter.pFlags[s]=!0;let s;s="included"===this.type?e=>t.includes(e):e=>!t.includes(e),Object(f.a)(this.filter.pinnedPeerIds,(e,t)=>{s(e)||(this.filter.pinnedPeerIds.splice(t,1),this.filter.pinned_peers.splice(t,1))});const i="included"===this.type?"excludePeerIds":"includePeerIds",n="included"===this.type?"exclude_peers":"include_peers";Object(f.a)(this.filter[i],(e,s)=>{t.includes(e)&&(this.filter[i].splice(s,1),this.filter[n].splice(s,1))}),this.filter["included"===this.type?"includePeerIds":"excludePeerIds"]=t,this.filter["included"===this.type?"include_peers":"exclude_peers"]=t.map(e=>o.a.getInputPeerById(e)),this.editFolderTab.setFilter(this.filter,!1),this.close()}),this.dialogsByFilters=new Map,i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.dialogsByFilters.set(t,new Set(i.a.dialogsStorage.getFolderDialogs(t.id).map(e=>e.peerId)))})}checkbox(e){const t=new pt.a({round:!0});return e&&(t.input.checked=e),t.label}onOpen(){this.init&&(this.init(),this.init=null),this.confirmBtn.style.display="excluded"===this.type?"":"none",this.setTitle("included"===this.type?"FilterAlwaysShow":"FilterNeverShow");const e=this.filter,t=new Kn({noDelimiter:!0,name:"FilterChatTypes"});let s;t.container.classList.add("folder-categories"),s="excluded"===this.type?{exclude_muted:{ico:"mute",text:"ChatList.Filter.MutedChats"},exclude_archived:{ico:"archive",text:"ChatList.Filter.Archive"},exclude_read:{ico:"readchats",text:"ChatList.Filter.ReadChats"}}:{contacts:{ico:"newprivate",text:"ChatList.Filter.Contacts"},non_contacts:{ico:"noncontacts",text:"ChatList.Filter.NonContacts"},groups:{ico:"group",text:"ChatList.Filter.Groups"},broadcasts:{ico:"newchannel",text:"ChatList.Filter.Channels"},bots:{ico:"bots",text:"ChatList.Filter.Bots"}};const i=document.createDocumentFragment();for(const e in s){const t=Object(B.a)("btn-primary btn-transparent folder-category-button",{icon:s[e].ico,text:s[e].text});t.dataset.peerId=e,t.append(this.checkbox()),i.append(t)}t.content.append(i);const n=("included"===this.type?e.includePeerIds:e.excludePeerIds).slice();this.selector=new Mt({appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search",sectionNameLangPackKey:"FilterChats"}),this.selector.selected=new Set(n);let a=!1;const o=this.selector.add.bind(this.selector);this.selector.add=(e,t,i)=>{if(this.selector.selected.size>=100&&a&&!s[e]){const t=this.selector.list.querySelector(`[data-peer-id="${e}"] [type="checkbox"]`);t&&setTimeout(()=>{t.checked=!1},0);return void ot(T.c.format("excluded"===this.type?"ChatList.Filter.Exclude.LimitReached":"ChatList.Filter.Include.LimitReached",!0))}const n=o(e,s[e]?Object(T.d)(s[e].text):void 0,i);return s[e]&&n.querySelector("avatar-element").classList.add("tgico-"+s[e].ico),n},this.selector.scrollable.container.append(t.container,this.selector.scrollable.container.lastElementChild),this.selector.addInitial(n),a=!0;for(const i in e.pFlags)s.hasOwnProperty(i)&&e.pFlags[i]&&t.content.querySelector(`[data-peer-id="${i}"]`).click()}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}open(e,t,s){return this.originalFilter=e,this.filter=Object(ue.a)(this.originalFilter),this.type=t,this.editFolderTab=s,super.open()}}var fn=s(105);class yn extends H{constructor(){super(...arguments),this.flags={}}init(){this.container.classList.add("edit-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.caption.append(Object(T.d)("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=N("check btn-confirm hide blue");const e={icon:"delete danger",text:"FilterMenuDelete",onClick:()=>{new ut("filter-delete",{titleLangKey:"ChatList.Filter.Confirm.Remove.Header",descriptionLangKey:"ChatList.Filter.Confirm.Remove.Text",buttons:[{langKey:"Delete",callback:()=>{e.element.setAttribute("disabled","true"),i.a.filtersStorage.updateDialogFilter(this.filter,!0).then(e=>{e&&this.close()}).finally(()=>{e.element.removeAttribute("disabled")})},isDanger:!0}]}).show()}};this.menuBtn=bi({},"bottom-left",[e]),this.menuBtn.classList.add("hide"),this.header.append(this.confirmBtn,this.menuBtn);const t=new Kn({}),s=document.createElement("div");s.classList.add("input-wrapper"),this.nameInputField=new O.b({label:"FilterNameHint",maxLength:12}),s.append(this.nameInputField.container),t.content.append(s);const n=(e,t,s,i)=>{const n=new Kn({name:t,noDelimiter:!0});n.container.classList.add("folder-list",e);const a=n.generateContentElement();return a.classList.add("folder-categories"),s.forEach(e=>{const t=Object(B.a)("folder-category-button btn btn-primary btn-transparent",{icon:e.icon,text:e.text,noRipple:!e.withRipple||void 0});e.name&&(i[e.name]=t),a.append(t)}),n};this.includePeerIds=n("folder-list-included","FilterInclude",[{icon:"add primary",text:"ChatList.Filter.Include.AddChat",withRipple:!0},{text:"ChatList.Filter.Contacts",icon:"newprivate",name:"contacts"},{text:"ChatList.Filter.NonContacts",icon:"noncontacts",name:"non_contacts"},{text:"ChatList.Filter.Groups",icon:"group",name:"groups"},{text:"ChatList.Filter.Channels",icon:"channel",name:"broadcasts"},{text:"ChatList.Filter.Bots",icon:"bots",name:"bots"}],this.flags),this.excludePeerIds=n("folder-list-excluded","FilterExclude",[{icon:"minus primary",text:"ChatList.Filter.Exclude.AddChat",withRipple:!0},{text:"ChatList.Filter.MutedChats",icon:"mute",name:"exclude_muted"},{text:"ChatList.Filter.Archive",icon:"archive",name:"exclude_archived"},{text:"ChatList.Filter.ReadChats",icon:"readchats",name:"exclude_read"}],this.flags),this.scrollable.append(this.stickerContainer,this.caption,t.container,this.includePeerIds.container,this.excludePeerIds.container);const a=this.includePeerIds.container.querySelector(".folder-categories"),o=this.excludePeerIds.container.querySelector(".folder-categories");a.querySelector(".btn").addEventListener("click",()=>{new vn(this.slider).open(this.filter,"included",this)}),o.querySelector(".btn").addEventListener("click",()=>{new vn(this.slider).open(this.filter,"excluded",this)}),this.confirmBtn.addEventListener("click",()=>{if(this.nameInputField.input.classList.contains("error"))return;if(!this.nameInputField.value.trim())return void this.nameInputField.input.classList.add("error");let e,t=Array.from(a.children).slice(1).reduce((e,t)=>e+ +!t.style.display,0);t+=this.filter.include_peers.length,t?(this.confirmBtn.setAttribute("disabled","true"),e=this.filter.id?i.a.filtersStorage.updateDialogFilter(this.filter):i.a.filtersStorage.createDialogFilter(this.filter),e.then(e=>{e&&this.close()}).catch(e=>{"DIALOG_FILTERS_TOO_MUCH"===e.type?ot("Sorry, you can't create more folders."):console.error("updateDialogFilter error:",e)}).finally(()=>{this.confirmBtn.removeAttribute("disabled")})):ot("Please choose at least one chat for this folder.")}),this.nameInputField.input.addEventListener("input",()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()});const r="edit"===this.type?[i.a.filtersStorage.reloadMissingPeerIds(this.filter.id,"pinned_peers"),i.a.filtersStorage.reloadMissingPeerIds(this.filter.id,"include_peers"),i.a.filtersStorage.reloadMissingPeerIds(this.filter.id,"exclude_peers")]:[];return Promise.all([this.loadAnimationPromise=oe.a.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_2").then(e=>(this.animation=e,oe.a.waitForFirstFrame(e))),...r])}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}onCreateOpen(){this.setTitle("FilterNew"),this.menuBtn.classList.add("hide"),this.confirmBtn.classList.remove("hide"),this.nameInputField.value="";for(const e in this.flags)this.flags[e].style.display="none"}onEditOpen(){this.setTitle("create"===this.type?"FilterNew":"FilterHeaderEdit"),"edit"===this.type&&(this.menuBtn.classList.remove("hide"),this.confirmBtn.classList.add("hide"));const e=this.filter;this.nameInputField.value=Object(fn.a)(X.b.wrapDraftText(e.title));for(const t in this.flags)this.flags[t].style.display=e.pFlags[t]?"":"none";["includePeerIds","excludePeerIds"].forEach(t=>{const s=this[t],n=_c.createChatList();let a=e[t];Object(f.a)(a,(e,t,s)=>{(e=>!!i.a.getDialogOnly(e)||!!e.isUser()&&"user"===E.a.getUser(e.toUserId())._)(e)||s.splice(t,1)}),a=a.slice();const o=e=>{for(let t=0,s=Math.min(a.length,e);t<s;++t){const e=a.shift();if(!e.isUser()&&!i.a.getDialogOnly(e))continue;const{dom:t}=_c.addDialogNew({dialog:e,container:n,drawStatus:!1,rippleEnabled:!1,meAsSaved:!0,avatarSize:32});t.lastMessageSpan.parentElement.remove()}a.length?r.lastElementChild.replaceWith(Object(T.d)("FilterShowMoreChats",[a.length])):r&&r.remove()};let r;if(s.generateContentElement().append(n),a.length){const e=s.generateContentElement();r=Object(B.a)("folder-category-button btn btn-primary btn-transparent",{icon:"down"}),r.classList.add("load-more","rp-overflow"),r.addEventListener("click",()=>o(20)),r.append(Object(T.d)("FilterShowMoreChats",[a.length])),e.append(r)}o(4)})}editCheckForChange(){if("edit"===this.type){const e=!Object(ge.a)(this.originalFilter,this.filter);this.confirmBtn.classList.toggle("hide",!e),this.menuBtn.classList.toggle("hide",e)}}setFilter(e,t){this.container&&Array.from(this.container.querySelectorAll("ul, .load-more")).forEach(e=>e.remove()),t?(this.originalFilter=e,this.filter=Object(ue.a)(e)):(this.filter=e,this.onEditOpen(),this.editCheckForChange())}open(e){return void 0===e?(this.setFilter({_:"dialogFilter",id:0,title:"",pFlags:{},pinned_peers:[],include_peers:[],exclude_peers:[],pinnedPeerIds:[],includePeerIds:[],excludePeerIds:[]},!0),this.type="create"):(this.setFilter(e,!0),this.type="edit"),super.open().then(()=>{"edit"===this.type?(this.setFilter(this.originalFilter,!0),this.onEditOpen()):this.onCreateOpen()})}}var wn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Sn extends H{constructor(){super(...arguments),this.filtersRendered={}}renderFolder(e,t,s){let n,a,r="",c=[];if("dialogFilterSuggested"===e._)n=e.filter,r=e.description;else{if(n=e,1===Object.keys(n.pFlags).length){const e=n.pFlags;let t;e.contacts?t="FilterAllContacts":e.non_contacts?t="FilterAllNonContacts":e.groups?t="FilterAllGroups":e.broadcasts?t="FilterAllChannels":e.bots&&(t="FilterAllBots"),t&&c.push(Object(T.d)(t))}if(!c.length){const e=i.a.dialogsStorage.getFolderDialogs(n.id);let t=0,s=0,a=0;for(const i of e)o.a.isAnyGroup(i.peerId)?a++:o.a.isBroadcast(i.peerId)?s++:t++;t&&c.push(Object(T.d)("Chats",[t])),s&&c.push(Object(T.d)("Channels",[s])),a&&c.push(Object(T.d)("Groups",[a]))}}if(s)s.subtitle.textContent="",Object(T.f)(c).forEach(e=>{s.subtitle.append(e)});else if(s=new Ze({title:X.a.wrapEmojiText(n.title),subtitle:r,clickable:!0}),c.length&&Object(T.f)(c).forEach(e=>{s.subtitle.append(e)}),"dialogFilter"===e._){const e=n.id;this.filtersRendered.hasOwnProperty(n.id)||Object(l.b)(s.container,()=>{new yn(this.slider).open(i.a.filtersStorage.getFilter(e))},{listenerSetter:this.listenerSetter}),this.filtersRendered[n.id]=s}return a=s.container,n.hasOwnProperty("orderIndex")?Ns(a,a.parentElement||t,n.orderIndex):t&&t.append(a),a}init(){return wn(this,void 0,void 0,(function*(){this.container.classList.add("chat-folders-container"),this.setTitle("ChatList.Filter.List.Title"),this.scrollable.container.classList.add("chat-folders"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const e=document.createElement("div");e.classList.add("caption"),Object(T.e)({element:e,key:"ChatList.Filter.Header"}),this.createFolderBtn=Object(B.a)("btn-primary btn-color-primary btn-control tgico",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new Kn({name:"Filters"}),this.foldersSection.container.style.display="none",this.suggestedSection=new Kn({name:"FilterRecommended"}),this.suggestedSection.container.style.display="none",this.scrollable.append(this.stickerContainer,e,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),Object(l.b)(this.createFolderBtn,()=>{Object.keys(this.filtersRendered).length>=10?ot("Sorry, you can't create more folders."):new yn(this.slider).open()},{listenerSetter:this.listenerSetter});const t=()=>{this.foldersSection.container.style.display=Object.keys(this.filtersRendered).length?"":"none"};return i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.renderFolder(t,this.foldersSection.content);t()}),this.listenerSetter.add(a.a)("filter_update",e=>{this.filtersRendered.hasOwnProperty(e.id)?this.renderFolder(e,null,this.filtersRendered[e.id]):this.renderFolder(e,this.foldersSection.content),t(),this.getSuggestedFilters()}),this.listenerSetter.add(a.a)("filter_delete",e=>{this.filtersRendered.hasOwnProperty(e.id)&&(this.getSuggestedFilters(),this.filtersRendered[e.id].container.remove(),delete this.filtersRendered[e.id]),t()}),this.listenerSetter.add(a.a)("filter_order",e=>{e.forEach((e,t)=>{const s=this.filtersRendered[e].container;Ns(s,s.parentElement,t+1)})}),this.loadAnimationPromise=oe.a.loadAnimationAsAsset({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"Folders_1").then(e=>(this.animation=e,oe.a.waitForFirstFrame(e))),this.getSuggestedFilters(),this.loadAnimationPromise}))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}getSuggestedFilters(){return ct.a.invokeApi("messages.getSuggestedDialogFilters").then(e=>{this.suggestedSection.container.style.display=e.length?"":"none",Array.from(this.suggestedSection.content.children).slice(1).forEach(e=>e.remove()),e.forEach(e=>{const t=this.renderFolder(e),s=Object(B.a)("btn-primary btn-color-primary",{text:"Add"});t.append(s),this.suggestedSection.content.append(t),Object(l.b)(s,n=>{if(Object(c.a)(n),Object.keys(this.filtersRendered).length>=10)return void ot("Sorry, you can't create more folders.");s.setAttribute("disabled","true");const a=e.filter;a.includePeerIds=[],a.excludePeerIds=[],a.pinnedPeerIds=[],i.a.filtersStorage.createDialogFilter(a,!0).then(e=>{e&&t.remove()}).finally(()=>{s.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter})})})}}class Cn extends z{init(){this.header.classList.add("with-border"),this.container.classList.add("notifications-container","with-border"),this.setTitle("Telegram.NotificationSettingsViewController");const e=e=>{const t=new Kn({name:e.name}),s=new Ze({checkboxField:new pt.a({text:e.typeText,checked:!0}),subtitleLangKey:"Loading"}),i=new Ze({checkboxField:new pt.a({text:"MessagePreview",checked:!0}),subtitleLangKey:"Loading"});t.content.append(s.container,i.container),this.scrollable.append(t.container);const n={_:e.inputKey},o=Bt.a.getNotifySettings(n);(o instanceof Promise?o:Promise.resolve(o)).then(t=>{const o=()=>{const e=Bt.a.isMuted(t);return s.checkboxField.checked=!e,i.checkboxField.checked=t.show_previews,e};o(),this.eventListener.addEventListener("destroy",()=>{const e=!s.checkboxField.checked,a=i.checkboxField.checked;if(e===Bt.a.isMuted(t)&&a===t.show_previews)return;const o=Object(ue.a)(t);o._="inputPeerNotifySettings",o.mute_until=e?2147483647:0,o.show_previews=a,Bt.a.updateNotifySettings(n,o)},{once:!0}),this.listenerSetter.add(a.a)("notify_settings",s=>{const i=Ki(s.peer._);e.inputKey===i&&(t=s.notify_settings,o())})})};e({name:"NotificationsPrivateChats",typeText:"NotificationsForPrivateChats",inputKey:"inputNotifyUsers"}),e({name:"NotificationsGroups",typeText:"NotificationsForGroups",inputKey:"inputNotifyChats"}),e({name:"NotificationsChannels",typeText:"NotificationsForChannels",inputKey:"inputNotifyBroadcasts"});{const e=new Kn({name:"NotificationsOther"}),t=new Ze({checkboxField:new pt.a({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading"}),s=new Ze({checkboxField:new pt.a({text:"Notifications.Sound",checked:!0,stateKey:"settings.notifications.sound"}),subtitleLangKey:"Loading"});M.c.getState().then(e=>{s.checkboxField.checked=e.settings.notifications.sound}),e.content.append(t.container,s.container),this.scrollable.append(e.container),Bt.a.getContactSignUpNotification().then(e=>{t.checkboxField.checked=e,this.eventListener.addEventListener("destroy",()=>{const s=t.checkboxField.checked;e!==s&&Bt.a.setContactSignUpNotification(!s)},{once:!0})})}}}var Ln=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class In extends H{init(){return Ln(this,void 0,void 0,(function*(){this.header.classList.add("with-border"),this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const e=new Kn({}),t=new Map,s=ct.a.invokeApiCacheable("langpack.getLanguages",{lang_pack:"macos"}).then(s=>{const i=Object(st.b)();s.forEach(e=>{const s=new Ze({radioField:new nt({text:e.name,name:i,value:e.lang_code}),subtitle:e.native_name});t.set(e.lang_code,s)});const n=et([...t.values()],e=>{T.c.getLangPack(e)});T.c.getCacheLangPack().then(e=>{const s=t.get(e.lang_code);s?s.radioField.setValueSilently(!0):console.error("no row",s,e)}),e.content.append(n)});return this.scrollable.append(e.container),s}))}}function Mn(e){return new Promise((t,s)=>{const{button:i,checkbox:n}=e;i.callback=e=>{t(e?!!e.size:void 0)};const a=Object(ht.a)([i]);a.find(e=>e.isCancel).callback=()=>{s()},e.buttons=a,e.checkboxes=n&&[n],new ut("popup-confirmation",e).show()})}function En(e,t){const s=new Kn({name:t}),i="settings.autoDownload."+e+".",n=new pt.a({text:"AutodownloadContacts",name:"contacts",stateKey:i+"contacts",withRipple:!0}),a=new pt.a({text:"AutodownloadPrivateChats",name:"private",stateKey:i+"private",withRipple:!0}),o=new pt.a({text:"AutodownloadGroupChats",name:"groups",stateKey:i+"groups",withRipple:!0}),r=new pt.a({text:"AutodownloadChannels",name:"channels",stateKey:i+"channels",withRipple:!0});return s.content.append(n.label,a.label,o.label,r.label),s}class Pn extends z{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadPhotos");const e=En("photo","AutoDownloadPhotosTitle");this.scrollable.append(e.container)}}class kn extends z{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadFiles");const e=Object(lt.a)(e=>{M.c.setByKey("settings.autoDownloadNew.file_size_max",e)},200,!1,!0),t=En("file","AutoDownloadFilesTitle"),s=a.a.settings.autoDownloadNew.file_size_max,i=Math.sqrt(Math.sqrt((s-524288)/20447232)),n=new T.c.IntlElement({key:"AutodownloadSizeLimitUpTo",args:[Ee(s)]}),o=new pn("AutoDownloadMaxFileSize",.01,i,0,1,!1);o.onChange=t=>{const s=20447232*Math.pow(t,4)+524288|0;n.compareAndUpdate({args:[Ee(s)]}),e(s)},o.valueContainer.append(n.element),t.content.append(o.container),this.scrollable.append(t.container)}}class Tn extends z{init(){this.header.classList.add("with-border"),this.setTitle("AutoDownloadVideos");const e=En("video","AutoDownloadVideosTitle");this.scrollable.append(e.container)}}var xn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const An={contacts:"AutoDownloadContacts",private:"AutoDownloadPm",groups:"AutoDownloadGroups",channels:"AutoDownloadChannels"};class On extends z{init(){return xn(this,void 0,void 0,(function*(){this.header.classList.add("with-border"),this.setTitle("DataSettings");{const e=new Kn({name:"AutomaticMediaDownload",caption:"AutoDownloadAudioInfo"}),t=yield M.c.getState(),s=new pt.a({text:"AutoDownloadMedia",name:"auto",checked:!t.settings.autoDownloadNew.pFlags.disabled,withRipple:!0}),i=()=>{Object(gt.a)([h],Object(ge.a)(t.settings.autoDownload,M.b.settings.autoDownload)&&Object(ge.a)(t.settings.autoDownloadNew,M.b.settings.autoDownloadNew))},n=()=>{this.setAutoDownloadSubtitle(r,t.settings.autoDownload.photo),this.setAutoDownloadSubtitle(c,t.settings.autoDownload.video),this.setAutoDownloadSubtitle(d,t.settings.autoDownload.file,t.settings.autoDownloadNew.file_size_max)},o=e=>{const t=new e(this.slider,!0);t.open(),this.listenerSetter.add(t.eventListener)("destroy",()=>{n(),i()},{once:!0})},r=new Ze({titleLangKey:"AutoDownloadPhotos",subtitle:"",clickable:()=>{o(Pn)}}),c=new Ze({titleLangKey:"AutoDownloadVideos",subtitle:"",clickable:()=>{o(Tn)}}),d=new Ze({titleLangKey:"AutoDownloadFiles",subtitle:"",clickable:()=>{o(kn)}}),h=Object(B.a)("btn-primary btn-transparent primary",{icon:"delete",text:"ResetAutomaticMediaDownload"});Object(l.b)(h,()=>{Mn({titleLangKey:"ResetAutomaticMediaDownloadAlertTitle",descriptionLangKey:"ResetAutomaticMediaDownloadAlert",button:{langKey:"Reset"}}).then(()=>{a.a.settings.autoDownloadNew=Object(ue.a)(M.b.settings.autoDownloadNew),a.a.settings.autoDownload=Object(ue.a)(M.b.settings.autoDownload),M.c.pushToState("settings",a.a.settings),a.a.dispatchEvent("settings_updated",{key:"settings",value:a.a.settings}),n(),s.checked=!t.settings.autoDownloadNew.pFlags.disabled})});const p=()=>{const e=!s.checked,t=a.a.settings;e?t.autoDownloadNew.pFlags.disabled=!0:delete t.autoDownloadNew.pFlags.disabled,[r,c,d].forEach(t=>{t.container.classList.toggle("is-disabled",e)}),M.c.pushToState("settings",t),a.a.dispatchEvent("settings_updated",{key:"settings",value:t}),i()};s.input.addEventListener("change",p),p(),n(),e.content.append(s.label,r.container,c.container,d.container,h),this.scrollable.append(e.container)}{const e=new Kn({name:"AutoplayMedia"}),t=new pt.a({text:"AutoplayGIF",name:"gifs",stateKey:"settings.autoPlay.gifs",withRipple:!0}),s=new pt.a({text:"AutoplayVideo",name:"videos",stateKey:"settings.autoPlay.videos",withRipple:!0});e.content.append(t.label,s.label),this.scrollable.append(e.container)}}))}setAutoDownloadSubtitle(e,t,s){let i,n=[];const a=Object.keys(t),o=a.map(e=>t[e]?An[e]:void 0).filter(Boolean);if(o.length&&0!==s){const e=o.length===a.length;if(void 0!==s?(i=e?"AutoDownloadUpToOnAllChats":"AutoDownloadOnUpToFor",n.push(Ee(s))):i=e?"AutoDownloadOnAllChats":"AutoDownloadOnFor",!e){const e=document.createElement("span");e.append(...Object(T.f)(o.map(e=>Object(T.d)(e)),!0,!1)),n.push(e)}}else i="AutoDownloadOff";Object(k.a)(e.subtitle,Object(T.d)(i,n))}}var jn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class _n extends H{constructor(){super(...arguments),this.buttons={}}init(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=bi({},"bottom-left",[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{new ut("logout",{titleLangKey:"LogOut",descriptionLangKey:"LogOut.Description",buttons:[{langKey:"LogOut",callback:()=>{ct.a.logOut()},isDanger:!0}]}).show()}}]);this.buttons.edit=N("edit"),this.header.append(this.buttons.edit,e),this.profile=new Jt(this.scrollable,this.listenerSetter,!1),this.profile.init(),this.profile.setPeer(a.a.myId),this.profile.fillProfileElements();const t=Object(B.a)("btn-circle btn-corner z-depth-1 profile-change-avatar",{icon:"cameraadd"});t.addEventListener("click",()=>{const e=document.createElement("canvas");(new W.a).open(e,e=>{e().then(e=>n.default.uploadProfilePhoto(e))})}),this.profile.element.lastElementChild.firstElementChild.append(t);const s=()=>{var e;const s=E.a.getSelf();t.classList.toggle("hide","userProfilePhoto"!==(null===(e=s.photo)||void 0===e?void 0:e._))};s(),this.listenerSetter.add(a.a)("avatar_update",e=>{a.a.myId===e&&s()});const i=document.createElement("div");i.classList.add("profile-buttons");const o=[["unmute","AccountSettings.Notifications",Cn],["data","DataSettings",On],["lock","AccountSettings.PrivacyAndSecurity",Gi],["settings","Telegram.GeneralSettingsViewController",un],["folder","AccountSettings.Filters",Sn]].map(([e,t,s])=>new Ze({titleLangKey:t,icon:e,clickable:()=>{new s(this.slider,!0).open()}}));o.push(this.devicesRow=new Ze({titleLangKey:"Devices",titleRightSecondary:" ",icon:"activesessions",clickable:()=>jn(this,void 0,void 0,(function*(){this.authorizations||(yield this.updateActiveSessions());const e=new Hi(this.slider);e.authorizations=this.authorizations,e.eventListener.addEventListener("destroy",()=>{this.authorizations=void 0,this.updateActiveSessions(!0)},{once:!0}),e.open()}))}),this.languageRow=new Ze({titleLangKey:"AccountSettings.Language",titleRightSecondary:Object(T.d)("LanguageName"),icon:"language",clickable:()=>{new In(this.slider).open()}})),i.append(...o.map(e=>e.container));const r=new Kn;r.content.append(i),this.scrollable.append(this.profile.element,r.container),this.buttons.edit.addEventListener("click",()=>{new mn(this.slider).open()}),oe.a.loadLottieWorkers(),this.updateActiveSessions()}getAuthorizations(e){if(this.getAuthorizationsPromise&&!e)return this.getAuthorizationsPromise;const t=this.getAuthorizationsPromise=ct.a.invokeApi("account.getAuthorizations").finally(()=>{this.getAuthorizationsPromise===t&&(this.getAuthorizationsPromise=void 0)});return t}updateActiveSessions(e){return this.getAuthorizations(e).then(e=>{this.authorizations=e.authorizations,this.devicesRow.titleRight.textContent=""+this.authorizations.length})}}class Fn extends H{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new q(e=>{this.uploadAvatar=e});const e=new Kn({caption:"Channel.DescriptionHolderDescrpiton"}),t=document.createElement("div");t.classList.add("input-wrapper"),this.channelNameInputField=new O.b({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new O.b({label:"DescriptionOptionalPlaceholder",maxLength:255}),t.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const s=()=>{this.nextBtn.classList.toggle("is-visible",!!this.channelNameInputField.value.length&&!this.channelNameInputField.input.classList.contains("error")&&!this.channelDescriptionInputField.input.classList.contains("error"))};this.channelNameInputField.input.addEventListener("input",s),this.channelDescriptionInputField.input.addEventListener("input",s),this.nextBtn=Q({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.channelNameInputField.value,t=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,G.a.createChannel({title:e,about:t,broadcast:!0}).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{G.a.editPhoto(e,t)}),$n.removeTabFromHistory(this),new Ut(this.slider).open({type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:t=>G.a.inviteToChannel(e,t)})})}),this.content.append(this.nextBtn),e.content.append(this.avatarEdit.container,t),this.scrollable.append(e.container)}onCloseAfterTimeout(){return this.avatarEdit.clear(),this.uploadAvatar=null,this.channelNameInputField.value="",this.channelDescriptionInputField.value="",this.nextBtn.disabled=!1,super.onCloseAfterTimeout()}}var Dn=s(154);class Rn extends ht.b{constructor(){super("popup-create-contact popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Add"}),Object(T.b)(this.title,"AddContactTitle"),Object(l.b)(this.btnConfirm,()=>{const e=E.a.importContact(s.value,i.value,n.value);e.then(()=>{this.hide()},e=>{"NO_USER"===e.type&&(rt({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),c.disabled=!1)}),c.lockWithPromise(e)},{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const s=new O.b({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0}),i=new O.b({label:"LastName",name:"create-contact-lastname",maxLength:70}),n=new Dn.a({required:!0});e.push(s,i,n);const a=()=>{const e=s.value+" "+i.value;c.avatarElem.peerTitle=e,c.avatarElem.update()};this.listenerSetter.add(s.input)("input",a),this.listenerSetter.add(i.input)("input",a),n.validate=()=>!!n.value.match(/\d/);const o=E.a.getSelf(),r=Object(qs.a)(o.phone);r.code&&(n.value="+"+r.code.country_code);const c=new Xe({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100});t.append(s.container,i.container,c.avatarElem),this.container.append(t,n.container),this.show()}}class Bn extends H{init(){this.container.id="contacts-container";const e=Q({icon:"add",className:"is-visible"});this.content.append(e),Object(l.b)(e,()=>{new Rn},{listenerSetter:this.listenerSetter}),this.inputSearch=new j("Search",e=>{this.openContacts(e)}),this.listenerSetter.add(a.a)("contacts_update",e=>{const t=E.a.isContact(e),s=e.toPeerId();t?this.sortedUserList.add(s):this.sortedUserList.delete(s)}),this.title.replaceWith(this.inputSearch.container),this.middleware=Object(Rs.a)()}createList(){const e=new Vs,t=e.list;return t.id="contacts",t.classList.add("contacts-container"),_c.setListClickListener(t,()=>{this.close()},void 0,!0),e}onClose(){this.middleware.clean()}onOpenAfterTimeout(){!ae.e&&Ei(!0)&&this.inputSearch.input.focus()}openContacts(e){this.init&&(this.init(),this.init=null),this.middleware.clean();const t=this.middleware.get();this.scrollable.onScrolledBottom=null,this.scrollable.container.textContent="",E.a.getContactsPeerIds(e,void 0,"online").then(e=>{if(!t())return;const s=this.sortedUserList=this.createList();let i=()=>{const t=St.a.height/72*1.25|0;e.splice(0,t).forEach(e=>{s.add(e)}),e.length||(i=void 0,this.scrollable.onScrolledBottom=null)};i(),this.scrollable.onScrolledBottom=()=>{i?i():this.scrollable.onScrolledBottom=null},Object(k.a)(this.scrollable.container,s.list)})}open(){return this.openContacts(),super.open()}}class Nn extends H{init(){if(this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),!_c.sortedLists[Nn.filterId]){const e=_c.createChatList();_c.generateScrollable(e,Nn.filterId).container.append(e),_c.setListClickListener(e,null,!0)}const e=_c.scrollables[Nn.filterId];this.scrollable.container.replaceWith(e.container),this.scrollable=e}onOpen(){this.init&&(this.init(),this.init=null),this.wasFilterId=_c.filterId,_c.setFilterId(Nn.filterId),_c.onTabChange()}onOpenAfterTimeout(){_c.sortedLists[this.wasFilterId].clear()}onClose(){_c.setFilterId(this.wasFilterId),_c.onTabChange()}onCloseAfterTimeout(){return _c.sortedLists[Nn.filterId].clear(),super.onCloseAfterTimeout()}}Nn.filterId=1;class Un extends H{constructor(){super(...arguments),this.isLocationWatched=!1}init(){this.container.classList.add("people-nearby-container"),this.setTitle("PeopleNearby"),this.errorCategory=document.createElement("div"),this.errorCategory.classList.add("text","hide","nearby-error"),this.retryBtn=Q({icon:"check"});const e=gs.a.getAnimatedEmojiSticker("🧭"),t=document.createElement("div");t.classList.add("sticker-container"),e?xs({doc:e,div:t,loop:!1,play:!0,width:86,height:86,emoji:"🧭",needUpscale:!0}).then(()=>{}):t.classList.add("media-sticker-wrapper");const s=document.createElement("div");s.classList.add("caption"),Object(T.b)(s,"PeopleNearbyInfo2"),this.locatedPeers=new Map;const i=()=>{const e=new Vs({avatarSize:42,createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onUpdate:e=>{const t=this.locatedPeers.get(e.id),s=[this.parseDistance(t.distance)];e.id.isUser()||s.push(n.default.getChatMembersString(e.id.toChatId())),e.dom.lastMessageSpan.textContent="",e.dom.lastMessageSpan.append(...Object(T.f)(s,!1))},getIndex:e=>2147483647-this.locatedPeers.get(e.id).distance});return _c.setListClickListener(e.list,void 0,void 0,!1),e},a=this.peopleSection=new qn({name:"PeopleNearbyHeader",sortedList:i()}),o=this.chatsSection=new qn({name:"ChatsNearbyHeader",sortedList:i()}),r=a.makeButton({text:"MakeMyselfVisible",icon:"location"}),c=a.makeButton({text:"StopShowingMe",icon:"location"}),d=o.makeButton({text:"NearbyCreateGroup",icon:"newgroup"});Object(l.b)(r,()=>{Mn({titleLangKey:"MakeMyselfVisibleTitle",descriptionLangKey:"MakeMyselfVisibleInfo",button:{langKey:"OK"}}).then(()=>{this.startWatching()})},{listenerSetter:this.listenerSetter}),Object(l.b)(c,()=>{this.stopWatching()},{listenerSetter:this.listenerSetter}),Object(l.b)(d,()=>{new $(this.slider).open([],!0)},{listenerSetter:this.listenerSetter}),r.classList.add("primary"),c.classList.add("danger"),d.classList.add("primary"),this.content.append(this.retryBtn),this.scrollable.append(t,s,a.container,o.container,this.errorCategory)}parseDistance(e){return"miles"===a.a.settings.distanceUnit?e>1609.34?Object(T.d)("MilesAway",[Math.round(e/1609)]):Object(T.d)("FootsAway",[Math.round(3.281*e)]):e>=1e3?Object(T.d)("KMetersAway2",[e/1e3]):Object(T.d)("MetersAway2",[e])}open(){const e=super.open();return e.then(()=>{this.retryBtn.classList.remove("is-visible"),navigator.geolocation.getCurrentPosition(e=>{this.latestLocationSaved={latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy},console.log(this.latestLocationSaved),E.a.getLocated(e.coords.latitude,e.coords.longitude,e.coords.accuracy).then(e=>{const t=e.updates[0].peers,s=t.sort((e,t)=>e.distance-t.distance),i=t.filter(e=>"peerChannel"==e.peer._).length,n=t.filter(e=>"peerChannel"!=e.peer._).length;null==s||s.forEach(e=>{const t=o.a.getPeerId(e.peer),s=t.isUser()?this.peopleSection:this.chatsSection;this.locatedPeers.set(t,e),s.sortedList.add(t)}),this.errorCategory.classList.toggle("hide",!(!n&&!i)),this.errorCategory.innerHTML="No groups or channels found around you."})},e=>{this.errorCategory.classList.remove("hide"),this.retryBtn.classList.add("is-visible"),this.retryBtn.addEventListener("click",this.open),e instanceof GeolocationPositionError?this.errorCategory.innerHTML="Location permission denied. Click below to retry.":this.errorCategory.innerHTML="An error has occurred. Please retry later clicking the button below."})}),e}startWatching(){this.latestLocationSaved&&!this.isLocationWatched&&(this.isLocationWatched=!0,ot("Your position is now being shared. Do not close the page or it will be suspended."),E.a.getLocated(this.latestLocationSaved.latitude,this.latestLocationSaved.longitude,this.latestLocationSaved.accuracy,!0,2147483647),navigator.geolocation.watchPosition(e=>{const t=e.coords.longitude!==this.latestLocationSaved.longitude,s=e.coords.latitude!==this.latestLocationSaved.latitude,i=this.calculateDistance(e.coords.latitude,e.coords.longitude,this.latestLocationSaved.latitude,this.latestLocationSaved.longitude)>100;(s||t)&&i&&(E.a.getLocated(e.coords.latitude,e.coords.longitude,e.coords.accuracy,!0,2147483647),this.latestLocationSaved={latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy})}))}stopWatching(){this.isLocationWatched&&(this.isLocationWatched=!1,ot("The sharing of your position has been stopped. You will no longer be visible to other users."),E.a.getLocated(0,0,0,!1,0))}calculateDistance(e,t,s,i){const n=.017453292519943295;return 12742*Math.asin(Math.sqrt(.5-Math.cos((s-e)*n)+Math.cos(e*n)*Math.cos(s*n)*(1-Math.cos((i-t)*n)/2)))}}var Hn=s(5),zn=s(6);function Vn(e,t=2){if(0===e)return"0";const s=t<0?0:t,i=Math.floor(Math.log(e)/Math.log(1e3));return parseFloat((e/Math.pow(1e3,i)).toFixed(s))+["","K","M","B","T"][i]}class Kn{constructor(e={}){const t=this.container=document.createElement("div");t.classList.add("sidebar-left-section-container");const s=this.innerContainer=document.createElement("div");if(s.classList.add("sidebar-left-section"),e.noShadow&&s.classList.add("no-shadow"),e.fakeGradientDelimiter)s.append(Wn()),s.classList.add("with-fake-delimiter");else if(e.noDelimiter)s.classList.add("no-delimiter");else{const e=document.createElement("hr");s.append(e)}const i=this.content=this.generateContentElement();if(e.name){const t=this.title=document.createElement("div");t.classList.add("sidebar-left-h2","sidebar-left-section-name"),Object(T.e)({element:t,key:e.name,args:e.nameArgs}),i.append(t)}if(t.append(s),e.caption){const s=this.caption=this.generateContentElement();s.classList.add("sidebar-left-section-caption"),t.append(s),!0!==e.caption&&Object(T.e)({element:s,key:e.caption})}}generateContentElement(){const e=document.createElement("div");return e.classList.add("sidebar-left-section-content"),this.innerContainer.append(e),e}}const Gn=(e,t,s)=>{const i=new Kn({name:t,caption:s});return e.append(i.container),i.content},Wn=()=>{const e=document.createElement("div");return e.classList.add("gradient-delimiter"),e};class qn extends Kn{constructor(e){super(e),this.sortedList=e.sortedList,this.content.append(this.sortedList.list)}makeButton(e){const t=Object(B.a)("folder-category-button btn btn-primary btn-transparent",e);return this.title?this.content.insertBefore(t,this.title.nextSibling):this.content.prepend(t),t}}const Qn=new class extends K{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={},this.inputSearch=new j("Search");const e=this.sidebarEl.querySelector(".item-main .sidebar-header");e.append(this.inputSearch.container);const t=()=>{new Bn(this).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const s={icon:"archive",text:"ArchivedChats",onClick:()=>{new Nn(this).open()},verify:()=>!!i.a.dialogsStorage.getFolderDialogs(1,!1).length||!i.a.dialogsStorage.isDialogsLoaded(1)},n=new pt.a({toggle:!0,checked:"night"===a.a.getTheme().name});n.input.addEventListener("change",()=>{a.a.settings.theme=n.input.checked?"night":"day",M.c.pushToState("settings",a.a.settings),a.a.dispatchEvent("theme_change")}),a.a.addEventListener("theme_change",()=>{n.setValueSilently("night"===a.a.getTheme().name)});const o=[{icon:"saved",text:"SavedMessages",onClick:()=>{setTimeout(()=>{nc.setPeer({peerId:nc.myId})},0)}},s,{icon:"user",text:"Contacts",onClick:t},dn?{icon:"group",text:"PeopleNearby",onClick:()=>{new Un(this).open()}}:void 0,{icon:"settings",text:"Settings",onClick:()=>{new _n(this).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:n},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new pt.a({toggle:!0,checked:!0,stateKey:"settings.animationsEnabled"})},{icon:"help",text:"TelegramFeatures",onClick:()=>{const e=T.c.format("TelegramFeaturesUrl",!0);nc.openUrl(e)}},{icon:"bug",text:"ReportBug",onClick:()=>{const e=document.createElement("a");e.target="_blank",e.href="https://bugs.telegram.org/?tag_ids=40&sort=time",document.body.append(e),e.click(),setTimeout(()=>{e.remove()},0)}},{icon:"char z",text:"ChatList.Menu.SwitchTo.Z",onClick:()=>{Promise.all([zn.a.set({kz_version:"Z"}),zn.a.delete("tgme_sync")]).then(()=>{location.href="https://web.telegram.org/z/"})},verify:()=>Hn.a.isMainDomain},{icon:"char w",text:"ChatList.Menu.SwitchTo.Webogram",onClick:()=>{zn.a.delete("tgme_sync").then(()=>{location.href="https://web.telegram.org/?legacy=1"})},verify:()=>Hn.a.isMainDomain}].filter(Boolean);this.toolsBtn=bi({},"bottom-right",o,e=>{o.forEach(e=>{e.verify&&e.element.classList.toggle("hide",!e.verify())})}),this.toolsBtn.classList.remove("tgico-more"),this.toolsBtn.classList.add("sidebar-tools-button","is-visible"),this.backBtn.parentElement.insertBefore(this.toolsBtn,this.backBtn);const r=this.toolsBtn.querySelector(".btn-menu"),c=document.createElement("a");c.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",c.target="_blank",c.rel="noopener noreferrer",c.classList.add("btn-menu-footer"),c.addEventListener(l.a,e=>{e.stopPropagation(),Object(ee.c)()});const d=document.createElement("span");d.classList.add("btn-menu-footer-text"),d.innerHTML="Telegram Web"+Hn.a.suffix+" "+Hn.a.versionFull,c.append(d),r.classList.add("has-footer"),r.append(c),this.newBtnMenu=bi({},"top-left",[{icon:"newchannel",text:"NewChannel",onClick:()=>{new Fn(this).open()}},{icon:"newgroup",text:"NewGroup",onClick:()=>{new Ut(this).open({type:"chat",skippable:!1,takeOut:e=>{new $(this).open(e)},title:"GroupAddMembers",placeholder:"SendMessageTo"})}},{icon:"newprivate",text:"NewPrivateChat",onClick:t}]),this.newBtnMenu.className="btn-circle rp btn-corner z-depth-1 btn-menu-toggle animated-button-icon",this.newBtnMenu.insertAdjacentHTML("afterbegin",'\n <span class="tgico tgico-newchat_filled"></span>\n <span class="tgico tgico-close"></span>\n '),this.newBtnMenu.id="new-menu",e.nextElementSibling.append(this.newBtnMenu),this.updateBtn=document.createElement("div"),this.updateBtn.className="btn-circle rp btn-corner z-depth-1 btn-update is-hidden",Object(te.a)(this.updateBtn),this.updateBtn.append(Object(T.d)("Update")),Object(l.b)(this.updateBtn,()=>{location.reload()}),e.nextElementSibling.append(this.updateBtn),this.inputSearch.input.addEventListener("focus",()=>this.initSearch(),{once:!0}),this.archivedCount=document.createElement("span"),this.archivedCount.className="archived-count badge badge-24 badge-gray",s.element.append(this.archivedCount),a.a.addEventListener("folder_unread",e=>{if(1===e.id){const t=e.unreadDialogsCount;this.archivedCount.innerText=""+Vn(t,1),this.archivedCount.classList.toggle("hide",!t)}}),E.a.getTopPeers("correspondents");const h={type:"global-search-focus",onPop:()=>(setTimeout(()=>{this.inputSearch.input.focus()},0),!1),noHistory:!0};F.a.pushItem(h),M.c.getState().then(e=>{const t=e.recentSearch||[];for(let e=0,s=t.length;e<s;++e)M.c.requestPeer(t[e],"recentSearch");const s=setInterval(()=>{fetch("version",{cache:"no-cache"}).then(e=>200===e.status&&e.ok&&e.text()||Promise.reject()).then(e=>{e!==Hn.a.versionFull&&(this.hasUpdate=!0,clearInterval(s),this.newBtnMenu.classList.contains("is-hidden")||this.updateBtn.classList.remove("is-hidden"))}).catch(Se.a)},18e5)})}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new P.b(e),s=()=>{this.backBtn.click()};this.searchGroups={contacts:new x("SearchAllChatsShort","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new x("GlobalSearch","contacts",void 0,void 0,void 0,void 0,s),messages:new x("SearchMessages","messages"),people:new x(!1,"contacts",!0,"search-group-people",!0,!1,s),recent:new x("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const n=this.searchSuper=new ui({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"FilterChats",type:"chats"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:t,searchGroups:this.searchGroups,asChatList:!0,hideEmptyTabs:!1,showSender:!0});e.prepend(n.nav.parentElement.parentElement),t.container.append(n.container);n.setQuery({peerId:"".toPeerId(),folderId:0}),n.selectTab(0),n.load(!0);let a=[],o="".toPeerId(),r=0,l=0;const c=()=>{this.inputSearch.container.classList.toggle("is-picked-twice",2===a.length),this.inputSearch.container.classList.toggle("is-picked",!!a.length),a.length?this.inputSearch.input.style.setProperty("--paddingLeft",a[a.length-1].getBoundingClientRect().right-this.inputSearch.input.getBoundingClientRect().left+"px"):this.inputSearch.input.style.removeProperty("--paddingLeft")},d=document.createElement("div");d.classList.add("search-helper"),d.addEventListener("click",e=>{const t=Object(Ce.a)(e.target,"selector-user");if(!t)return;const s=t.dataset.key;if(0===s.indexOf("date_")){const[e,t,i]=s.split("_");r=+t,l=+i}else o=s.toPeerId();t.addEventListener("click",()=>{p(t)}),this.inputSearch.container.append(t),this.inputSearch.onChange(this.inputSearch.value=""),a.push(t),c()}),n.nav.parentElement.append(d);const h=(e,t)=>{const s=document.createElement("div");s.classList.add("selector-user");const i=new fc;return i.classList.add("selector-user-avatar","tgico","avatar-30"),i.isDialog=!0,s.dataset.key=""+e,e.isPeerId()?(void 0===t&&(t=new wt.a({peerId:e.toPeerId()}).element),i.updateWithOptions({peerId:e})):i.classList.add("tgico-calendarfilter"),t&&("string"==typeof t?s.innerHTML=t:(Object(k.a)(s,t),s.append(t))),s.insertAdjacentElement("afterbegin",i),s},p=e=>{0===e.dataset.key.indexOf("date_")?r=l=0:o="".toPeerId(),e.remove(),Object(V.a)(a,e),setTimeout(()=>{c(),this.inputSearch.onChange(this.inputSearch.value)},0)};this.inputSearch.onClear=()=>{a.forEach(e=>{p(e)})},this.inputSearch.onChange=e=>{if(n.cleanupHTML(),n.setQuery({peerId:o,folderId:o?void 0:0,query:e,minDate:r,maxDate:l}),n.load(!0),d.innerHTML="",n.nav.classList.remove("hide"),!o&&e.trim()){const t=n.middleware.get();Promise.all([i.a.getConversations(e).promise.then(({dialogs:e})=>e.map(e=>e.peerId)),E.a.getContactsPeerIds(e,!0)]).then(e=>{if(!t())return;new Set(e[0].concat(e[1])).forEach(e=>{d.append(h(e))}),n.nav.classList.toggle("hide",!!d.innerHTML)})}if(!r&&e.trim()){const t=[];Object(ne.b)(e,t),t.forEach(e=>{d.append(h("date_"+e.minDate+"_"+e.maxDate,e.title))}),n.nav.classList.toggle("hide",!!d.innerHTML)}},n.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",e=>{const t=Object(bt.a)(e.target,"LI");if(!t)return;const s=Object(Ce.a)(t,"search-group");if(!s||s.classList.contains("search-group-recent")||s.classList.contains("search-group-people"))return;const i=t.getAttribute("data-peer-id").toPeerId();M.c.getState().then(e=>{const t=e.recentSearch||[];if(t[0]!==i){Object(V.a)(t,i),t.unshift(i),t.length>20&&(t.length=20),M.c.pushToState("recentSearch",t);for(const e of t)M.c.requestPeer(e,"recentSearch")}})},{capture:!0});let u=document.createElement("div");u.classList.add("search-group-scrollable"),u.append(this.searchGroups.people.list),this.searchGroups.people.container.append(u);new P.a(u);let g,m=!0;const b=Object(_.a)(e.parentElement,"zoom-fade",150,e=>{g&&clearTimeout(g),0!==e||m||(n.selectTab(0,!1),this.inputSearch.onClearClick(),g=window.setTimeout(()=>{g=0,this.newBtnMenu.classList.remove("is-hidden"),this.hasUpdate&&this.updateBtn.classList.remove("is-hidden")},150)),m=!1});b(0);const v=()=>{this.toolsBtn.classList.remove("is-visible"),this.backBtn.classList.add("is-visible"),this.newBtnMenu.classList.add("is-hidden"),this.updateBtn.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0);ae.f||F.a.findItemByType("global-search")||F.a.pushItem({onPop:()=>{s()},type:"global-search"}),b(1)};this.inputSearch.input.addEventListener("focus",v),v(),this.backBtn.addEventListener("click",e=>{this.toolsBtn.classList.add("is-visible"),this.backBtn.classList.remove("is-visible"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),F.a.removeByType("global-search"),b(0)});const f=N("close");this.searchGroups.recent.nameEl.append(f),f.addEventListener("click",()=>{Mn({descriptionLangKey:"Search.Confirm.ClearHistory",button:{langKey:"ClearButton",isDanger:!0}}).then(()=>{M.c.getState().then(e=>{this.searchGroups.recent.clear();const t=e.recentSearch||[];for(const e of t)M.c.releaseSinglePeer(e,"recentSearch");t.length=0,M.c.pushToState("recentSearch",t)})})})}};le.a.appSidebarLeft=Qn;var $n=Qn;class Yn{constructor(e){this.chat=e,this.bubbles=[],this.detailsMap=new Map,this.groups=[],this.newGroupDiff=121}removeBubble(e){const t=this.detailsMap.get(e);t&&(t.group.length&&(Object(Lt.a)(t.group,t=>t.bubble===e),t.group.length?this.updateGroup(t.group):Object(V.a)(this.groups,t.group)),this.detailsMap.delete(e))}changeBubbleMid(e,t){const s=this.detailsMap.get(e);s&&(s.mid=t)}addBubble(e,t,s){const i=t.date,n=t.mid;let o,r=t.viaBotId||t.fromId;r===a.a.myId&&t.peerId===a.a.myId&&t.fwdFromId===r&&(r=r.toPeerId(!0)),this.removeBubble(e);const l={bubble:e,mid:n,timestamp:i};if(this.bubbles.length){let e,t=-1;for(let e=0;e<this.bubbles.length;++e){const s=this.bubbles[e],a=Math.abs(s.timestamp-i);if(s.fromId===r&&a<=this.newGroupDiff){if(t=e,"scheduled"===this.chat.type)break}else t=-1;if("scheduled"!==this.chat.type&&n>s.mid)break}if(-1!==t&&(e=this.bubbles[t]),e){o=e.group;let t=0,s=0;for(;t<o.length;++t){const e=o[t].timestamp,a=o[t].mid;if(i<e)break;if(i===e&&(s=a),s&&n<s)break}o.splice(t,0,l)}else this.groups.push(o=[l])}else this.groups.push(o=[l]);const c={timestamp:i,fromId:r,mid:t.mid,group:o};let d=0;for(;d<this.bubbles.length&&!(this.bubbles[d].mid<n);++d);this.bubbles.splice(d,0,{timestamp:i,fromId:r,mid:t.mid,group:o}),this.updateGroup(o),this.detailsMap.set(e,c)}updateGroup(e){if(!e.length)return;const t=e[0].bubble;if(1===e.length)return void t.classList.add("is-group-first","is-group-last");t.classList.remove("is-group-last"),t.classList.add("is-group-first");const s=e.length-1;for(let t=1;t<s;++t){e[t].bubble.classList.remove("is-group-last","is-group-first")}const i=e[e.length-1].bubble;i.classList.remove("is-group-first"),i.classList.add("is-group-last")}updateGroupByMessageId(e){const t=this.bubbles.find(t=>t.mid===e);t&&this.updateGroup(t.group)}cleanup(){this.bubbles=[],this.groups=[],this.detailsMap.clear()}}class Xn extends ht.b{constructor(e,t,s={}){if(super("popup-date-picker",s.noButtons?[]:[{langKey:"JumpToDate",callback:()=>{this.onPick&&this.onPick(this.selectedDate.getTime()/1e3|0)}},{langKey:"Cancel",isCancel:!0}],Object.assign({body:!0,overlayClosable:!0},s)),this.onPick=t,this.options=s,this.onPrevClick=e=>{this.selectedMonth.setMonth(this.selectedMonth.getMonth()-1),this.setMonth(),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.nextBtn.removeAttribute("disabled")},this.onNextClick=e=>{this.selectedMonth.setMonth(this.selectedMonth.getMonth()+1),this.setMonth(),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),this.prevBtn.removeAttribute("disabled")},this.onDateClick=e=>{const t=e.target;if(!t.dataset.timestamp)return;if(this.selectedEl){if(this.selectedEl===t)return;this.selectedEl.classList.remove("active")}this.selectedEl=t,t.classList.add("active");const s=+t.dataset.timestamp;this.selectedDate=new Date(s),this.setTitle(),this.setTimeTitle()},this.minDate=s.minDate||new Date("2013-08-01T00:00:00"),e<this.minDate&&e.setFullYear(this.minDate.getFullYear(),this.minDate.getMonth(),this.minDate.getDate()),this.controlsDiv=document.createElement("div"),this.controlsDiv.classList.add("date-picker-controls"),this.prevBtn=document.createElement("button"),this.prevBtn.classList.add("btn-icon","tgico-down","date-picker-prev"),Object(l.b)(this.prevBtn,this.onPrevClick,{listenerSetter:this.listenerSetter}),this.nextBtn=document.createElement("button"),this.nextBtn.classList.add("btn-icon","tgico-down","date-picker-next"),Object(l.b)(this.nextBtn,this.onNextClick,{listenerSetter:this.listenerSetter}),this.monthTitle=document.createElement("div"),this.monthTitle.classList.add("date-picker-month-title"),this.controlsDiv.append(this.prevBtn,this.monthTitle,this.nextBtn),this.monthsContainer=document.createElement("div"),this.monthsContainer.classList.add("date-picker-months"),Object(l.b)(this.monthsContainer,this.onDateClick,{listenerSetter:this.listenerSetter}),this.body.append(this.controlsDiv,this.monthsContainer),s.withTime){this.timeDiv=document.createElement("div"),this.timeDiv.classList.add("date-picker-time");const t=document.createElement("div");t.classList.add("date-picker-time-delimiter"),t.append(":");const s=(e,t,s,i)=>{const n=""+e;this.listenerSetter.add(t.input)("input",a=>{let o=t.value.replace(/\D/g,"");o.length>2?o=o.slice(0,2):(1===o.length&&+o[0]>+n[0]||2===o.length&&+o>e)&&(2===o.length&&i&&i(+o[1]),o="0"+o[0]),t.setValueSilently(o),s(o.length)})};this.hoursInputField=new O.b({plainText:!0}),this.minutesInputField=new O.b({plainText:!0}),s(23,this.hoursInputField,e=>{2===e&&this.minutesInputField.input.focus(),this.setTimeTitle()},e=>{this.minutesInputField.value=(e+this.minutesInputField.value).slice(0,2)}),s(59,this.minutesInputField,e=>{e||this.hoursInputField.input.focus(),this.setTimeTitle()}),this.selectedDate=e,e.setMinutes(e.getMinutes()+10),this.hoursInputField.setValueSilently(("0"+e.getHours()).slice(-2)),this.minutesInputField.setValueSilently(("0"+e.getMinutes()).slice(-2)),e.setHours(0,0,0,0),this.timeDiv.append(this.hoursInputField.container,t,this.minutesInputField.container),Object(l.b)(this.btnConfirm,()=>{this.onPick&&(this.selectedDate.setHours(+this.hoursInputField.value||0,+this.minutesInputField.value||0,0,0),this.onPick(this.selectedDate.getTime()/1e3|0)),this.hide()},{listenerSetter:this.listenerSetter}),this.body.append(this.timeDiv),this.prevBtn.classList.add("primary"),this.nextBtn.classList.add("primary")}const i=document.createElement("div");i.classList.add("popup-centerer"),i.append(this.container),this.element.append(i),e.setHours(0,0,0,0),this.selectedDate=e,this.maxDate=s.maxDate||new Date,this.maxDate.setHours(0,0,0,0),this.selectedMonth=new Date(this.selectedDate),this.selectedMonth.setDate(1),this.maxMonth=new Date(this.maxDate),this.maxMonth.setDate(1),this.minMonth=new Date(this.minDate),this.minMonth.setHours(0,0,0,0),this.minMonth.setDate(1),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),s.noTitle&&(this.setTitle=()=>{}),this.setTimeTitle(),this.setTitle(),this.setMonth()}setTimeTitle(){if(this.btnConfirm&&this.selectedDate){let e,t=[];const s=new Date;s.setHours(0,0,0,0);const i={minute:"2-digit",hour:"2-digit"},n=new Date(this.selectedDate.getTime());if(n.setHours(+this.hoursInputField.value,+this.minutesInputField.value),this.selectedDate.getTime()===s.getTime())e="Schedule.SendToday";else{e="Schedule.SendDate";const i={month:"short",day:"numeric"};n.getFullYear()!==s.getFullYear()&&(i.year="numeric"),t.push(new T.c.IntlDateElement({date:n,options:i}).element)}t.push(new T.c.IntlDateElement({date:n,options:i}).element),this.btnConfirm.firstChild.replaceWith(Object(T.d)(e,t))}}setTitle(){this.title.textContent="",this.title.append(new T.c.IntlDateElement({date:this.selectedDate,options:{day:"numeric",month:"long",weekday:"short"}}).element)}renderElement(e,t=""){const s=document.createElement("button");return s.classList.add("btn-icon","date-picker-month-date"),e&&s.setAttribute("disabled","true"),t&&s.append(t),s}setMonth(){const e=new Date(this.selectedMonth),t={year:"numeric",month:this.timeDiv&&b.b.isMobile?"short":"long"};this.monthTitle.textContent="",this.monthTitle.append(new T.c.IntlDateElement({date:e,options:t}).element),this.month&&this.month.remove(),this.month=document.createElement("div"),this.month.classList.add("date-picker-month");const s=new Date,i=s.getDay();1!==i&&s.setHours(-24*(i-1));for(let e=0;e<7;++e){const e=this.renderElement(!0,new T.c.IntlDateElement({date:s,options:{weekday:"narrow"}}).element);e.classList.remove("date-picker-month-date"),e.classList.add("date-picker-month-day"),this.month.append(e),s.setDate(s.getDate()+1)}let n=e.getDay()-1;-1===n&&(n=6);const a=new Date(e.getTime());a.setDate(a.getDate()-n-1);for(let e=0;e<n;++e)this.options.showOverflowMonths?(a.setDate(a.getDate()+1),this.month.append(this.renderElement(!0,""+a.getDate()))):this.month.append(this.renderElement(!0));do{const t=e.getDate(),s=this.renderElement(e>this.maxDate||e<this.minDate,""+t);s.dataset.timestamp=""+e.getTime(),e.getTime()===this.selectedDate.getTime()&&(this.selectedEl=s,s.classList.add("active")),this.month.append(s),e.setDate(t+1)}while(1!==e.getDate());const o=this.month.childElementCount%7;if(this.options.showOverflowMonths&&o)for(let t=o;t<7;++t)this.month.append(this.renderElement(!0,""+e.getDate())),e.setDate(e.getDate()+1);const r=Math.ceil(this.month.childElementCount/7);this.container.dataset.lines=""+r,this.monthsContainer.append(this.month)}}class Jn{constructor(e,t){this.container=e,this.handler=t,this.observeHeaders(),this.observeElements()}observeHeaders(){this.headersObserver=new IntersectionObserver(e=>{for(const t of e){const e=t.boundingClientRect,s=t.target.parentElement,i=t.rootBounds;e.bottom<i.top&&this.handler(!0,s),e.bottom>=i.top&&e.bottom<i.bottom&&this.handler(!1,s)}},{threshold:0,root:this.container})}observeElements(){this.elementsObserver=new IntersectionObserver(e=>{const t=e.filter(e=>e.boundingClientRect.top<e.rootBounds.top).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!t)return;const s=t.isIntersecting?t.target:t.target.nextElementSibling;this.handler(!0,s)},{root:this.container})}addSentinel(e,t){const s=document.createElement("div");return s.classList.add("sticky_sentinel",t),e.appendChild(s)}observeStickyHeaderChanges(e){const t=this.addSentinel(e,"sticky_sentinel--top");this.headersObserver.observe(t),this.elementsObserver.observe(e)}disconnect(){this.headersObserver.disconnect(),this.elementsObserver.disconnect()}unobserve(e,t){this.elementsObserver.unobserve(e),this.headersObserver.unobserve(t)}}class Zn extends HTMLElement{constructor(){super(),this.classList.add("reaction")}get reactionCount(){return this._reactionCount}set reactionCount(e){this._reactionCount=e}get count(){return this.reactionCount.count}init(e){this.type=e,this.classList.add("reaction-"+e)}setCanRenderAvatars(e){this.canRenderAvatars=e}render(e){const t=!!this.stickerContainer;t||(this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("reaction-sticker"),this.append(this.stickerContainer));const s=this.reactionCount;if(!e&&!t){const e=jt.a.getReaction(s.reaction);Object(zt.a)(e,e=>{var t;e.center_icon||this.stickerContainer.classList.add("is-static"),e.pFlags.inactive&&this.classList.add("is-inactive");const s="inline"===this.type?14:22,i=this.wrapStickerPromise=xs({div:this.stickerContainer,doc:null!==(t=e.center_icon)&&void 0!==t?t:e.static_icon,width:s,height:s,static:!0}).finally(()=>{this.wrapStickerPromise===i&&(this.wrapStickerPromise=void 0)})})}}renderCounter(){var e;const t=this.reactionCount,s="inline"===this.type?2:4;if(t.count>=s||"block"===this.type&&!this.canRenderAvatars){this.counter||(this.counter=document.createElement("inline"===this.type?"i":"span"),this.counter.classList.add("reaction-counter"));const e=Vn(t.count);this.counter.textContent!==e&&(this.counter.textContent=e),this.counter.parentElement||this.append(this.counter)}else(null===(e=this.counter)||void 0===e?void 0:e.parentElement)&&(this.counter.remove(),this.counter=void 0)}renderAvatars(e){"inline"!==this.type&&(this.reactionCount.count>=4||!this.canRenderAvatars?this.stackedAvatars&&(this.stackedAvatars.container.remove(),this.stackedAvatars=void 0):(this.stackedAvatars||(this.stackedAvatars=new ns({avatarSize:24}),this.append(this.stackedAvatars.container)),this.stackedAvatars.render(e.map(e=>o.a.getPeerId(e.peer_id)))))}setIsChosen(e=!!this.reactionCount.pFlags.chosen){if("inline"===this.type)return;(this.classList.contains("is-chosen")&&!this.classList.contains("backwards"))!==e&&Object(is.a)(this,"is-chosen",e,this.isConnected?300:0)}fireAroundAnimation(){Object(zt.a)(jt.a.getReaction(this.reactionCount.reaction),e=>{const t="inline"===this.type?28:40,s=document.createElement("div");s.classList.add("reaction-sticker-activate"),Promise.all([xs({div:s,doc:e.center_icon,width:t,height:t,withThumb:!1,needUpscale:!0,play:!1,skipRatio:1,group:"none",needFadeIn:!1}),Ts({doc:e.around_animation,size:80,target:this.stickerContainer,side:"center",skipRatio:1,play:!1}).stickerPromise]).then(([e,t])=>{const i=()=>{Object(Le.b)(()=>{e.remove(),s.remove(),this.stickerContainer.classList.remove("has-animation")})};e.addEventListener("enterFrame",t=>{t===e.maxFrame&&(this.wrapStickerPromise?this.wrapStickerPromise.then(()=>{setTimeout(i,1e3)}):i())}),e.addEventListener("firstFrame",()=>{this.stickerContainer.append(s),this.stickerContainer.classList.add("has-animation"),e.play(),t.play()},{once:!0})})})}}customElements.define("reaction-element",Zn);const ea=new Map;class ta extends HTMLElement{constructor(){super(),this.classList.add("reactions"),this.sorted=[]}connectedCallback(){let e=ea.get(this.key);e||ea.set(this.key,e=new Set),e.add(this),this.onConnectCallback&&this.isConnected&&(this.onConnectCallback(),this.onConnectCallback=void 0)}disconnectedCallback(){const e=ea.get(this.key);e.delete(this),e.size||ea.delete(this.key)}getReactionCount(e){return this.sorted[this.sorted.indexOf(e)].reactionCount}getMessage(){return this.message}init(e,t,s){void 0!==this.key&&this.disconnectedCallback(),this.message=e,this.key=this.message.peerId+"_"+this.message.mid,this.isPlaceholder=s,this.type!==t&&(this.type=t,this.classList.add("reactions-"+t)),this.connectedCallback()}changeMessage(e){return this.init(e,this.type,this.isPlaceholder)}update(e,t){this.message=e,this.render(t)}render(e){const t=this.message.reactions,s=!(!t||!t.results.length);if(this.classList.toggle("has-no-reactions",!s),!s&&!this.sorted.length)return;const i=jt.a.getAvailableReactions(),n=s?i instanceof Promise?t.results:t.results.filter(e=>jt.a.isReactionActive(e.reaction)):[];Object(f.a)(this.sorted,(e,t,s)=>{const i=e.reactionCount.reaction;n.some(e=>e.reaction===i)||(s.splice(t,1),e.remove())});const a=n.reduce((e,t)=>e+t.count,0),o=t&&!!t.pFlags.can_see_list&&a<4;if(this.sorted=n.map((e,s)=>{const i=this.sorted.findIndex(t=>t.reactionCount.reaction===e.reaction);let n=-1!==i&&this.sorted[i];n||(n=new Zn,n.init(this.type)),Ns(n,this,s);const a=t.recent_reactions?t.recent_reactions.filter(t=>t.reaction===e.reaction):[];return n.reactionCount=Object.assign({},e),n.setCanRenderAvatars(o),n.render(this.isPlaceholder),n.renderCounter(),n.renderAvatars(a),n.setIsChosen(),n}),!this.isPlaceholder&&(null==e?void 0:e.length)&&(this.isConnected?this.handleChangedResults(e):this.onConnectCallback=()=>{this.handleChangedResults(e)}),!this.sorted.length&&"block"===this.type){const e=this.parentElement;if(this.remove(),e.classList.contains("document-message")&&!e.childNodes.length)return void e.remove();const t=this.querySelector(".time");t&&e.append(t)}}handleChangedResults(e){this.message.peerId===a.a.peerId&&e.forEach(e=>{const t=this.sorted.find(t=>t.reactionCount.reaction===e.reaction);t&&t.fireAroundAnimation()})}}customElements.define("reactions-element",ta);a.a.addEventListener("replies_updated",e=>{Array.from(document.querySelectorAll(`replies-element[data-post-key="${e.peerId}_${e.mid}"]`)).forEach(t=>{t.message=e,t.render()})});class sa extends HTMLElement{constructor(){super(),this.updated=!1}init(){this.render(),this.dataset.postKey=this.message.peerId+"_"+this.message.mid,this.classList.add("replies","replies-"+this.type)}render(){const e=this.message.replies;if("footer"===this.type){let t;this.firstElementChild&&(t=this.firstElementChild),(null==e?void 0:e.recent_repliers)?(t&&!t.classList.contains("replies-footer-avatars")&&(this.innerHTML="",t=null),this.stackedAvatars||(this.stackedAvatars=new ns({lazyLoadQueue:this.lazyLoadQueue,avatarSize:30}),this.stackedAvatars.container.classList.add("replies-footer-avatars")),t=this.stackedAvatars.container,this.stackedAvatars.render(e.recent_repliers.map(e=>o.a.getPeerId(e)),this.loadPromises)):(t&&!t.classList.contains("tgico-comments")&&(t.remove(),t=null),t||(t=document.createElement("span"),t.classList.add("tgico-comments"))),t.parentElement||this.prepend(t),this.text||(this.text=new T.c.IntlElement);const s=this.text;if(e?e.replies?s.compareAndUpdate({key:"Comments",args:[e.replies]}):s.compareAndUpdate({key:"LeaveAComment"}):s.compareAndUpdate({key:"ViewInChat"}),e){let t=!1;e.replies&&void 0!==e.read_max_id&&void 0!==e.max_id&&(t=e.read_max_id<e.max_id),this.classList.toggle("is-unread",t)}let i=this.children[1];if(!i){i=document.createElement("span"),i.classList.add("replies-footer-text");const e=document.createElement("span");e.classList.add("tgico-next");const t=document.createElement("div");Object(te.a)(t),this.append(i,e,t)}Object(k.a)(i,s.element)}else this.classList.add("bubble-beside-button"),this.innerHTML=`<span class="tgico-commentssticker"></span><span class="replies-beside-text">${(null==e?void 0:e.replies)?Vn(e.replies,0):""}</span>`;!e||this.updated||this.message.pFlags.is_outgoing||(i.a.subscribeRepliesThread(this.message.peerId,this.message.mid),i.a.updateMessage(this.message.peerId,this.message.mid,"replies_updated"),this.updated=!0),this.loadPromises&&(this.loadPromises=void 0)}}customElements.define("replies-element",sa);const ia=()=>{const e=document.createElement("i");return e.classList.add("edited"),Object(T.b)(e,"EditedMessage"),e},na=()=>Object(T.d)("SponsoredMessage");var aa,oa;(oa=aa||(aa={})).setTime=e=>{var t;const{chatType:s,message:n}=e,a=new Date(1e3*n.date),o=[];let r,l,c,d;const h=!!n.pFlags.sponsored,p=!("action"in n)&&!h;let u,g=h?void 0:Object(ne.f)(a);if(p){if(n.views){const e=n.post_author||(null===(t=n.fwd_from)||void 0===t?void 0:t.post_author),s=document.createElement("span");s.classList.add("post-views"),s.innerHTML=Vn(n.views,1);const i=document.createElement("i");if(i.classList.add("tgico-channelviews","time-icon"),o.push(s,i),e){const t=document.createElement("span");Object(m.a)(t,X.b.wrapEmojiText(e)),t.insertAdjacentHTML("beforeend",",&nbsp;"),o.push(t)}}if(n.edit_date&&"scheduled"!==s&&!n.pFlags.edit_hide&&o.unshift(r=ia()),"pinned"!==s&&n.pFlags.pinned){const e=document.createElement("i");e.classList.add("tgico-pinnedchat","time-icon"),o.unshift(e)}"peerUser"===n.peer_id._&&(u=!0,d=i.a.getGroupsFirstMessage(n),c=new ta,c.init(d,"inline",!0),c.render(),o.unshift(c))}else h&&o.push(l=na());g&&o.push(g);let b=h?void 0:Object(ne.g)(a);p&&(b+=(n.edit_date&&!n.pFlags.edit_hide?"\nEdited: "+Object(ne.g)(new Date(1e3*n.edit_date)):"")+(n.fwd_from?"\nOriginal: "+Object(ne.g)(new Date(1e3*n.fwd_from.date)):""));const v=document.createElement("span");v.classList.add("time","tgico"),v.append(...o);const f=document.createElement("div");f.classList.add("inner","tgico"),b&&(f.title=b);let y=o;if(r&&(y[y.indexOf(r)]=ia()),l&&(y[y.indexOf(l)]=na()),c){const e=y[y.indexOf(c)]=new ta;e.init(d,"inline"),e.render()}return y=y.map(e=>e instanceof HTMLElement&&!e.classList.contains("i18n")&&!e.classList.contains("reactions")?e.cloneNode(!0):e),g&&(y[y.length-1]=Object(ne.f)(a)),f.append(...y),v.append(f),v},oa.renderReplies=({bubble:e,bubbleContainer:t,message:s,messageDiv:i,loadPromises:n,lazyLoadQueue:a})=>{const o=!e.classList.contains("sticker")&&!e.classList.contains("emoji-big")&&!e.classList.contains("round"),r=new sa;return r.message=s,r.type=o?"footer":"beside",r.loadPromises=n,r.lazyLoadQueue=a,r.init(),t.prepend(r),o},oa.setReply=({chat:e,bubble:t,bubbleContainer:s,message:i})=>{const n=!s;n&&(s=t.querySelector(".bubble-content"));const a=n?s.querySelector(".reply"):null;if(!i.reply_to_mid)return a&&a.remove(),void t.classList.remove("is-reply");const o=i.reply_to.reply_to_peer_id?e.appPeersManager.getPeerId(i.reply_to.reply_to_peer_id):e.peerId;let r,l=e.appMessagesManager.getMessageByPeer(o,i.reply_to_mid);"messageEmpty"===l._?(e.appMessagesManager.wrapSingleMessage(o,i.reply_to_mid),e.bubbles.needUpdate.push({replyToPeerId:o,replyMid:i.reply_to_mid,mid:i.mid}),r=Object(T.d)("Loading")):r=new wt.a({peerId:l.fromId||l.fwdFromId,dialog:!1,onlyFirstName:!1,plainText:!1}).element;const c=js(r,void 0,l);a?a.replaceWith(c):s.append(c),t.classList.add("is-reply")};var ra=s(150);function la(e,t,s){const i=e.getBoundingClientRect(),n="center"===s?Math.ceil(i.left+(i.right-i.left)/2+1):Math.ceil(i.left+1),a="bottom"===t?Math.floor(i.top+i.height-1):Math.ceil(i.top+1);return document.elementFromPoint(n,a)}function ca(e){e.style.display="none",e.offsetLeft,e.style.display=""}le.a.getElementByPoint=la;var da=s(16),ha=s(19),pa=s(49),ua=s(136),ga=s(11);const ma={keywords:{},version:0,langCode:Hn.a.langPackCode};class ba{constructor(){this.keywordLangPacks={},this.indexedLangPacks={},this.getKeywordsPromises={}}getEmojiKeywords(e=Hn.a.langPackCode){const t=this.getKeywordsPromises[e];if(t)return t;const s="emojiKeywords_"+e;return this.getKeywordsPromises[e]=ga.a.get(s).then(t=>(Object(ha.a)(t)||(t={}),Object(pa.a)(ma,t),t.langCode=e,this.keywordLangPacks[e]=t,ct.a.invokeApi("messages.getEmojiKeywordsDifference",{lang_code:t.langCode,from_version:t.version}).then(e=>{t.version=e.version;const i=t.keywords,n=e.keywords;for(let e=0,t=n.length;e<t;++e){const{keyword:t,emoticons:s}=n[e];i[t]=s}return ga.a.set({[s]:t}),t},()=>t)))}getBothEmojiKeywords(){const e=[this.getEmojiKeywords()];return T.c.lastRequestedLangCode!==Hn.a.langPackCode&&e.push(this.getEmojiKeywords(T.c.lastRequestedLangCode)),this.recent||e.push(this.getRecentEmojis()),Promise.all(e)}indexEmojis(){this.index||(this.index=new ua.a(void 0,2));for(const e in this.keywordLangPacks){if(this.indexedLangPacks[e])continue;const t=this.keywordLangPacks[e].keywords;for(const e in t){const s=t[e];this.index.indexObject(s,e)}this.indexedLangPacks[e]=!0}}searchEmojis(e){let t;if(this.indexEmojis(),(e=e.toLowerCase().replace(/_/g," ")).trim()){const s=this.index.search(e);t=Array.from(s).reduce((e,t)=>e.concat(t),[])}else t=this.recent.concat(ba.POPULAR_EMOJI).slice(0,36);return t=Array.from(new Set(t)),t}getRecentEmojis(){return this.getRecentEmojisPromise?this.getRecentEmojisPromise:this.getRecentEmojisPromise=M.c.getState().then(e=>this.recent=Array.isArray(e.recentEmoji)?e.recentEmoji:[])}pushRecentEmoji(e){e=X.b.fixEmoji(e),this.getRecentEmojis().then(t=>{Object(V.a)(t,e),t.unshift(e),t.length>36&&(t.length=36),M.c.pushToState("recentEmoji",t),a.a.dispatchEvent("emoji_recent",e)})}}ba.POPULAR_EMOJI=["😂","😘","❤️","😍","😊","😁","👍","☺️","😔","😄","😭","💋","😒","😳","😜","🙈","😉","😃","😢","😝","😱","😡","😏","😞","😅","😚","🙊","😌","😀","😋","😆","👌","😐","😕"];const va=new ba;le.a&&(le.a.appEmojiManager=va);var fa=va,ya=s(23),wa=s(26);const Sa=new Set;function Ca(e,t,s=!1,i=!1){var n;const o=document.createElement("span");let r;if(o.classList.add("super-emoji"),i&&!ya.a?r=X.a.wrapSingleEmoji(e):(e=X.a.fixEmoji(e),r=X.a.wrapEmojiText(e)),o.append(r),o.children.length>1){const e=o.firstElementChild;o.innerHTML="",o.append(e)}if("IMG"===(null===(n=o.firstElementChild)||void 0===n?void 0:n.tagName)){const e=o.firstElementChild,t=e.src;if(!Sa.has(t)){e.setAttribute("loading","lazy");const s=document.createElement("span");s.classList.add("emoji-placeholder"),a.a.settings.animationsEnabled&&(e.style.opacity="0",s.style.opacity="1"),e.addEventListener("load",()=>{Object(Le.b)(()=>{a.a.settings.animationsEnabled&&(e.style.opacity="",s.style.opacity=""),o.classList.remove("empty"),Sa.add(t)})},{once:!0}),o.append(s)}}s?t.prepend(o):t.appendChild(o)}function La(e){return Object(Ce.a)(e,"super-emoji")?3===e.nodeType?e.nodeValue:("SPAN"===e.tagName&&!e.classList.contains("emoji")&&e.firstElementChild&&(e=e.firstElementChild),e.getAttribute("alt")||e.innerText):""}class Ia{constructor(){this.closeScrollTop=0,this.onContentClick=e=>{Object(c.a)(e);const t=La(e.target);t&&(nc.chat.input.onEmojiSelected(t,!1),he.b&&Object(ti.a)())}}init(){this.content=document.getElementById("content-emoji");const e=["Emoji.SmilesAndPeople","Emoji.AnimalsAndNature","Emoji.FoodAndDrink","Emoji.TravelAndPlaces","Emoji.ActivityAndSport","Emoji.Objects","Emoji.Flags","Skin Tones"],t={},s=new Map([["Emoji.Recent",[]]]);for(const t in wa.b){const i=""+wa.b[t],n=e[+i[0]-1];if(!n)continue;let a=s.get(n);a||(a=[],s.set(n,a)),a[+i.slice(1)||0]=t}s.delete(e.pop()),s.forEach((e,s)=>{const i=document.createElement("div");i.classList.add("emoji-category");const n=document.createElement("div");n.classList.add("category-title"),n.append(Object(T.d)(s));const a=document.createElement("div");a.classList.add("super-emojis"),i.append(n,a),e.forEach(e=>{Ca(Object(se.a)(e),a,!1)}),t[s]=i});const i=this.menu=this.content.previousElementSibling,n=this.scroll=new P.b(this.content,"EMOJI"),o=Object(ee.f)(this.content,!0);Promise.all([Object(da.a)(200),fa.getRecentEmojis().then(e=>{const t=!!e.length,s=t?0:1;this.menu.children[0].classList.toggle("hide",!t),this.menu.children[s].classList.add("active");const a=za.menuOnClick(i,n,void 0,s);return this.stickyIntersector=a.stickyIntersector,this.setMenuActive=a.setActive,e})]).then(([s,i])=>{o.remove(),this.recentItemsDiv=t["Emoji.Recent"].querySelector(".super-emojis");for(const e of i)Ca(e,this.recentItemsDiv);this.recentItemsDiv.parentElement.classList.toggle("hide",!this.recentItemsDiv.childElementCount),e.unshift("Emoji.Recent"),e.map(e=>{const s=t[e];return s||console.error("no div by category:",e),n.container.append(s),this.stickyIntersector.observeStickyHeaderChanges(s),s})}),this.content.addEventListener("click",this.onContentClick),this.init=null,a.a.addEventListener("emoji_recent",e=>{const t=Array.from(this.recentItemsDiv.children);for(let s=0,i=t.length;s<i;++s){const i=t[s];if(e===X.a.fixEmoji(La(i))){if(0===s)return;i.remove()}}Ca(e,this.recentItemsDiv,!0),this.recentItemsDiv.parentElement.classList.remove("hide"),this.menu.children[0].classList.remove("hide"),this.closeScrollTop||this.setMenuActive(0)}),Ka.addEventListener("close",()=>{this.closeScrollTop=this.scroll.scrollTop})}onClose(){}}var Ma=s(139),Ea=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Pa{constructor(e,t,s,i=!0){this.element=e,this.group=t,this.scrollable=s,this.scrollPromise=Promise.resolve(),this.timeout=0,this.onScroll=()=>{this.timeout?clearTimeout(this.timeout):this.scrollPromise=Object(ie.a)(),this.timeout=window.setTimeout(()=>{this.timeout=0,this.scrollPromise.resolve()},150)},this.processInvisibleDiv=e=>this.scrollPromise.then(()=>Ea(this,void 0,void 0,(function*(){if(this.lazyLoadQueue.intersector.isVisible(e))return;const t=e.querySelector("video"),s=e.querySelector("img");if(s&&(s&&s.classList.remove("hide"),yield Object(Le.a)()),!this.lazyLoadQueue.intersector.isVisible(e)&&t){t.remove(),t.src="",t.load();I.a.getAnimations(t).forEach(e=>{I.a.checkAnimation(e,!0,!0)})}}))),this.lazyLoadQueue=new Z.c(void 0,(e,t)=>{t?this.processVisibleDiv(e):this.processInvisibleDiv(e)}),i&&this.attach()}attach(){this.scrollable.container.addEventListener("scroll",this.onScroll)}detach(){this.clear(),this.scrollable.container.removeEventListener("scroll",this.onScroll)}clear(){this.lazyLoadQueue.clear()}processVisibleDiv(e){if(e.querySelector("video"))return;this.lazyLoadQueue.push({div:e,load:()=>{const t=e.dataset.docId,s=L.a.getDoc(t);return this.scrollPromise.then(()=>{const t=Ms({doc:s,container:e,lazyLoadQueue:null,group:this.group,noInfo:!0}).loadPromise;return t.finally(()=>{const t=e.querySelector("video");e.style.opacity="";const s=e.querySelector("img");s&&s.classList.add("hide"),t&&!t.parentElement&&setTimeout(()=>{t.src="",t.load();I.a.getAnimations(t).forEach(e=>{I.a.checkAnimation(e,!0,!0)})},0),this.lazyLoadQueue.intersector.isVisible(e)||this.processInvisibleDiv(e)}),t})}})}add(e,t=this.element){var s;let i=e.w,n=e.h;n<100&&(i*=100/n,n=100);const a=Math.min(300,400,i),o=Object(Ma.a)(i,n,a,100),r=document.createElement("div");r.classList.add("gif","fade-in-transition"),r.style.width=o.width+"px",r.style.opacity="0",r.dataset.docId=""+e.id,t.append(r),this.lazyLoadQueue.observe(r);const l=L.a.getThumb(e,!1);let c;!!l&&(c=new Image,c.classList.add("media-poster"),l.cacheContext.url||l.promise.then(()=>{c.src=l.cacheContext.url}));const d=()=>{c&&(r.append(c),r.style.opacity="")};(null===(s=null==l?void 0:l.cacheContext)||void 0===s?void 0:s.url)?Object(ps.a)(c,l.cacheContext.url,d):d()}}class ka{init(){this.content=document.getElementById("content-gifs");const e=this.content.firstElementChild;e.addEventListener("click",za.onMediaClick);const t=new P.b(this.content,"GIFS"),s=new Pa(e,Ha,t),i=Object(ee.f)(this.content,!0);ct.a.invokeApi("messages.getSavedGifs",{hash:"0"}).then(e=>{"messages.savedGifs"===e._&&e.gifs.forEach((t,i)=>{e.gifs[i]=t=L.a.saveDoc(t),s.add(t)}),i.remove()}),Ka.addLazyLoadQueueRepeat(s.lazyLoadQueue,s.processInvisibleDiv),this.init=null}onClose(){}}var Ta=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class xa{constructor(e,t){this.regularLazyLoadQueue=e,this.group=t,this.animatedDivs=new Set,this.checkAnimationContainer=(e,t)=>{I.a.getAnimations(e).forEach(e=>{t?I.a.checkAnimation(e,!1):I.a.checkAnimation(e,!0,!0)})},this.processVisibleDiv=e=>{const t=e.dataset.docId,s=L.a.getDoc(t),i=b.b.active.esgSticker.width,n=xs({doc:s,div:e,width:i,height:i,lazyLoadQueue:null,group:this.group,onlyThumb:!1,play:!0,loop:!0});return n.then(()=>{this.checkAnimationContainer(e,this.lazyLoadQueue.intersector.isVisible(e))}),n},this.processInvisibleDiv=e=>{const t=e.dataset.docId,s=L.a.getDoc(t);this.checkAnimationContainer(e,!1),e.innerHTML="",this.renderSticker(s,e)},this.lazyLoadQueue=new Z.b(void 0,(e,t)=>{t||this.processInvisibleDiv(e)})}clear(){this.lazyLoadQueue.clear()}renderSticker(e,t,s){return t||((t=document.createElement("div")).classList.add("grid-item","super-sticker"),e.animated&&this.observeAnimatedDiv(t)),xs({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:e.animated,loadPromises:s}),t}observeAnimatedDiv(e){this.animatedDivs.add(e),this.lazyLoadQueue.observe({div:e,load:this.processVisibleDiv})}}class Aa{constructor(){this.stickerSets={},this.recentStickers=[],this.mounted=!1,this.queueCategoryPush=[]}categoryPush(e,t="",s,i){const n=document.createElement("div");n.classList.add("category-items","super-stickers");const a=document.createElement("div");return a.classList.add("category-title"),t&&("string"==typeof t?a.innerHTML=t:a.append(t)),e.append(a,n),this.stickyIntersector.observeStickyHeaderChanges(e),this.queueCategoryPush.push({element:e,prepend:i}),s.then(e=>{e.forEach(e=>{n.append(this.superStickerRenderer.renderSticker(e))}),this.queueCategoryPush.length&&(this.queueCategoryPush.forEach(({element:e,prepend:t})=>{t?this.recentDiv.parentElement?(this.stickersDiv.prepend(e),this.stickersDiv.prepend(this.recentDiv)):this.stickersDiv.prepend(e):this.stickersDiv.append(e)}),this.queueCategoryPush.length=0)}),{titleDiv:a}}renderStickerSet(e,t=!1){return Ta(this,void 0,void 0,(function*(){const s=document.createElement("div");s.classList.add("sticker-category"),s.dataset.id=""+e.id,s.dataset.access_hash=""+e.access_hash;const i=document.createElement("button");i.classList.add("btn-icon","menu-horizontal-div-item"),this.stickerSets[e.id]={stickers:s,tab:i},t?this.menu.insertBefore(i,this.menu.firstElementChild.nextSibling):this.menu.append(i);const n=gs.a.getStickerSet(e);this.categoryPush(s,X.a.wrapEmojiText(e.title),n.then(e=>e.documents),t);yield n;As({set:e,container:i,group:Ha,lazyLoadQueue:za.lazyLoadQueue,width:32,height:32,autoplay:!1})}))}init(){this.content=document.getElementById("content-stickers"),this.recentDiv=document.createElement("div"),this.recentDiv.classList.add("sticker-category","stickers-recent");let e=this.content.previousElementSibling;this.menu=e.firstElementChild;let t=new P.a(e);this.stickersDiv=document.createElement("div"),this.stickersDiv.classList.add("stickers-categories"),this.content.append(this.stickersDiv),a.a.addEventListener("stickers_installed",e=>{const t=e;!this.stickerSets[t.id]&&this.mounted&&this.renderStickerSet(t,!0)}),a.a.addEventListener("stickers_deleted",e=>{const t=e;if(this.stickerSets[t.id]&&this.mounted){const e=this.stickerSets[t.id];e.stickers.remove(),e.tab.remove(),delete this.stickerSets[t.id]}}),this.stickersDiv.addEventListener("click",e=>{const t=e.target;if(Object(Ce.a)(t,"category-title")){const e=Object(yt.a)(t,"data-id");new on({id:e.dataset.id,access_hash:e.dataset.access_hash}).show()}else za.onMediaClick(e)});const s=(e=!1)=>{a.a.dispatchEvent("choosing_sticker",!e)};this.scroll=new P.b(this.content,"STICKERS"),this.scroll.setVirtualContainer(this.stickersDiv),this.scroll.onAdditionalScroll=()=>{s()},Ka.addEventListener("closed",()=>{s(!0)}),Ka.addEventListener("opened",()=>{s()}),this.stickyIntersector=za.menuOnClick(this.menu,this.scroll,t).stickyIntersector;const i=Object(ee.f)(this.content,!0);Promise.all([gs.a.getRecentStickers().then(e=>{this.recentStickers=e.stickers.slice(0,20),this.stickerSets.recent={stickers:this.recentDiv,tab:this.menu.firstElementChild},i.remove();const{titleDiv:t}=this.categoryPush(this.recentDiv,"",Promise.resolve(this.recentStickers),!0);t.append(Object(T.d)("Stickers.Recent"))}),gs.a.getAllStickers().then(e=>{i.remove();for(let t of e.sets)this.renderStickerSet(t)})]).finally(()=>{this.mounted=!0,s()}),this.superStickerRenderer=new xa(za.lazyLoadQueue,Ha),Ka.addLazyLoadQueueRepeat(this.superStickerRenderer.lazyLoadQueue,this.superStickerRenderer.processInvisibleDiv),this.init=null}pushRecentSticker(e){var t;if(gs.a.pushRecentSticker(e),!(null===(t=this.recentDiv)||void 0===t?void 0:t.parentElement))return;let s=this.recentDiv.querySelector(`[data-doc-id="${e.id}"]`);s||(s=this.superStickerRenderer.renderSticker(e));const i=this.recentDiv.querySelector(".category-items");i.prepend(s),i.childElementCount>20&&Array.from(i.children).slice(20).forEach(e=>e.remove())}onClose(){}}var Oa=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const ja=new class{constructor(){this.inlineResults={},this.setHash={}}getGeoInput(e){return"geoPoint"===e._?{_:"inputGeoPoint",lat:e.lat,long:e.long,accuracy_radius:e.accuracy_radius}:{_:"inputGeoPointEmpty"}}getInlineResults(e,t,s="",i="",n){return ct.a.invokeApi("messages.getInlineBotResults",{bot:E.a.getUserInput(t),peer:o.a.getInputPeerById(e),query:s,geo_point:n?this.getGeoInput(n):void 0,offset:i},{stopTime:-1,noErrorBox:!0}).then(e=>{const t=e.query_id;return e.results.forEach(e=>{"botInlineMediaResult"===e._&&(e.document&&(e.document=L.a.saveDoc(e.document)),e.photo&&(e.photo=r.a.savePhoto(e.photo))),this.inlineResults[this.generateQId(t,e.id)]=e}),e})}generateQId(e,t){return e+"_"+t}pushPopularBot(e){E.a.getTopPeers("bots_inline").then(t=>{const s=e.toPeerId(),i=t.findIndex(e=>e.id===s);let n;n=-1!==i?t[i]:{id:s,rating:0},++n.rating,Object(Us.a)(t,n,"rating"),M.c.setKeyValueToStorage("topPeersCache")})}switchToPM(e,t,s){return this.setHash[t]={peerId:e,time:Date.now()},a.a.dispatchEvent("history_focus",{peerId:t.toPeerId()}),i.a.startBot(t,void 0,s)}checkSwitchReturn(e){return Oa(this,void 0,void 0,(function*(){const t=E.a.getUser(e);if(!t||!t.pFlags.bot||!t.bot_inline_placeholder)return;const s=this.setHash[e];return s&&(delete this.setHash[e],Date.now()-s.time<36e5)?s.peerId:void 0}))}switchInlineQuery(e,t,s,i){a.a.dispatchEvent("history_focus",{peerId:e,threadId:t}),Vi.a.setDraft(e,t,"@"+E.a.getUser(s).username+" "+i)}callbackButtonClick(e,t,s){return ct.a.invokeApi("messages.getBotCallbackAnswer",{peer:o.a.getInputPeerById(e),msg_id:v.a.getServerMessageId(t),data:s.data},{stopTime:-1,noErrorBox:!0}).then(e=>{"string"==typeof e.message&&e.message.length&&ot(X.a.wrapRichText(e.message,{noLinks:!0,noLinebreaks:!0}))})}sendInlineResult(e,t,s,n={}){var a;const o=this.inlineResults[s];if(!o)return;this.pushPopularBot(t);const l=s.split("_"),c=l.shift(),d=l.join("_");if(n.viaBotId=t,n.queryId=c,n.resultId=d,o.send_message.reply_markup&&(n.replyMarkup=o.send_message.reply_markup),"botInlineMessageText"===o.send_message._)n.entities=o.send_message.entities,i.a.sendText(e,o.send_message.message,n);else{let t,s="";const l=o.send_message;switch(l._){case"botInlineMessageMediaAuto":if(s=l.message,"botInlineMediaResult"===o._){const{document:e,photo:s}=o;t=e?L.a.getMediaInput(e):r.a.getMediaInput(s)}break;case"botInlineMessageMediaGeo":t={_:"inputMediaGeoPoint",geo_point:this.getGeoInput(l.geo)},n.geoPoint=l.geo;break;case"botInlineMessageMediaVenue":t={_:"inputMediaVenue",geo_point:this.getGeoInput(l.geo),title:l.title,address:l.address,provider:l.provider,venue_id:l.venue_id,venue_type:l.venue_type},n.geoPoint=l.geo;break;case"botInlineMessageMediaContact":t={_:"inputMediaContact",phone_number:l.phone_number,first_name:l.first_name,last_name:l.last_name,vcard:l.vcard}}t||(t={_:"messageMediaPending",type:o.type,file_name:o.title||(null===(a=o.content)||void 0===a?void 0:a.url)||o.url,size:0,progress:{percent:30,total:0}}),i.a.sendOther(e,t,n)}}};le.a&&(le.a.appInlineBotsManager=ja);var _a=ja,Fa=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Da extends H{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=e=>{const t=Object(Ce.a)(e.target,"gif");if(!t)return;const s=t.dataset.docId;nc.chat.input.sendMessageWithDocument(s)?b.b.isMobile&&ts.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new j("SearchGifsTitle",e=>{this.reset(),this.search(e)}),this.title.replaceWith(this.inputSearch.container),this.gifsDiv=document.createElement("div"),this.gifsDiv.classList.add("gifs-masonry"),Object(l.b)(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new Pa(this.gifsDiv,"GIFS-SEARCH",this.scrollable)}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.innerHTML="",I.a.checkAnimations(void 0,"GIFS-SEARCH"),this.inputSearch.remove(),super.onCloseAfterTimeout()}reset(){this.searchPromise=null,this.nextOffset="",this.loadedAll=!1,this.masonry.clear()}open(){const e=super.open();return ts.toggleSidebar(!0).then(()=>{this.search("",!0),this.scrollable.onScrolledBottom=()=>{this.search(this.inputSearch.value,!1)}}),e}search(e,t=!0){return Fa(this,void 0,void 0,(function*(){if(!this.searchPromise&&!this.loadedAll){this.gifBotPeerId||(this.gifBotPeerId=(yield E.a.resolveUsername("gif")).id.toPeerId(!1));try{this.searchPromise=_a.getInlineResults(Me.c,this.gifBotPeerId,e,this.nextOffset);const{results:s,next_offset:i}=yield this.searchPromise;if(this.inputSearch.value!==e)return;this.searchPromise=null,this.nextOffset=i,t&&(this.gifsDiv.innerHTML=""),s.length?s.forEach(e=>{"botInlineMediaResult"===e._&&e.document&&this.masonry.add(e.document)}):this.loadedAll=!0,this.scrollable.onScroll()}catch(e){throw this.searchPromise=null,console.error("gifs loading error:",e),e}}}))}}class Ra extends H{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new Z.d,this.inputSearch=new j("StickersTab.SearchPlaceholder",e=>{this.search(e)}),this.title.replaceWith(this.inputSearch.container),this.setsDiv=document.createElement("div"),this.setsDiv.classList.add("sticker-sets"),this.scrollable.append(this.setsDiv),Object(l.b)(this.setsDiv,e=>{const t=Object(Ce.a)(e.target,"sticker-set-sticker");if(t){const e=t.dataset.docId;return void nc.chat.input.sendMessageWithDocument(e)}const s=Object(Ce.a)(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,a=Object(Ce.a)(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),gs.a.getStickerSet({id:i,access_hash:n}).then(e=>{gs.a.toggleStickerSet(e.set).then(t=>{t&&(a.textContent="",a.append(Object(T.d)(e.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!e.set.installed_date))}).finally(()=>{a.removeAttribute("disabled")})})):gs.a.getStickerSet({id:i,access_hash:n}).then(e=>{new on(e.set).show()})},{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.setsDiv.innerHTML="",I.a.checkAnimations(void 0,"STICKERS-SEARCH"),super.onCloseAfterTimeout()}renderSet(e){const t=document.createElement("div");t.classList.add("sticker-set");const s=document.createElement("div");s.classList.add("sticker-set-header");const i=document.createElement("div");i.classList.add("sticker-set-details"),i.innerHTML='<div class="sticker-set-name"></div>',Object(m.a)(i.firstElementChild,X.a.wrapEmojiText(e.title));const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append(Object(T.d)("Stickers",[e.count])),i.append(n);const a=document.createElement("button");a.classList.add("btn-primary","btn-color-primary","sticker-set-button"),a.append(Object(T.d)(e.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),e.installed_date&&a.classList.add("gray"),s.append(i,a);const o=document.createElement("div");o.classList.add("sticker-set-stickers");const r=Math.min(5,e.count);for(let e=0;e<r;++e){const e=document.createElement("div");e.classList.add("sticker-set-sticker"),o.append(e)}gs.a.getStickerSet(e).then(e=>{for(let t=0;t<r;++t){const s=o.children[t],i=e.documents[t];"documentEmpty"!==i._&&xs({doc:i,div:s,lazyLoadQueue:this.lazyLoadQueue,group:"STICKERS-SEARCH",play:!0,loop:!0,width:68,height:68})}}),t.dataset.stickerSet=""+e.id,t.dataset.access_hash=""+e.access_hash,t.dataset.title=e.title,t.append(s,o),this.setsDiv.append(t)}open(){const e=super.open();return ts.toggleSidebar(!0).then(()=>{this.renderFeatured()}),e}renderFeatured(){return gs.a.getFeaturedStickers().then(e=>{this.inputSearch.value||(e=this.filterRendered("",e)).forEach(e=>{this.renderSet(e.set)})})}filterRendered(e,t){t=t.slice();const s=Array.from(this.setsDiv.children);return Object(f.a)(s,s=>{const i=s.dataset.stickerSet,n=t.findIndex(e=>e.set.id===i);-1!==n?t.splice(n,1):e&&s.dataset.title.toLowerCase().includes(e.toLowerCase())||s.remove()}),I.a.checkAnimations(void 0,"STICKERS-SEARCH"),t}search(e){return e?gs.a.searchStickerSets(e,!1).then(t=>{this.inputSearch.value===e&&(t=this.filterRendered(e,t)).forEach(e=>{this.renderSet(e.set)})}):this.renderFeatured()}}var Ba=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Na extends D.a{constructor(e){super(!1),this.forceClose=!1,this.inited=!1,this.onMouseOut=e=>{if(clearTimeout(this.displayTimeout),!this.isActive())return;const t=e.toElement;t&&Object(ii.a)(t,this.element)||(this.displayTimeout=window.setTimeout(()=>{this.toggle(!1)},200))},this.toggle=e=>Ba(this,void 0,void 0,(function*(){const t=!!this.element.style.display&&void 0===e||e;if(this.init){if(!t)return;this.init(),this.init=null}if(t!==this.isActive())if(this.element.style.display&&void 0===e||e){const e=this.dispatchResultableEvent("open");yield Promise.all(e),this.element.style.display="",this.element.offsetLeft,this.element.classList.add("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.forceClose=!1,this.dispatchEvent("opened")},he.a?0:200)}else this.dispatchEvent("close"),this.element.classList.remove("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.element.style.display="none",this.forceClose=!1,this.dispatchEvent("closed")},he.a?0:200)})),Object(w.a)(this,e)}attachButtonListener(e,t){let s=!0;he.a?Object(l.b)(e,()=>{s?(s=!1,this.toggle(!0)):this.toggle()},{listenerSetter:t}):t.add(e)("mouseover",i=>{s&&(t.add(e)("mouseout",this.onMouseOut),s=!1),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.toggle(!0)},200)})}init(){he.a||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||clearTimeout(this.displayTimeout)})}isActive(){return this.element.classList.contains("active")}}var Ua=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Ha="emoticons-dropdown";class za extends Na{constructor(){super({element:document.getElementById("emoji-dropdown")}),this.tabId=-1,this.onSelectTabClick=e=>{this.tabId!==e&&(I.a.checkAnimations(!0,Ha),this.tabId=e,this.searchButton.classList.toggle("hide",0===this.tabId),this.deleteBtn.classList.toggle("hide",0!==this.tabId))},this.checkRights=()=>{const{peerId:e,threadId:t}=nc.chat,s=this.tabsEl.children,n=Array.from(s),a=i.a.canSendToPeer(e,t,"send_stickers");n[2].toggleAttribute("disabled",!a);const o=i.a.canSendToPeer(e,t,"send_gifs");n[3].toggleAttribute("disabled",!o);const r=this.tabsEl.querySelector(".active");!r||1===Object(Bs.a)(r)||a&&o||this.selectTab(0,!1)},this.addEventListener("open",()=>Ua(this,void 0,void 0,(function*(){he.a&&Object(ti.a)()&&(yield Object(da.a)(100)),this.element.parentElement!==nc.chat.input.chatInput&&nc.chat.input.chatInput.append(this.element),this.savedRange=this.getGoodRange(),za.lazyLoadQueue.lock(),I.a.lockIntersectionGroup(Ha)}))),this.addEventListener("opened",()=>{I.a.unlockIntersectionGroup(Ha),za.lazyLoadQueue.unlock(),za.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover")}),this.addEventListener("close",()=>{za.lazyLoadQueue.lock(),I.a.lockIntersectionGroup(Ha),I.a.checkAnimations(!0,Ha)}),this.addEventListener("closed",()=>{I.a.unlockIntersectionGroup(Ha),za.lazyLoadQueue.unlock(),za.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover"),this.savedRange=void 0})}init(){this.emojiTab=new Ia,this.stickersTab=new Aa,this.gifsTab=new ka,this.tabs={0:this.emojiTab,1:this.stickersTab,2:this.gifsTab},this.container=this.element.querySelector(".emoji-container .tabs-container"),this.tabsEl=this.element.querySelector(".emoji-tabs"),this.selectTab=Object(J.a)(this.tabsEl,this.container,this.onSelectTabClick,()=>{const e=this.tabs[this.tabId];e.init&&e.init(),e.onCloseAfterTimeout&&e.onCloseAfterTimeout(),I.a.checkAnimations(!1,Ha)}),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.searchButton.addEventListener("click",()=>{1===this.tabId?ts.isTabExists(Ra)||new Ra(ts).open():ts.isTabExists(Da)||new Da(ts).open()}),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),this.deleteBtn.addEventListener("click",e=>{var t;const s=nc.chat.input.messageInput;(null===(t=s.lastChild)||void 0===t?void 0:t.tagName)?s.lastElementChild.remove():s.lastChild&&(s.lastChild.textContent.length?s.lastChild.textContent=s.lastChild.textContent.slice(0,-1):s.lastChild.remove());const i=new Event("input",{bubbles:!0,cancelable:!0});nc.chat.input.messageInput.dispatchEvent(i),Object(c.a)(e)});const e=ae.c,t=e?1:0;return e&&this.tabsEl.children[1].classList.add("hide"),this.tabsEl.children[t+1].click(),this.tabs[t].init&&this.tabs[t].init(),a.a.addEventListener("peer_changed",this.checkRights),this.checkRights(),super.init()}addLazyLoadQueueRepeat(e,t){this.addEventListener("close",()=>{e.lock()}),this.addEventListener("closed",()=>{const s=e.intersector.getVisible();for(const e of s)t(e);e.intersector.clearVisible()}),this.addEventListener("opened",()=>{e.unlockAndRefresh()})}getSavedRange(){return this.getGoodRange()||this.savedRange}getGoodRange(){const e=document.getSelection();if(e.rangeCount&&document.activeElement===nc.chat.input.messageInput)return e.getRangeAt(0)}}za.lazyLoadQueue=new Z.d,za.menuOnClick=(e,t,s,i=0)=>{let n=-1;const a=t=>t!==i&&(e.children[i].classList.remove("active"),e.children[t].classList.add("active"),i=t,!0),o=new Jn(t.container,(i,o)=>{if(Math.abs(n-t.container.scrollTop)<=1)return;n=-1;const r=Object(Bs.a)(o);!i&&r||(a(r),s&&(r<e.childElementCount-4?s.container.scrollLeft=47*(r-3):s.container.scrollLeft=47*r))});return e.addEventListener("click",e=>{let s=e.target;if(s=Object(Ce.a)(s,"menu-horizontal-div-item"),!s)return;const i=Object(Bs.a)(s);if(!a(i))return;const o=(t.splitUp||t.container).children[i].offsetTop+1;t.container.scrollTop=n=o}),{stickyIntersector:o,setActive:a}},za.onMediaClick=(e,t=!1)=>{let s=e.target;if(s=Object(bt.a)(s,"DIV"),!s)return!1;const i=s.dataset.docId;return!!i&&(nc.chat.input.sendMessageWithDocument(i,void 0,t)?(Va.container&&(Va.forceClose=!0,Va.container.classList.add("disable-hover"),Va.toggle(!1)),!0):(console.warn("got no doc by id:",i),!1))};const Va=new za;le.a.emoticonsDropdown=Va;var Ka=Va;var Ga=s(190);var Wa=!("undefined"==typeof RTCPeerConnection||ae.d);var qa=Wa;function Qa(e,t,s,i=e.getBoundingClientRect(),n=t.getBoundingClientRect()){let{top:a,right:o,bottom:r,left:l}=n;if(s){const e=t.querySelector(".sticky");if(e){a=e.getBoundingClientRect().bottom}}if(i.top>=r||i.bottom<=a||i.right<=l||i.left>=o)return null;const c={top:!1,right:!1,bottom:!1,left:!1,vertical:0,horizontal:0},d="visualViewport"in window?window.visualViewport:window,h=d.width||d.innerWidth,p=d.height||d.innerHeight;return{rect:{top:i.top<a&&0!==a?(c.top=!0,++c.vertical,a):i.top,right:i.right>o&&o!==h?(c.right=!0,++c.horizontal,o):i.right,bottom:i.bottom>r&&r!==p?(c.bottom=!0,++c.vertical,r):i.bottom,left:i.left<l&&0!==l?(c.left=!0,++c.horizontal,l):i.left},overflow:c}}window.getVisibleRect=Qa;var $a,Ya=s(156);class Xa extends ht.b{constructor(e,t){super("popup-join-chat-invite",Object(ht.a)([{langKey:t.pFlags.request_needed?"RequestJoin.Button":t.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle",callback:()=>{ct.a.invokeApi("messages.importChatInvite",{hash:e}).then(e=>{vi.a.processUpdateMessage(e);const t=e.chats[0].id.toPeerId(!0);a.a.dispatchEvent("history_focus",{peerId:t})},e=>{"INVITE_REQUEST_SENT"===e.type&&rt({langPackKey:"RequestToJoinSent"})})}}]),{closable:!0,overlayClosable:!0,body:!0}),this.header.remove();const s=new fc;s.classList.add("avatar-100"),s.isDialog=!1,"photo"===t.photo._?(t.photo=r.a.savePhoto(t.photo),Ps({container:s,message:null,photo:t.photo,boxHeight:100,boxWidth:100,withoutPreloader:!0}),s.style.width=s.style.height=""):d.a.putPhoto(s,Me.c,!1,t.title);const i=document.createElement("div");i.classList.add("chat-title"),Object(m.a)(i,X.b.wrapEmojiText(t.title));const n=t.pFlags.broadcast,o=Object(T.d)(n?"Subscribers":"Members",[Object(Ya.a)(t.participants_count)]);if(o.classList.add("chat-participants-count"),this.body.append(s,i,o),t.pFlags.request_needed){const e=document.createElement("div");Object(T.b)(e,n?"RequestToJoinChannelDescription":"RequestToJoinGroupDescription"),e.classList.add("chat-participants-count","request-caption"),this.body.append(e)}}}!function(e){e[e.MESSAGE=0]="MESSAGE",e[e.PRIVATE_POST=1]="PRIVATE_POST",e[e.STICKER_SET=2]="STICKER_SET",e[e.JOIN_CHAT=3]="JOIN_CHAT",e[e.VOICE_CHAT=4]="VOICE_CHAT",e[e.USER_PHONE_NUMBER=5]="USER_PHONE_NUMBER"}($a||($a={}));class Ja{constructor(e,t){this.scrollable=e,this.reverse=t}get container(){return this.scrollable.container}getSaved(){return{scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,clientHeight:this.clientHeight}}save(){const{scrollTop:e,scrollHeight:t,clientHeight:s}=this.container;this.scrollHeight=t,this.scrollTop=e,this.clientHeight=s,this.scrollHeightMinusTop=this.reverse?t-e:e}restore(e){const{container:t,scrollHeightMinusTop:s,scrollable:i}=this;if(void 0===s)throw new Error("scroll was not saved");const n=t.scrollHeight;if(n===this.scrollHeight)return;this.scrollHeight=n;const a=this.reverse?n-s:s;this.scrollable.setScrollTopSilently(this.scrollTop=a),ae.g&&e&&ca(t)}}class Za{constructor(e){this.observing=new Map,this.observingQueue=new Map,this.freezedObservingNew=!1,this.observer=new IntersectionObserver(e=>{const t=this.observing;for(let s=0,i=e.length;s<i;++s){const i=e[s],n=t.get(i.target);for(const e of n)try{e(i)}catch(e){console.error("intersection process callback error:",e)}}},e)}disconnect(){this.observing.clear(),this.observingQueue.clear(),this.observer.disconnect()}toggleObservingNew(e){if(this.freezedObservingNew===e)return;this.freezedObservingNew=e;const t=this.observingQueue;if(!e&&t.size){for(const[e,s]of t)for(const t of s)this.observe(e,t);t.clear()}}has(e,t,s=this.observing){const i=s.get(e);return!(!i||!i.has(t))}observe(e,t){if(this.freezedObservingNew&&this.has(e,t))return;const s=this.freezedObservingNew?this.observingQueue:this.observing;let i=s.get(e);i&&i.has(t)||(i||(i=new Set,s.set(e,i),s===this.observing&&this.observer.observe(e)),i.add(t))}unobserve(e,t){const s=this.freezedObservingNew&&!this.has(e,t)?this.observingQueue:this.observing,i=s.get(e);i&&(i.delete(t),i.size||(s.delete(e),this.observer.unobserve(e)))}}var eo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const to=new Set(["messageActionHistoryClear","messageActionChatCreate"]),so=new Set;qa&&so.add("messageActionPhoneCall");let io=void 0,no=0;class ao{constructor(e,t,s,i,n,o,r,d,h,p,u,g,m){if(this.chat=e,this.appMessagesManager=t,this.appStickersManager=s,this.appUsersManager=i,this.appInlineBotsManager=n,this.appPhotosManager=o,this.appPeersManager=r,this.appProfileManager=d,this.appDraftsManager=h,this.appMessagesIdsManager=p,this.appChatsManager=u,this.appReactionsManager=g,this.appWebPagesManager=m,this.unreadOut=new Set,this.needUpdate=[],this.bubbles={},this.skippedMids=new Set,this.dateMessages={},this.scrolledDown=!0,this.isScrollingTimeout=0,this.unreaded=new Map,this.unreadedSeen=new Set,this.preloader=null,this.messagesQueuePromise=null,this.messagesQueue=[],this.messagesQueueOnRender=null,this.messagesQueueOnRenderAdditional=null,this.firstUnreadBubble=null,this.middleware=Object(Rs.a)(),this.replyFollowHistory=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.viewsMids=new Set,this.isTopPaddingSet=!1,this.unreadedObserverCallback=e=>{if(e.isIntersecting){const t=e.target,s=this.unreaded.get(t);this.onUnreadedInViewport(t,s)}},this.viewsObserverCallback=e=>{if(e.isIntersecting){const t=+e.target.dataset.mid;if(this.observer.unobserve(e.target,this.viewsObserverCallback),t)this.viewsMids.add(t),this.sendViewCountersDebounced();else{const{sponsoredMessage:e}=this;e&&e.random_id&&(delete e.random_id,this.chat.apiManager.invokeApiSingle("channels.viewSponsoredMessage",{channel:this.appChatsManager.getChannelInput(this.peerId.toChatId()),random_id:e.random_id}))}}},this.onBubblesMouseMove=e=>{const t=Object(Ce.a)(e.target,"bubble-content");if(t&&!this.chat.selection.isSelecting){const e=Object(Ce.a)(t,"bubble");if(!this.chat.selection.canSelectBubble(e))return void this.unhoverPrevious();let{hoverBubble:s,hoverReaction:i}=this;if(e===s)return;if(this.unhoverPrevious(),s=this.hoverBubble=e,i=this.hoverReaction,i)i.dataset.loaded&&this.setHoverVisible(i,!0);else{i=this.hoverReaction=document.createElement("div"),i.classList.add("bubble-hover-reaction");const s=document.createElement("div");s.classList.add("bubble-hover-reaction-sticker"),i.append(s),t.append(i);let n=this.chat.getMessage(+e.dataset.mid);n=this.appMessagesManager.getGroupsFirstMessage(n);const a=this.getMiddleware(()=>this.hoverReaction===i);Promise.all([this.appReactionsManager.getAvailableReactionsByMessage(n),Object(da.a)(400)]).then(([e])=>{const t=e[0];t?xs({div:s,doc:t.select_animation,width:18,height:18,needUpscale:!0,middleware:a,group:tc,withThumb:!1,needFadeIn:!1}).then(e=>{Object(ys.a)(e),a()&&(e.addEventListener("firstFrame",()=>{a()&&(i.dataset.loaded="1",this.setHoverVisible(i,!0))},{once:!0}),Object(l.b)(i,e=>{Object(c.a)(e),this.appReactionsManager.sendReaction(n,t.reaction),this.unhoverPrevious()},{listenerSetter:this.listenerSetter}))}):i.remove()})}}else this.unhoverPrevious()},this.unhoverPrevious=()=>{const{hoverBubble:e,hoverReaction:t}=this;e&&(this.setHoverVisible(t,!1),this.hoverBubble=void 0,this.hoverReaction=void 0)},this.onBubblesClick=e=>{var t;let s=e.target,i=null;try{i=Object(Ce.a)(s,"bubble")}catch(e){}if(!i)return;if(i.classList.contains("is-date")&&Object(Ce.a)(s,"bubble-content")){if(i.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const e in this.dateMessages){if(this.dateMessages[e].div===i){new Xn(new Date(+e),this.onDatePick).show();break}}return}if(!he.a&&Object(Ce.a)(s,"time"))return void this.chat.selection.toggleByElement(i);if(this.chat.selection.isSelecting&&e.isTrusted){if(i.classList.contains("service")&&void 0===i.dataset.mid)return;return Object(c.a)(e),he.a&&this.chat.selection.selectedText?void(this.chat.selection.selectedText=void 0):void this.chat.selection.toggleByElement(Object(Ce.a)(s,"grouped-item")||i)}const n=Object(Ce.a)(s,"contact");if(n)return void this.chat.appImManager.setInnerPeer({peerId:n.dataset.peerId.toPeerId()});const a=Object(Ce.a)(s,"bubble-call");if(a)return void this.chat.appImManager.callUser(this.peerId.toUserId(),a.dataset.type);const o=Object(Ce.a)(s,"spoiler");if(o){const t=Object(Ce.a)(o,"message"),s="is-spoiler-visible",i=t.classList.contains(s);i||Object(c.a)(e);const n=200,a=5e3,r=i?0:2;r&&t.classList.add("will-change");const l=t.dataset.spoilerTimeout;return null!==l&&(clearTimeout(+l),delete t.dataset.spoilerTimeout),void Object(is.a)(t,s,!0,n,()=>{t.dataset.spoilerTimeout=""+window.setTimeout(()=>{Object(is.a)(t,s,!1,n,()=>{t.classList.remove("will-change"),delete t.dataset.spoilerTimeout})},a)},r)}const r=Object(bt.a)(s,"REACTION-ELEMENT");if(r){if(Object(c.a)(e),r.classList.contains("is-inactive"))return;const t=r.parentElement,s=t.getReactionCount(r),i=t.getMessage();return void this.appReactionsManager.sendReaction(i,s.reaction)}if(Object(Ce.a)(s,"replies")){const e=+i.dataset.mid;if(this.peerId===Me.e){const t=this.chat.getMessage(e),s=this.appPeersManager.getPeerId(t.reply_to.reply_to_peer_id),i=t.reply_to.reply_to_top_id,n=t.fwd_from.saved_from_msg_id;this.chat.appImManager.openThread(s,n,i)}else{const t=this.appMessagesManager.filterMessages(this.chat.getMessage(e),e=>!!e.replies)[0],s=t.replies;s&&this.appMessagesManager.getDiscussionMessage(this.peerId,t.mid).then(e=>{this.chat.appImManager.setInnerPeer({peerId:s.channel_id.toPeerId(!0),type:"discussion",threadId:e.mid})})}return}const d=Object(Ce.a)(s,"is-via");if(d){const t=d.querySelector(".peer-title");if(s===t||Object(ii.a)(s,t)){const s=t.innerText+" ";return this.appDraftsManager.setDraft(this.peerId,this.chat.threadId,s),void Object(c.a)(e)}}const h=Object(Ce.a)(s,"peer-title")||Object(bt.a)(s,"AVATAR-ELEMENT")||Object(yt.a)(s,"data-saved-from");if(h&&h!==i){s=h||s;const e=s.dataset.peerId||s.getAttribute("peer")||s.peerId,t=s.dataset.savedFrom;if("string"==typeof e||t)if(t){const[e,s]=t.split("_");this.chat.appImManager.setInnerPeer({peerId:e.toPeerId(),lastMsgId:+s})}else{const t=e.toPeerId();t!==Me.c?this.chat.appImManager.setInnerPeer({peerId:t}):ot(T.c.format("HidAccount",!0))}return}if(i.classList.contains("sticker")&&s.parentElement.classList.contains("attachment")){const e=+i.dataset.mid,s=null===(t=this.chat.getMessage(e).media)||void 0===t?void 0:t.document;return void((null==s?void 0:s.stickerSetInput)&&new on(s.stickerSetInput).show())}const p=Object(Ce.a)(s,"document-with-thumb");if("IMG"===s.tagName&&!s.classList.contains("emoji")&&!s.classList.contains("document-thumb")||s.classList.contains("album-item")||"VIDEO"===s.tagName&&!i.classList.contains("round")||p&&!p.querySelector(".preloader-container")||s.classList.contains("canvas-thumbnail")){const t=Object(Ce.a)(s,"album-item")||Object(Ce.a)(s,"document-container"),n=+(t||i).dataset.mid,a=this.chat.getMessage(n);if(!a)return void this.log.warn("no message by messageId:",n);const o=(t||i).querySelector(".preloader-container");if(o)return Object(l.d)(o),void Object(c.a)(e);const r="webpage",d=i.classList.contains(r),h=p?e=>cc.isMediaCompatibleForDocumentViewer(e):e=>"photo"===e._||["video","gif"].includes(e.type),u=[],g=d?[n]:Object.keys(this.bubbles).map(e=>+e).filter(e=>{const t=this.chat.getMessage(e),s=this.appMessagesManager.getMediaFromMessage(t);return s&&h(s)}).sort((e,t)=>e-t);g.forEach(e=>{let t;if(p)t=".document-container";else{t=".album-item video, .album-item img, .preview video, .preview img, ",t+=this.bubbles[e].classList.contains("with-media-tail")?".bubble__media-container":".attachment video, .attachment img"}const s=Array.from(this.bubbles[e].querySelectorAll(t)),i=new Set;if(p)s.forEach(e=>{u.push({element:e.querySelector(".document-ico"),mid:+e.dataset.mid,peerId:this.peerId})});else{const t=!!this.bubbles[e].querySelector(".media-container-aspecter");s.forEach(s=>{if(t&&!Object(Ce.a)(s,"media-container-aspecter"))return;let n=Object(Ce.a)(s,"album-item");const a=n||s.parentElement;i.has(a)||(i.add(a),u.push({element:s,mid:n?+n.dataset.mid:e,peerId:this.peerId}))})}}),u.sort((e,t)=>e.mid-t.mid);let m=u.findIndex(e=>e.mid===n);return le.b&&this.log("open mediaViewer single with ids:",g,m,u),u[m]?((new cc).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:p?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:"scheduled"!==this.chat.type&&!d,isScheduled:"scheduled"===this.chat.type}).openMedia(a,u[m].element,0,!0,u.slice(0,m),u.slice(m+1)),void Object(c.a)(e)):void this.log("no target for media viewer!",s)}if(-1===["IMG","DIV","SPAN"].indexOf(s.tagName)&&(s=Object(bt.a)(s,"DIV")),-1!==["DIV","SPAN"].indexOf(s.tagName)){if(s.classList.contains("goto-original")){const e=i.dataset.savedFrom,[t,s]=e.split("_");return void this.chat.appImManager.setInnerPeer({peerId:t.toPeerId(),lastMsgId:+s})}if(s.classList.contains("forward")){const e=+i.dataset.mid,t=this.appMessagesManager.getMessageByPeer(this.peerId,e);return void new Xs({[this.peerId]:this.appMessagesManager.getMidsByMessage(t)})}let t=!1;try{t=!!Object(Ce.a)(e.target,"reply")}catch(e){}if(t&&i.classList.contains("is-reply")){const e=+i.dataset.mid;this.replyFollowHistory.push(e);const t=this.chat.getMessage(e),s=t.reply_to.reply_to_peer_id?this.appPeersManager.getPeerId(t.reply_to.reply_to_peer_id):this.peerId,n=t.reply_to.reply_to_msg_id;this.chat.appImManager.setInnerPeer({peerId:s,lastMsgId:n,type:this.chat.type,threadId:this.chat.threadId})}}},this.onScroll=(e,t)=>{var s,i;if(this.isHeavyAnimationInProgress){if(this.sliceViewportDebounced&&this.sliceViewportDebounced.clearTimeout(),this.scrolledDown&&!e)return}else this.chat.topbar.pinnedMessage&&this.chat.topbar.pinnedMessage.setCorrectIndexThrottled(this.scrollable.lastScrollDirection),this.sliceViewportDebounced&&this.sliceViewportDebounced(),this.setStickyDateManually();if(t&&t.distanceToEnd<300&&this.scrolledDown)return;const n=null!==(s=null==t?void 0:t.distanceToEnd)&&void 0!==s?s:this.scrollable.getDistanceToEnd();(0!==this.scrollable.lastScrollDirection&&n>0||t)&&(this.isScrollingTimeout?clearTimeout(this.isScrollingTimeout):this.chatInner.classList.contains("is-scrolling")||this.chatInner.classList.add("is-scrolling"),this.isScrollingTimeout=window.setTimeout(()=>{this.chatInner.classList.remove("is-scrolling"),this.isScrollingTimeout=0},1350+(null!==(i=null==t?void 0:t.duration)&&void 0!==i?i:0))),n<300&&(this.scrollable.loadedAll.bottom||this.chat.setPeerPromise||!this.peerId)?(this.bubblesContainer.classList.add("scrolled-down"),this.scrolledDown=!0):this.bubblesContainer.classList.contains("scrolled-down")&&(this.bubblesContainer.classList.remove("scrolled-down"),this.scrolledDown=!1)},this.onDatePick=e=>{const t=this.peerId;this.appMessagesManager.requestHistory(t,0,2,-1,e,this.chat.threadId).then(e=>{var s;(null===(s=null==e?void 0:e.messages)||void 0===s?void 0:s.length)?this.peerId===t&&this.chat.setMessageId(e.messages[0].mid):this.log.error("no history!")})},this.listenerSetter=new R.a,this.bubblesContainer=document.createElement("div"),this.bubblesContainer.classList.add("bubbles","scrolled-down"),this.chatInner=document.createElement("div"),this.chatInner.classList.add("bubbles-inner"),this.setScroll(),this.bubblesContainer.append(this.scrollable.container),this.log=this.chat.log,this.bubbleGroups=new Yn(this.chat),this.preloader=new ye.a({cancelable:!1}),this.lazyLoadQueue=new Z.d,this.lazyLoadQueue.queueId=++no,this.listenerSetter.add(a.a)("history_update",({storage:e,peerId:t,mid:s})=>{if(this.chat.getMessagesStorage()===e){const e=this.bubbles[s];if(!e)return;const t=this.chat.getMessage(s);if(+e.dataset.timestamp>=t.date+Ye.a.serverTimeOffset-1)return void this.bubbleGroups.changeBubbleMid(e,s);this.setBubblePosition(e,t,!1),this.scrollingToBubble&&this.scrollToEnd()}}),this.listenerSetter.add(a.a)("dialog_flush",({peerId:e})=>{this.peerId===e&&this.deleteMessagesByIds(Object.keys(this.bubbles).map(e=>+e))}),this.listenerSetter.add(a.a)("message_sent",e=>{var t,s,i,n,o,r,l,c;const{storage:d,tempId:h,tempMessage:p,mid:u}=e;if(this.chat.getMessagesStorage()!==d)return;const g=this.getMountedBubble(h,p)||this.getMountedBubble(u);if(g){const e=this.chat.getMessage(u),a=g.bubble,d=Array.from(a.querySelectorAll("reactions-element"));if(d.length&&d.forEach(t=>{t.changeMessage(e)}),e.replies){const t=a.querySelector("replies-element");t&&(t.message=e,t.init())}if(null===(t=e.media)||void 0===t?void 0:t.document){const t=a.querySelector(`.document-container[data-mid="${h}"] .document`);if(t){const a=Object(Ce.a)(t,"document-container");!(null===(n=null===(i=null===(s=p.media)||void 0===s?void 0:s.document)||void 0===i?void 0:i.thumbs)||void 0===n?void 0:n.length)&&(null===(o=e.media.document.thumbs)||void 0===o?void 0:o.length)&&Object(Ds.c)().then(()=>{const s=t.querySelector(".time"),i=Es({message:e});t.replaceWith(i),s&&i.querySelector(".document-size").append(s)}),a&&(a.dataset.mid=""+u)}}if(e.grouped_id){const e=a.querySelector(`.grouped-item[data-mid="${h}"]`)||a;e&&(e.dataset.mid=""+u)}if(null===(r=e.media)||void 0===r?void 0:r.poll){const t=a.querySelector("poll-element");if(t){const s=e.media.poll;t.message=e,t.setAttribute("poll-id",s.id),t.setAttribute("message-id",""+u)}}if(null===(l=e.media)||void 0===l?void 0:l.document){const t=a.querySelector(`audio-element[data-mid="${h}"], .document[data-doc-id="${h}"], .media-round[data-mid="${h}"]`);t&&(t instanceof De||t.classList.contains("media-round")?(t.dataset.mid=""+e.mid,delete t.dataset.isOutgoing,t.message=e,t.onLoad(!0)):t.dataset.docId=e.media.document.id)}(null===(c=e.media)||void 0===c?void 0:c.webpage)&&!a.querySelector(".web")&&Object(Ds.c)().then(()=>{this.safeRenderMessage(e,!0,!1,a,!1),this.scrollToBubbleIfLast(a)})}else this.log.warn("message_sent there is no bubble",e);const m=this.bubbles;if(m[h]){const e=m[h];m[u]=e,delete m[h],Object(Le.b)(()=>{const t=+e.dataset.mid;m[t]===e&&e.classList.contains("is-outgoing")&&(e.classList.remove("is-sending","is-outgoing"),e.classList.add(this.peerId===a.a.myId&&"scheduled"!==this.chat.type||!this.unreadOut.has(t)?"is-read":"is-sent"))}),e.dataset.mid=""+u}if(this.unreadOut.has(h)&&(this.unreadOut.delete(h),this.unreadOut.add(u)),"scheduled"===this.chat.type){(Date.now()/1e3|0)>=p.date-10&&this.deleteMessagesByIds([u])}}),this.listenerSetter.add(a.a)("message_edit",({storage:e,peerId:t,mid:s})=>{if(e!==this.chat.getMessagesStorage())return;const i=this.chat.getMessage(s),n=i.grouped_id?this.getGroupedBubble(i.grouped_id):this.getMountedBubble(s);if(!n)return;const a="scheduled"===this.chat.type,o=new Ja(this.scrollable,!0);o.save(),this.safeRenderMessage(n.message,!0,!1,n.bubble,a),o.restore(),a&&(this.messagesQueuePromise||Promise.resolve()).then(()=>{this.deleteEmptyDateGroups()})}),"scheduled"!==this.chat.type&&(this.listenerSetter.add(a.a)("missed_reactions_element",({message:e,changedResults:t})=>{if(this.peerId!==e.peerId||!e.reactions||!e.reactions.results.length)return;const s=this.getBubbleByMessage(e);if(s){if(e.grouped_id){e=this.getGroupedBubble(e.grouped_id).message}this.appendReactionsElementToBubble(s,e,t)}}),this.listenerSetter.add(a.a)("messages_reactions",e=>{let t;for(const{message:s,changedResults:i}of e){if(this.peerId!==s.peerId)return;if(!this.getBubbleByMessage(s))return;t||(t=new Ja(this.scrollable,!0),t.save());const e=s.peerId+"_"+s.mid,n=ea.get(e);if(n)for(const e of n)e.update(s,i);else a.a.dispatchEvent("missed_reactions_element",{message:s,changedResults:i})}t&&t.restore()})),this.listenerSetter.add(a.a)("album_edit",({peerId:e,groupId:t,deletedMids:s})=>{if(e!==this.peerId)return;const i=this.appMessagesManager.getMidsByAlbum(t).concat(s).find(e=>this.bubbles[e]);if(!i)return;const n=Object(li.a)(this.appMessagesManager.groupedMessagesStorage[t],"asc").pop();this.safeRenderMessage(this.chat.getMessage(n),!0,!1,this.bubbles[i],!1)}),this.listenerSetter.add(a.a)("messages_downloaded",({peerId:e,mids:t})=>{const s=this.getMiddleware();Object(Ds.c)().then(()=>{s()&&t.forEach(t=>{Object(f.a)(this.needUpdate,(s,i)=>{if(s.replyMid===t&&s.replyToPeerId===e){const{mid:e,replyMid:t}=this.needUpdate.splice(i,1)[0],n=this.bubbles[e];if(!n)return;const a=this.chat.getMessage(e);this.appMessagesManager.getMessageByPeer(s.replyToPeerId,t).deleted&&delete a.reply_to_mid,aa.setReply({chat:this.chat,bubble:n,message:a})}})})})}),he.a){const e="is-gesturing-reply",t=64,s=.75*t;let i,n,a=!1;Gs({element:this.bubblesContainer,verifyTouchTarget:t=>!(this.chat.selection.isSelecting||!this.chat.canSend())&&(i=Object(Ce.a)(t.target,"bubble"),i&&(Object(is.a)(i,e,!0,250),i.offsetLeft,n?(n.classList.remove("is-visible"),n.style.opacity=""):(n=document.createElement("span"),n.classList.add("tgico-reply_filled","bubble-gesture-reply-icon")),i.append(n)),!!i),onSwipe:(e,o)=>{a=e>=s,a&&!n.classList.contains("is-visible")&&n.classList.add("is-visible"),n.style.opacity=""+Math.min(1,e/s);const r=-Math.max(0,Math.min(t,e));i.style.transform=`translateX(${r}px)`,Object(ee.b)()},onReset:()=>{const t=i;Object(is.a)(t,e,!1,250,()=>{n.parentElement===t&&(n.classList.remove("is-visible"),n.remove())}),Object(Le.b)(()=>{if(t.style.transform="",a){const{mid:e}=t.dataset;this.chat.input.initMessageReply(+e),a=!1}})},listenerOptions:{capture:!0}})}let b;Object(l.b)(this.scrollable.container,this.onBubblesClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.scrollable.container)("mousedown",e=>{if(0!==e.button)return;const t=Object(bt.a)(e.target,"CODE");return t?(Object(c.a)(e),tt(t.textContent),void rt({langPackKey:"TextCopied"})):void 0}),le.b&&this.listenerSetter.add(this.bubblesContainer)("dblclick",e=>{const t=Object(Ce.a)(e.target,"grouped-item")||Object(Ce.a)(e.target,"bubble");if(t){const e=+t.dataset.mid;this.log("debug message:",this.chat.getMessage(e)),this.highlightBubble(t)}}),ae.e||"pinned"===this.chat.type||this.listenerSetter.add(this.bubblesContainer)("dblclick",e=>{if(this.chat.selection.isSelecting||!this.chat.canSend())return;const t=e.target,s=t.classList.contains("bubble")?t:t.classList.contains("document-selection")?t.parentElement:null;if(s&&!s.classList.contains("bubble-first")){const e=+s.dataset.mid;if(this.chat.getMessage(e).pFlags.is_outgoing)return;this.chat.input.initMessageReply(e)}}),this.stickyIntersector=new Jn(this.scrollable.container,(e,t)=>{for(const s in this.dateMessages){const i=this.dateMessages[s];if(i.container===t){const t=i.div;t.classList.toggle("is-sticky",e),e&&(this.previousStickyDate=t);break}}this.previousStickyDate}),ae.g||(this.sliceViewportDebounced=Object(lt.a)(this.sliceViewport.bind(this),3e3,!1,!0)),Object(Ds.a)(()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),b=this.getMiddleware()},()=>{this.isHeavyAnimationInProgress=!1,b&&b()&&(this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh()),b=null},this.listenerSetter)}constructPeerHelpers(){this.listenerSetter.add(a.a)("history_append",({storage:e,mid:t})=>{if(e===this.chat.getMessagesStorage()&&(this.scrollable.loadedAll.bottom?this.renderNewMessagesByIds([t],!0):this.chat.setMessageId(),a.a.settings.animationsEnabled)){const e=this.chat.gradientRenderer;e&&e.toNextPosition()}}),this.listenerSetter.add(a.a)("history_multiappend",e=>{if(!(this.peerId in e))return;const t=Array.from(e[this.peerId]).slice().sort((e,t)=>t-e);this.renderNewMessagesByIds(t)}),this.listenerSetter.add(a.a)("history_delete",({peerId:e,msgs:t})=>{e===this.peerId&&this.deleteMessagesByIds(Array.from(t))}),this.listenerSetter.add(a.a)("dialog_unread",({peerId:e})=>{e===this.peerId&&(this.chat.input.setUnreadCount(),Object(Ds.c)().then(()=>{this.updateUnreadByDialog()}))}),this.listenerSetter.add(a.a)("dialogs_multiupdate",e=>{e[this.peerId]&&this.chat.input.setUnreadCount()}),this.listenerSetter.add(a.a)("dialog_notify_settings",e=>{this.peerId===e.peerId&&this.chat.input.setUnreadCount()}),this.listenerSetter.add(a.a)("chat_update",e=>{if(this.peerId===e.toPeerId(!0)){this.chatInner.classList.contains("has-rights")!==this.chat.canSend()&&(this.finishPeerChange(),this.chat.input.finishPeerChange())}}),this.listenerSetter.add(a.a)("settings_updated",e=>{if("settings.emoji.big"===e.key){const e=this.scrollable.isScrolledDown;e||this.setMessagesQueuePromise();Object(li.a)(this.bubbles,"desc").forEach(e=>{const t=this.bubbles[e];if(t.classList.contains("can-have-big-emoji")){const s=this.chat.getMessage(e);this.safeRenderMessage(s,void 0,!1,t)}}),e?this.scrollable.setScrollTopSilently(99999):this.performHistoryResult([],!0,!1,void 0)}}),this.listenerSetter.add(a.a)("messages_views",e=>{Object(Le.b)(()=>{let t;for(const{peerId:s,views:i,mid:n}of e){if(this.peerId!==s)return;const e=this.bubbles[n];if(!e)return;const a=Array.from(e.querySelectorAll(".post-views"));if(a.length){const e=Vn(i,1);let s=!1;a.forEach(i=>{(s||i.innerHTML!==e)&&(t||(t=new Ja(this.scrollable,!0),t.save()),s=!0,i.innerHTML=e)})}}t&&t.restore()})}),this.observer=new Za({root:this.scrollable.container}),this.listenerSetter.add(a.a)("chat_changing",({to:e})=>{const t=e!==this.chat,s=()=>{this.observer.toggleObservingNew(t)};t?s():setTimeout(()=>{s()},400)}),this.sendViewCountersDebounced=Object(lt.a)(()=>{const e=[...this.viewsMids];this.viewsMids.clear(),this.appMessagesManager.incrementMessageViews(this.peerId,e)},1e3,!1,!0)}createResizeObserver(){if(!("ResizeObserver"in window)||this.resizeObserver)return;const e=this.scrollable.container;let t=0,s=!1,i=!1,n=0,a=0,o=0;const r=()=>{const r=e.offsetHeight,l=this.scrollable.isScrolledDown;r===t||i&&l||(a+=t-r),a&&this.scrollable.setScrollTopSilently(this.scrollable.scrollTop+Math.round(a)),t=r,n=0,o=0,a=0,s=!1,i=!1},l=e=>{o&&window.cancelAnimationFrame(o),o=window.requestAnimationFrame(e?r:()=>{o=window.requestAnimationFrame(r)})};(this.resizeObserver=new ResizeObserver(e=>{if(i)return void l(!1);const o=e[0].contentRect.height;if(!t)return void(t=o);const r=t-o;let c=r+a;const d=c%1;if(c-=d,!s&&(s=!0,r<0&&this.scrollable.isScrolledDown))return a=-r,i=!0,void l(!1);if(n+=c,c){const e=this.scrollable.scrollTop+c;this.scrollable.setScrollTopSilently(e)}l(!1),a=d,t=o})).observe(e)}destroyResizeObserver(){const e=this.resizeObserver;e&&(e.disconnect(),this.resizeObserver=void 0)}setReactionsHoverListeners(){this.listenerSetter.add(a.a)("context_menu_toggle",this.unhoverPrevious),this.listenerSetter.add(a.a)("overlay_toggle",this.unhoverPrevious),this.listenerSetter.add(this.chat.selection)("toggle",this.unhoverPrevious),this.listenerSetter.add(this.bubblesContainer)("mousemove",this.onBubblesMouseMove)}setHoverVisible(e,t){Object(is.a)(e,"is-visible",t,200,t?void 0:()=>{e.remove()},2)}setStickyDateManually(){}getRenderedLength(){return Object.keys(this.bubbles).length-this.skippedMids.size}onUnreadedInViewport(e,t){this.unreadedSeen.add(t),this.observer.unobserve(e,this.unreadedObserverCallback),this.unreaded.delete(e),this.readUnreaded()}readUnreaded(){if(this.readPromise)return;const e=this.getMiddleware();this.readPromise=a.a.idle.focusPromise.then(()=>{if(!e())return;let t=Math.max(...Array.from(this.unreadedSeen));if(this.scrollable.loadedAll.bottom){const e=Math.max(...Object.keys(this.bubbles).map(e=>+e));t>=e&&(t=Math.max(this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId).maxId||0,t))}this.unreaded.forEach((e,s)=>{e<=t&&this.onUnreadedInViewport(s,e)});const s=[];for(const e of this.unreadedSeen){const t=this.chat.getMessage(e);this.appMessagesManager.isMentionUnread(t)&&s.push(e)}return this.appMessagesManager.readMessages(this.peerId,s),this.unreadedSeen.clear(),le.b&&this.log("will readHistory by maxId:",t),this.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId).catch(e=>{this.log.error("readHistory err:",e),this.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId)}).finally(()=>{e()&&(this.readPromise=void 0,this.unreadedSeen.size&&this.readUnreaded())})})}constructPinnedHelpers(){this.listenerSetter.add(a.a)("peer_pinned_messages",e=>{const{peerId:t,mids:s,pinned:i}=e;t===this.peerId&&s&&(i||this.deleteMessagesByIds(s))})}constructScheduledHelpers(){const e=()=>{this.chat.topbar.setTitle(this.appMessagesManager.getScheduledMessagesStorage(this.peerId).size)};this.listenerSetter.add(a.a)("scheduled_new",({peerId:t,mid:s})=>{t===this.peerId&&(this.renderNewMessagesByIds([s]),e())}),this.listenerSetter.add(a.a)("scheduled_delete",({peerId:t,mids:s})=>{t===this.peerId&&(this.deleteMessagesByIds(s),e())})}onGoDownClick(){if(this.replyFollowHistory.length){Object(f.a)(this.replyFollowHistory,(e,t)=>{const s=this.bubbles[e];let i=!0;if(s){const e=s.getBoundingClientRect();i=St.a.height/2>e.top}else{this.chat.getMessage(e).deleted||(i=!1)}i&&this.replyFollowHistory.splice(t,1)}),this.replyFollowHistory.sort((e,t)=>t-e);const e=this.replyFollowHistory.pop();this.chat.setMessageId(e)}else this.chat.setMessageId()}getBubbleByPoint(e){let t=la(this.scrollable.container,e,"center");return t&&(t=Object(Ce.a)(t,"bubble")),t}getGroupedBubble(e){const t=this.appMessagesManager.groupedMessagesStorage[e];for(const[e]of t)if(this.bubbles[e]){const s=Math.max(...t.keys());return{bubble:this.bubbles[e],mid:+e,message:this.chat.getMessage(s)}}}getBubbleByMessage(e){if(!e.grouped_id)return this.bubbles[e.mid];const t=this.getGroupedBubble(e.grouped_id);return null==t?void 0:t.bubble}getBubbleGroupedItems(e){return Array.from(e.querySelectorAll(".grouped-item"))}getMountedBubble(e,t=this.chat.getMessage(e)){if(t.grouped_id&&this.appMessagesManager.getMidsByAlbum(t.grouped_id).length>1){const s=this.getGroupedBubble(t.grouped_id);if(s)return s.bubble=s.bubble.querySelector(`.document-container[data-mid="${e}"]`)||s.bubble,s}const s=this.bubbles[e];if(s)return{bubble:s,mid:e,message:t}}findNextMountedBubbleByMsgId(e){return this.bubbles[Object(li.a)(this.bubbles).find(t=>{var s;return!(t<e)&&!!(null===(s=this.bubbles[t])||void 0===s?void 0:s.parentElement)})]}loadMoreHistory(e,t=!1){if(!this.peerId||this.chat.setPeerPromise||this.isHeavyAnimationInProgress||e&&(this.getHistoryTopPromise||this.scrollable.loadedAll.top)||!e&&(this.getHistoryBottomPromise||this.scrollable.loadedAll.bottom))return;const s=Object.keys(this.bubbles).map(e=>+e).sort((e,t)=>e-t).filter(e=>e>0&&!this.skippedMids.has(e));if(s.length)if(e)le.b&&this.log("Will load more (up) history by id:",s[0],"maxId:",s[s.length-1],t),this.getHistory(s[0],!0,void 0,void 0,t);else{const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);if(-1!==s.indexOf(e.maxId))return void this.setLoaded("bottom",!0);le.b&&this.log("Will load more (down) history by id:",s[s.length-1],t),this.getHistory(s[s.length-1],!1,!0,void 0,t)}}setScroll(){this.scrollable=new P.b(null,"IM",300),this.setLoaded("top",!1),this.setLoaded("bottom",!1),this.scrollable.container.append(this.chatInner),this.scrollable.onAdditionalScroll=this.onScroll,this.scrollable.onScrolledTop=()=>this.loadMoreHistory(!0),this.scrollable.onScrolledBottom=()=>this.loadMoreHistory(!1),he.a}updateUnreadByDialog(){const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),t=this.peerId===a.a.myId?e.readMaxId:e.readOutboxMaxId;for(const e of this.unreadOut)if(e>0&&e<=t){const t=this.bubbles[e];if(t){if(this.unreadOut.delete(e),t.classList.contains("is-outgoing"))continue;t.classList.remove("is-sent","is-sending","is-outgoing"),t.classList.add("is-read")}}}deleteMessagesByIds(e,t=!0,s){let i=!1;e.forEach(e=>{if(!(e in this.bubbles))return;i=!0;const t=this.bubbles[e];delete this.bubbles[e],this.skippedMids.delete(e),this.firstUnreadBubble===t&&(this.firstUnreadBubble=null),this.bubbleGroups.removeBubble(t),this.observer&&(this.observer.unobserve(t,this.unreadedObserverCallback),this.unreaded.delete(t),this.observer.unobserve(t,this.viewsObserverCallback),this.viewsMids.delete(e)),t.remove(),this.emptyPlaceholderMid===e&&(this.emptyPlaceholderMid=void 0)}),i&&(this.scrollable.ignoreNextScrollEvent(),t&&this.chat.selection.isSelecting&&this.chat.selection.deleteSelectedMids(this.peerId,e),I.a.checkAnimations(!1,tc),this.deleteEmptyDateGroups(),s||this.onScroll())}setTopPadding(e=this.getMiddleware()){let t,s=!1;if(!this.isTopPaddingSet){const{clientHeight:e,scrollHeight:i}=this.scrollable.container;s=e===i,s&&(t=this.chatInner,t.style.paddingTop=e+"px",this.scrollable.setScrollTopSilently(i),this.isTopPaddingSet=!0)}return{isPaddingNeeded:s,unsetPadding:s?()=>{e()&&s&&(t.style.paddingTop="",this.isTopPaddingSet=!1)}:void 0}}renderNewMessagesByIds(e,t){if(!this.scrollable.loadedAll.bottom){const t=this.chat.setPeerPromise;if(t){const s=this.getMiddleware();t.then(()=>{s()&&this.renderNewMessagesByIds(e)})}return}this.chat.threadId&&(e=e.filter(e=>{const t=this.chat.getMessage(e).reply_to;return t&&(t.reply_to_top_id||t.reply_to_msg_id)===this.chat.threadId})),e=e.filter(e=>!this.bubbles[e]),t||(t=this.scrolledDown&&(!this.scrollingToBubble||this.scrollingToBubble===this.getLastBubble()||this.scrollingToBubble===this.chatInner));const s=this.getMiddleware(),{isPaddingNeeded:i,unsetPadding:n}=this.setTopPadding(s),a=this.performHistoryResult(e,!1,!0);t&&a.then(()=>{if(!s())return;let t;"scheduled"===this.chat.type&&(t=this.bubbles[Math.max(...e)]);const a=t?this.scrollToBubbleEnd(t):this.scrollToEnd();i&&a.then(n)})}getLastBubble(){const e=this.getLastDateGroup();if(e)return e.lastElementChild}scrollToBubble(e,t,s,i){const n=Object(Ce.a)(e,"bubble");let a;if(n&&"end"!==t&&Object(Bs.a)(n)===(this.stickyIntersector?3:1)){a=n.parentElement}const o=this.chat.input.messageInput&&this.chat.input.messageInput.classList.contains("is-changing-height")||this.chat.container.classList.contains("is-toggling-helper"),r=this.scrollable.scrollIntoViewNew({element:e,position:t,margin:4,forceDirection:s,forceDuration:i,axis:"y",getNormalSize:o?({rect:e})=>{let t=St.a.height;return t-=this.bubblesContainer.offsetTop,t-=b.b.isMobile||St.a.height<570?58:78,t}:void 0,fallbackToElementStartWhenCentering:a,startCallback:e=>{this.onScroll(!0,e)}});return s===ft.a.Static&&(this.scrollable.lastScrollPosition=this.scrollable.scrollTop),r}scrollToEnd(){return this.scrollToBubbleEnd(this.chatInner)}scrollToBubbleEnd(e){return eo(this,void 0,void 0,(function*(){if(e){this.scrollingToBubble=e;const t=this.getMiddleware();if(yield this.scrollToBubble(e,"end",void 0,void 0),!t())return;this.scrollingToBubble=void 0}}))}getLastDateGroup(){let e,t=0;for(const s in this.dateMessages){const i=this.dateMessages[s];i.firstTimestamp>t&&(e=i.container,t=i.firstTimestamp)}return e}scrollToBubbleIfLast(e){return eo(this,void 0,void 0,(function*(){if(this.getLastBubble()===e)return this.scrollToEnd()}))}highlightBubble(e){const t="highlightTimeout";e.dataset[t]&&(clearTimeout(+e.dataset[t]),e.classList.remove("is-highlighted"),e.offsetWidth),e.classList.add("is-highlighted"),e.dataset[t]=""+setTimeout(()=>{e.classList.remove("is-highlighted"),delete e.dataset[t]},2e3)}createDateBubble(e,t=new Date(1e3*e)){let s;const i=new Date;i.setHours(0,0,0,0);const n="scheduled"===this.chat.type;if(i.getTime()===t.getTime())s=Object(T.d)(n?"Chat.Date.ScheduledForToday":"Date.Today");else if(n&&2147483646===e)s=Object(T.d)("MessageScheduledUntilOnline");else{const e={day:"numeric",month:"long"};t.getFullYear()!==i.getFullYear()&&(e.year="numeric"),s=new T.c.IntlDateElement({date:t,options:e}).element,n&&(s=Object(T.d)("Chat.Date.ScheduledFor",[s]))}const a=document.createElement("div");a.className="bubble service is-date";const o=document.createElement("div");o.classList.add("bubble-content");const r=document.createElement("div");return r.classList.add("service-msg"),r.append(s),o.append(r),a.append(o),a}getDateContainerByMessage(e,t){const s=new Date(1e3*e.date);s.setHours(0,0,0);const i=s.getTime();if(!this.dateMessages[i]){const t=this.createDateBubble(e.date,s),n=this.createDateBubble(e.date,s);n.classList.add("is-fake");const a=document.createElement("section");a.className="bubbles-date-group",a.append(t,n),this.dateMessages[i]={div:t,container:a,firstTimestamp:s.getTime()};const o=Object(li.a)(this.dateMessages,"asc");let r,l=0,c=o.length;for(;l<o.length;++l){const e=o[l];if(r=this.dateMessages[e].container,i<e)break}l===c&&r&&(r=r.nextElementSibling),r?this.chatInner.insertBefore(a,r):this.chatInner.append(a),this.stickyIntersector&&this.stickyIntersector.observeStickyHeaderChanges(a)}return this.dateMessages[i]}destroy(){this.scrollable.onScrolledTop=this.scrollable.onScrolledBottom=this.scrollable.onAdditionalScroll=null,this.listenerSetter.removeAll(),this.lazyLoadQueue.clear(),this.observer&&this.observer.disconnect(),this.stickyIntersector&&this.stickyIntersector.disconnect(),delete this.lazyLoadQueue,this.observer&&delete this.observer,this.stickyIntersector&&delete this.stickyIntersector}cleanup(e=!1){this.bubbles={},this.setLoaded("top",!1),this.setLoaded("bottom",!1),Object(Pe.c)(this.scrollable.container),Object(Ds.d)(),void 0!==io&&(io=void 0),this.skippedMids.clear(),this.dateMessages={},this.bubbleGroups.cleanup(),this.unreadOut.clear(),this.needUpdate.length=0,this.lazyLoadQueue.clear(),e&&(this.scrollable.container.textContent=""),this.firstUnreadBubble=null,this.attachedUnreadBubble=!1,this.messagesQueue.length=0,this.messagesQueuePromise=null,this.getHistoryTopPromise=this.getHistoryBottomPromise=void 0,this.fetchNewPromise=void 0,this.getSponsoredMessagePromise=void 0,this.stickyIntersector&&this.stickyIntersector.disconnect(),this.observer&&(this.observer.disconnect(),this.unreaded.clear(),this.unreadedSeen.clear(),this.readPromise=void 0,this.viewsMids.clear()),this.middleware.clean(),this.onAnimateLadder=void 0,this.resolveLadderAnimation=void 0,this.emptyPlaceholderMid=void 0,this.sponsoredMessage=void 0,this.previousStickyDate=void 0,this.scrollingToBubble=void 0,this.isTopPaddingSet=!1,this.isScrollingTimeout&&(clearTimeout(this.isScrollingTimeout),this.isScrollingTimeout=0),this.bubblesContainer.classList.remove("has-sticky-dates"),this.scrollable.cancelMeasure()}setPeer(e,t,s){var i;if(!e)return this.cleanup(!0),this.peerId=e,this.preloader.detach(),null;const n=this.peerId===e,a=this.chat.type;("scheduled"===a||this.chat.isRestricted)&&(t=0);const o=this.historyStorage=this.appMessagesManager.getHistoryStorage(e,this.chat.threadId);let r="pinned"===a?this.appMessagesManager.pinnedMessages[e].maxId:null!==(i=this.historyStorage.maxId)&&void 0!==i?i:0;const l=void 0!==t;let c,d,h,p=0;if(!l)if(n||(d=this.chat.appImManager.getChatSavedPosition(this.chat)),d);else if(r){p=this.appMessagesManager.getReadMaxIdIfUnread(e,this.chat.threadId);const s=this.appMessagesManager.getDialogOnly(e);if(!p||n||s&&1===s.unread_count)t=r;else{const e=o.history.findSliceOffset(p);e&&e.slice.isEnd(ra.a.Bottom)&&(h=e.slice[e.offset-25]||e.slice[0]||p),c=!l,t=p}}const u=t!==r,{scrollable:g}=this;if(n){const e=this.getMountedBubble(t);if(e)return l?(this.scrollToBubble(e.bubble,"center"),this.highlightBubble(e.bubble),this.chat.dispatchEvent("setPeer",t,!1)):r&&!u&&(this.scrollToEnd(),this.chat.dispatchEvent("setPeer",t,!0)),void 0!==s&&this.chat.input.setStartParam(s),null}else this.peerId&&(this.lazyLoadQueue.queueId=++no,this.chat.apiManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)),this.peerId=e,this.replyFollowHistory.length=0,this.passEntities={messageEntityBotCommand:this.appPeersManager.isAnyGroup(e)||this.appUsersManager.isBot(e)};le.b&&this.log("setPeer peerId:",e,this.historyStorage,t,r);const m=null!=h?h:u||"scheduled"===a||this.chat.isRestricted?0:r;let b=0;if(n){let e=this.getBubbleByPoint("bottom");e&&(b=+e.dataset.mid),b<=0&&(b=Math.max(...Object.keys(this.bubbles).map(e=>+e)))}else this.isFirstLoad=!0,this.destroyResizeObserver();const v=this.chatInner;this.cleanup();const f=this.chatInner=document.createElement("div");n?(f.className=v.className,f.classList.remove("disable-hover","is-scrolling")):f.classList.add("bubbles-inner"),this.lazyLoadQueue.lock();const y=n||r&&u||l,w=b>0&&(!t||b<t||t<0),S=!w&&n,C=!S&&w;let L;this.willScrollOnLoad=S||C,L=d?{promise:Object(Ds.c)().then(()=>this.performHistoryResult(d.mids,!0,!1,void 0)),cached:!0}:this.getHistory(t,!0,u,m);const{promise:M,cached:E}=L;E||n||(g.container.textContent="",this.chat.finishPeerChange(l,u,t,s),this.preloader.attach(this.bubblesContainer));const P=this.getMiddleware();I.a.lockGroup(tc);const T=M.then(()=>{if(E&&(n||this.chat.finishPeerChange(l,u,t,s)),this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),g.lastScrollDirection=0,g.lastScrollPosition=0,Object(k.a)(g.container,f),I.a.unlockGroup(tc),I.a.checkAnimations(!1,tc),this.lazyLoadQueue.unlock(),d)g.setScrollTopSilently(d.top);else if(y){let e;if(S)g.setScrollTopSilently(99999);else if(C){const t=this.setTopPadding();t.isPaddingNeeded&&(e=t.unsetPadding),g.setScrollTopSilently(0)}const s=t?this.getMountedBubble(t):{bubble:this.getLastBubble()};let i,a=c&&this.firstUnreadBubble||(null==s?void 0:s.bubble);if((null==a?void 0:a.parentElement)||(a=this.findNextMountedBubbleByMsgId(t)),a){const e=this.getLastBubble(),t=c?"start":u||l||e!==a?"center":"end";i="end"===t&&e===a&&n?this.scrollToEnd():this.scrollToBubble(a,t,n?void 0:ft.a.Static),!c&&l&&this.highlightBubble(a)}e&&(i||Promise.resolve()).then(()=>{e()})}else g.setScrollTopSilently(99999);this.onRenderScrollSet(),this.onScroll();const i=this.getMiddleware(),o=Promise.all([T,Object(Ds.c)()]);o.then(()=>{g.checkForTriggers()}),this.chat.dispatchEvent("setPeer",t,!u);if(this.appPeersManager.isChannel(e)){const e=this.getMiddleware(),t=()=>{if(!e())return;const s=[];for(const e in this.bubbles){let t=this.chat.getMessage(+e);"message"===t._&&(t=this.appMessagesManager.getGroupsFirstMessage(t),s.push(t.mid))}(s.length?this.appReactionsManager.getMessagesReactions(this.peerId,s):Promise.resolve()).then(()=>{setTimeout(t,1e4)})};Promise.all([o,Object(Ds.c)(),Object(da.a)(500)]).then(()=>{t()})}const h=this.appMessagesManager.isFetchIntervalNeeded(e);if(d||h?o.then(()=>{if(i()&&(g.checkForTriggers(),h)){const t=()=>{this.fetchNewPromise=new Promise(s=>{i()&&this.appMessagesManager.isFetchIntervalNeeded(e)?this.appMessagesManager.getNewHistory(e,this.chat.threadId).then(e=>{if(!i()||!e)return void s();const n=e.history.slice.isEnd(ra.a.Bottom);g.loadedAll.bottom&&g.loadedAll.bottom!==n&&(this.setLoaded("bottom",n),this.onScroll()),setTimeout(t,3e4),s()}):s()}).finally(()=>{this.fetchNewPromise=void 0})};n?setTimeout(t,3e4):t()}}):t&&!this.bubbles[r]&&t!==r||this.setLoaded("bottom",!0),this.log("scrolledAllDown:",g.loadedAll.bottom),g.loadedAll.bottom&&r&&!this.unreaded.size&&this.onScrolledAllDown(),"chat"===a){const t=this.appMessagesManager.getDialogOnly(e);(null==t?void 0:t.pFlags.unread_mark)&&this.appMessagesManager.markDialogUnread(e,!0)}}).catch(e=>{throw this.log.error("getHistory promise error:",e),P()||this.preloader.detach(),e});return{cached:E,promise:T}}onScrolledAllDown(){if("chat"===this.chat.type||"discussion"===this.chat.type){const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);this.appMessagesManager.readHistory(this.peerId,e.maxId,this.chat.threadId,!0)}}finishPeerChange(){const e=this.appPeersManager.isChannel(this.peerId),t=this.chat.canSend();this.chatInner.classList.toggle("has-rights",t),this.bubblesContainer.classList.toggle("is-chat-input-hidden",!t),this.chatInner.classList.toggle("is-chat",this.chat.isAnyGroup()),this.chatInner.classList.toggle("is-channel",e),this.createResizeObserver()}renderMessagesQueue(e,t,s,i){return this.messagesQueue.push({message:e,bubble:t,reverse:s,promises:i}),this.setMessagesQueuePromise()}setMessagesQueuePromise(){return this.messagesQueuePromise||!this.messagesQueue.length?Promise.resolve():this.messagesQueuePromise=new Promise((e,t)=>{setTimeout(()=>{const s=this.messagesQueue.slice();this.messagesQueue.length=0;const i=s.reduce((e,{promises:t})=>(e.push(...t),e),[]);this.log("promises to call",i,s,this.isHeavyAnimationInProgress);const n=this.getMiddleware();Promise.all(i).then(()=>{if(!n())throw"setMessagesQueuePromise: peer changed!";this.messagesQueueOnRender&&this.messagesQueueOnRender(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional(),s.forEach(({message:e,bubble:t,reverse:s})=>{this.setBubblePosition(t,e,s)}),e(),this.messagesQueuePromise=null,this.messagesQueue.length&&this.setMessagesQueuePromise(),this.setUnreadDelimiter()}).catch(t)},0)})}setBubblePosition(e,t,s){if(t.pFlags.local)return void this.chatInner[t.pFlags.sponsored?"append":"prepend"](e);const i=this.getDateContainerByMessage(t,s);if("scheduled"===this.chat.type||"pinned"===this.chat.type){const s=this.stickyIntersector?3:1;let n=Array.from(i.container.children).slice(s),a=0,o=0;for(;a<n.length;++a){const e=n[a],s=+e.dataset.timestamp;if(t.date<s)break;if(t.date===s&&(o=+e.dataset.mid),o&&t.mid<o)break}let r=s+a;Ns(e,i.container,r)}else s?i.container.insertBefore(e,i.container.children[this.stickyIntersector?2:0].nextSibling):i.container.append(e);"message"===t._||t.action&&so.has(t.action._)?this.bubbleGroups.addBubble(e,t,s):e.classList.add("is-group-first","is-group-last")}getMiddleware(e){return this.middleware.get(e)}renderMessage(e,t=!1,s=!1,i=null,n=!0){var o,r,d,h,p;if(!i&&this.bubbles[e.mid])return;const u="message"===e._,g=u&&e.grouped_id,v="pinned"!==this.chat.type;if(e.deleted)return;if(g&&v){const t=this.appMessagesManager.groupedMessagesStorage[g],s=Math.max(...t.keys());if(e.mid<s)return}const f=this.peerId,y=e.fromId===a.a.myId||e.pFlags.out&&this.appPeersManager.isMegagroup(f),w=document.createElement("div");let S,C;if(w.classList.add("message"),i){const t=["is-highlighted","is-group-first","is-group-last"],s=i.className.split(" "),n=["bubble"].concat(t.filter(e=>s.includes(e)));i.className=n.join(" "),C=i.lastElementChild,C.classList.contains("bubble-content-wrapper")||(C=i.querySelector(".bubble-content-wrapper")),S=C.firstElementChild,S.innerHTML="",S.style.cssText="",C.innerHTML="",C.appendChild(S);const a=C.style.transitionDelay;C.style.cssText="",C.style.transitionDelay=a,i===this.firstUnreadBubble&&i.classList.add("is-first-unread");const o=+i.dataset.mid;+e.mid===o||(delete this.bubbles[o],this.skippedMids.delete(o))}else if(C=document.createElement("div"),C.classList.add("bubble-content-wrapper"),S=document.createElement("div"),S.classList.add("bubble-content"),(i=document.createElement("div")).classList.add("bubble"),C.appendChild(S),i.appendChild(C),!y&&!e.pFlags.out&&this.observer){(e.pFlags.unread||this.appMessagesManager.isMentionUnread(e)||void 0!==this.historyStorage.readMaxId&&this.historyStorage.readMaxId<e.mid)&&(this.observer.observe(i,this.unreadedObserverCallback),this.unreaded.set(i,e.mid))}this.bubbles[+e.mid]=i,i.dataset.mid=""+e.mid,i.dataset.peerId=""+e.peerId,i.dataset.timestamp=""+e.date;const L=[];if(!("messageService"!==e._||e.action&&so.has(e.action._))){const s=e.action;if(s){const t=s._;if(to.has(t)||T.h.hasOwnProperty(t)&&!T.h[t])return this.skippedMids.add(+e.mid),i}i.className="bubble service",S.innerHTML="";const a=document.createElement("div");return a.classList.add("service-msg"),s&&("messageActionChannelMigrateFrom"===s._?a.append(Object(T.d)("ChatMigration.From",[new wt.a({peerId:s.chat_id.toPeerId(!0)}).element])):"messageActionChatMigrateTo"===s._?a.append(Object(T.d)("ChatMigration.To",[new wt.a({peerId:s.channel_id.toPeerId(!0)}).element])):a.append(this.appMessagesManager.wrapMessageActionTextNew(e))),S.append(a),n&&(this.renderMessagesQueue(e,i,t,L),e.pFlags.is_single&&i.classList.add("is-group-last")),i}let I,M,E=u&&e.media;if(u)if((null===(o=E)||void 0===o?void 0:o.document)&&!["video","gif"].includes(E.document.type));else if(g&&v){const e=this.appMessagesManager.getAlbumText(g);I=e.message,M=e.totalEntities}else"sticker"!==(null===(d=null===(r=E)||void 0===r?void 0:r.document)||void 0===d?void 0:d.type)&&(I=e.message,M=e.totalEntities);else"messageActionPhoneCall"===e.action._&&(E={_:"messageMediaCall",action:e.action});let P=X.b.wrapRichText(I,{entities:M,passEntities:this.passEntities}),k=!0,x=!1,A=!0;if(M&&!E){let e=M.filter(e=>"messageEntityEmoji"===e._),t=I.length;if(e.reduce((e,t)=>e+t.length,0)===t&&e.length<=3&&M.length===e.length){if(a.a.settings.emoji.big){let t=this.appStickersManager.getAnimatedEmojiSticker(I);if(1===e.length&&!E&&t)E={_:"messageMediaDocument",document:t};else{let t=document.createElement("div");t.classList.add("attachment"),Object(m.a)(t,P),i.classList.add("emoji-"+e.length+"x"),S.append(t)}i.classList.add("is-message-empty","emoji-big"),x=!0,k=!1,A=!1}i.classList.add("can-have-big-emoji")}}A&&Object(m.a)(w,P);const O=aa.setTime({chatType:this.chat.type,message:e});if(w.append(O),S.prepend(w),u&&e.views){if(i.classList.add("channel-post"),!(null===(h=e.fwd_from)||void 0===h?void 0:h.saved_from_msg_id)&&"pinned"!==this.chat.type){const e=document.createElement("div");e.classList.add("bubble-beside-button","forward","tgico-forward_filled"),S.prepend(e),i.classList.add("with-beside-button")}!e.pFlags.is_outgoing&&this.observer&&this.observer.observe(i,this.viewsObserverCallback)}const j=u&&e.reply_markup;if(j&&"replyInlineMarkup"===j._&&j.rows&&j.rows.length){const t=j.rows,s=document.createElement("div");s.classList.add("reply-markup"),t.forEach(t=>{const i=t.buttons;if(!i||!i.length)return;const n=document.createElement("div");n.classList.add("reply-markup-row"),i.forEach(t=>{const s=X.b.wrapRichText(t.text,{noLinks:!0,noLinebreaks:!0});let i;switch(t._){case"keyboardButtonUrl":{const e=X.b.wrapRichText(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:t.url}]});i=Object(Zs.a)(e).firstElementChild,i.classList.add("is-link","tgico");break}case"keyboardButtonSwitchInline":i=document.createElement("button"),i.classList.add("is-switch-inline","tgico"),Object(l.b)(i,s=>{Object(c.a)(s);const i=e.viaBotId||e.fromId;let n;n=t.pFlags.same_peer?Promise.resolve(this.peerId):this.appInlineBotsManager.checkSwitchReturn(i).then(e=>e||new Promise((e,t)=>{new Xs({[this.peerId]:[]},t=>{e(t)},!0).addEventListener("close",()=>{t()})})),n.then(e=>{const s=this.peerId===e?this.chat.threadId:void 0;this.appInlineBotsManager.switchInlineQuery(e,s,i,t.query)})});break;default:i=document.createElement("button")}i.classList.add("reply-markup-button","rp"),"string"==typeof s?i.insertAdjacentHTML("beforeend",s):i.append(s),Object(te.a)(i),n.append(i)}),s.append(n)}),Object(l.b)(s,s=>{let i=s.target;if(i.classList.contains("reply-markup-button")||(i=Object(Ce.a)(i,"reply-markup-button")),!i||i.classList.contains("is-link")||i.classList.contains("is-switch-inline"))return;Object(c.a)(s);const n=Object(Bs.a)(i),a=t[Object(Bs.a)(i.parentElement)];if(!a.buttons||!a.buttons[n])return void this.log.warn("no such button",a,n,e);const o=a.buttons[n];this.appInlineBotsManager.callbackButtonClick(this.peerId,e.mid,o)}),k=!1,i.classList.add("with-reply-markup"),C.append(s)}const _=e.pFlags.is_outgoing;if(y){(e.pFlags.unread||_)&&this.unreadOut.add(e.mid);let t="";t=_?"is-sending":e.pFlags.unread||e.pFlags.is_scheduled?"is-sent":"is-read",i.classList.add(t)}_&&i.classList.add("is-outgoing");const F=u&&this.appMessagesManager.getMessageWithReplies(e),D=!!F&&e.mid>0;D&&i.classList.add("with-replies");const R=u&&e.fwd_from,B=u&&e.fwdFromId,N=y&&(!R||this.peerId!==a.a.myId);let U=S;const H=!(e.viaBotId||e.fromId!==a.a.myId&&e.pFlags.out);if(E){let t=document.createElement("div");t.classList.add("attachment"),I||i.classList.add("is-message-empty");let s=!1;switch(E._){case"messageMediaPhoto":{const s=E.photo;I||(k=!1),H&&i.classList.add("hide-name"),i.classList.add("photo");const n=this.appMessagesManager.groupedMessagesStorage[g];if(g&&1!==n.size&&v){i.classList.add("is-album","is-grouped"),Fs({groupId:g,attachmentDiv:t,middleware:this.getMiddleware(),isOut:y,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:L,autoDownload:this.chat.autoDownload});break}const a=!ae.a&&k&&!D&&!1;a&&i.classList.add("with-media-tail"),Ps({photo:s,message:e,container:t,withTail:a,isOut:N,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:L,autoDownloadSize:this.chat.autoDownload.photo});break}case"messageMediaWebPage":{s=!0;let t=E.webpage;if("webPage"!==t._)break;i.classList.add("webpage");let n=document.createElement("div");n.classList.add("web");let a,o,r=document.createElement("div");r.classList.add("quote");const l=t.photo;(l||t.document)&&(a=document.createElement("div"),a.classList.add("preview-resizer"),o=document.createElement("div"),o.classList.add("preview"),a.append(o));let c=document.createElement("div");c.classList.add("quote-text");const d=t.document;if(d)if("gif"===d.type||"video"===d.type||"round"===d.type){const t="round"===d.type?b.b.active.round:b.b.active.webpage;"round"===d.type?(i.classList.add("round"),o.classList.add("is-round")):i.classList.add("video"),Ms({doc:d,container:o,message:e,boxWidth:t.width,boxHeight:t.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:N,group:tc,loadPromises:L,autoDownload:this.chat.autoDownload})}else{const t=Es({message:e,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,loadPromises:L,sizeType:"documentName",searchContext:{useSearch:!1,peerId:this.peerId,inputFilter:{_:"inputMessagesFilterEmpty"}}});o.append(t),o.classList.add("preview-with-document"),c.classList.add("has-document")}let h;if(a&&c.append(a),t.site_name){const e=X.b.wrapRichText(t.url),s=Object(Zs.a)(e).firstElementChild;s.classList.add("webpage-name");const i=document.createElement("strong");Object(m.a)(i,X.b.wrapEmojiText(t.site_name)),s.textContent="",s.append(i),c.append(s),h=s}const p=this.appWebPagesManager.wrapTitle(t);if(p.textContent){let e=document.createElement("div");e.classList.add("title");const t=document.createElement("strong");Object(m.a)(t,p),e.append(t),c.append(e),h=e}const u=this.appWebPagesManager.wrapDescription(t);if(u.textContent){let e=document.createElement("div");e.classList.add("text"),Object(m.a)(e,u),c.append(e),h=e}if(r.append(c),l&&!d){i.classList.add("photo");const t=l.sizes[l.sizes.length-1];let s=!1;t.w===t.h&&h?(i.classList.add("is-square-photo"),s=!0,this.appPhotosManager.setAttachmentSize(l,o,48,48,!1)):t.h>t.w&&i.classList.add("is-vertical-photo"),Ps({photo:l,message:e,container:o,boxWidth:s?0:b.b.active.webpage.width,boxHeight:s?0:b.b.active.webpage.height,isOut:N,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:L,withoutPreloader:s,autoDownloadSize:this.chat.autoDownload.photo})}n.append(r),w.insertBefore(n,O);break}case"messageMediaDocument":{const n=E.document;if(n.sticker){i.classList.add("sticker"),k=!1,x=!0,n.animated&&i.classList.add("sticker-animated");const e=b.b.active,s=i.classList.contains("emoji-big")?e.emojiSticker:n.animated?e.animatedSticker:e.staticSticker;this.appPhotosManager.setAttachmentSize(n,t,s.width,s.height),S.style.minWidth=t.style.width,S.style.minHeight=t.style.height,xs({doc:n,div:t,middleware:this.getMiddleware(),lazyLoadQueue:this.lazyLoadQueue,group:tc,play:!0,loop:!0,emoji:i.classList.contains("emoji-big")?I:void 0,withThumb:!0,loadPromises:L})}else if("video"===n.type||"gif"===n.type||"round"===n.type){const s="round"===n.type;s&&(x=!0),!s&&I||(k=!1),H&&i.classList.add("hide-name"),i.classList.add(s?"round":"video");const a=this.appMessagesManager.groupedMessagesStorage[g];if(g&&1!==a.size&&v)i.classList.add("is-album","is-grouped"),Fs({groupId:g,attachmentDiv:t,middleware:this.getMiddleware(),isOut:y,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:L,autoDownload:this.chat.autoDownload});else{const a=!ae.a&&!ae.b&&!s&&k&&!D&&!1;a&&i.classList.add("with-media-tail"),Ms({doc:n,container:t,message:e,boxWidth:b.b.active.regular.width,boxHeight:b.b.active.regular.height,withTail:a,isOut:N,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),group:tc,loadPromises:L,autoDownload:this.chat.autoDownload,searchContext:s?{peerId:this.peerId,inputFilter:{_:"inputMessagesFilterRoundVoice"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0})}}else{const t=function({albumMustBeRenderedFull:e,message:t,bubble:s,messageDiv:i,chat:n,loadPromises:a,autoDownloadSize:o,lazyLoadQueue:r,searchContext:l,useSearch:c,sizeType:d}){let h;const p=e?n.getMidsByMid(t.mid):[t.mid];return p.forEach((e,t)=>{const s=n.getMessage(e),c=Es({message:s,loadPromises:a,autoDownloadSize:o,lazyLoadQueue:r,searchContext:l,sizeType:d}),u=document.createElement("div");u.classList.add("document-container"),u.dataset.mid=""+e,u.dataset.peerId=""+s.peerId;const g=document.createElement("div");if(g.classList.add("document-wrapper"),s.message){const e=document.createElement("div");e.classList.add("document-message");const t=X.b.wrapRichText(s.message,{entities:s.totalEntities});Object(m.a)(e,t),g.append(e)}if(p.length>1){const e=document.createElement("div");e.classList.add("document-selection"),u.append(e),u.classList.add("grouped-item"),0===t&&(h=g)}g.append(c),u.append(g),i.append(u)}),p.length>1&&s.classList.add("is-multiple-documents","is-grouped"),h}({albumMustBeRenderedFull:v,message:e,bubble:i,messageDiv:w,chat:this.chat,loadPromises:L,autoDownloadSize:this.chat.autoDownload.file,lazyLoadQueue:this.lazyLoadQueue,searchContext:"voice"===n.type||"audio"===n.type?{peerId:this.peerId,inputFilter:{_:"voice"===n.type?"inputMessagesFilterRoundVoice":"inputMessagesFilterMusic"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0,sizeType:"documentName"});t&&(U=t);const a=w.lastElementChild.querySelector(".document-message, .document-size, .audio");a&&a.append(O),i.classList.remove("is-message-empty"),w.classList.add((["photo","pdf"].includes(n.type)?"document":n.type||"document")+"-message"),s=!0}break}case"messageMediaCall":{const e=E.action,t=document.createElement("div");t.classList.add("bubble-call",e.pFlags.video?"tgico-videocamera":"tgico-phone");const n=e.pFlags.video?"video":"voice";t.dataset.type=n;const a=document.createElement("div");a.classList.add("bubble-call-title"),Object(T.b)(a,N?e.pFlags.video?"CallMessageVideoOutgoing":"CallMessageOutgoing":e.pFlags.video?"CallMessageVideoIncoming":"CallMessageIncoming");const o=document.createElement("div");if(o.classList.add("bubble-call-subtitle"),void 0!==e.duration)o.append(Object(Ga.a)(e.duration));else{let t;switch(e.reason._){case"phoneCallDiscardReasonBusy":t="Call.StatusBusy";break;case"phoneCallDiscardReasonMissed":t="Chat.Service.Call.Missed";break;default:t="Chat.Service.Call.Cancelled"}o.classList.add("is-reason"),Object(T.b)(o,t)}o.classList.add("tgico","arrow-"+(void 0!==e.duration?"green":"red")),t.append(a,o),s=!0,i.classList.remove("is-message-empty"),w.classList.add("call-message"),w.append(t);break}case"messageMediaContact":{const e=E,t=document.createElement("div");t.classList.add("contact"),t.dataset.peerId=""+e.user_id,s=!0;const n=document.createElement("div");n.className="contact-details";const a=document.createElement("div");a.className="contact-name",a.append(X.b.wrapEmojiText([e.first_name,e.last_name].filter(Boolean).join(" ")));const o=document.createElement("div");o.className="contact-number",o.textContent=e.phone_number?"+"+Object(qs.a)(e.phone_number).formatted:"Unknown phone number",t.append(n),n.append(a,o);const r=new fc;r.updateWithOptions({lazyLoadQueue:this.lazyLoadQueue,peerId:e.user_id.toPeerId()}),r.classList.add("contact-avatar","avatar-54"),t.prepend(r),i.classList.remove("is-message-empty"),w.classList.add("contact-message"),w.append(t);break}case"messageMediaPoll":{i.classList.remove("is-message-empty");const t=function(e){const t=new hs;return t.message=e,t.setAttribute("peer-id",""+e.peerId),t.setAttribute("poll-id",e.media.poll.id),t.setAttribute("message-id",""+e.mid),t.render(),t}(e);w.prepend(t),w.classList.add("poll-message");break}default:i.classList.remove("is-message-empty"),w.append(Object(T.d)(T.a),O),this.log.warn("unrecognized media type:",E._,e)}s||S.append(t)}x&&i.classList.add("just-media"),this.chat.selection.isSelecting&&this.chat.selection.toggleElementCheckbox(i,!0);let z="";const V=e.fromId!==a.a.myId&&this.appPeersManager.isAnyGroup(f)||e.viaBotId||e.pFlags.sponsored;if(V||R||e.reply_to_mid){let t,s;const n=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===B;let o,r=R&&!R.from_id;if(e.viaBotId&&(s=document.createElement("span"),s.innerText="@"+this.appUsersManager.getUser(e.viaBotId).username,s.classList.add("peer-title"),i.classList.add("must-have-name")),r?(t=document.createElement("span"),Object(m.a)(t,X.b.wrapEmojiText(R.from_name)),t.classList.add("peer-title"),i.classList.add("hidden-profile")):t=new wt.a({peerId:B||e.fromId}).element,e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId&&u&&aa.setReply({chat:this.chat,bubble:i,bubbleContainer:S,message:e}),B||R)if(this.peerId===a.a.myId||n||i.classList.add("forwarded"),e.savedFrom&&(z=e.savedFrom,t.dataset.savedFrom=z),o=document.createElement("div"),t.dataset.peerId=""+B,this.peerId!==a.a.myId&&this.peerId!==Me.e&&!n||x){const e=[t];x&&e.unshift(document.createElement("br")),o.append(Object(T.d)("ForwardedFrom",[e]))}else o.style.color=this.appPeersManager.getPeerColorById(B,!1),o.append(t);else if(!e.viaBotId)if(!x&&V){o=document.createElement("div"),o.append(t);const s=null===(p=this.appPeersManager.getPeer(e.fromId))||void 0===p?void 0:p.pFlags;s&&(s.scam||s.fake)&&o.append(Vt(s.scam)),y||(o.style.color=this.appPeersManager.getPeerColorById(e.fromId,!1)),o.dataset.peerId=""+e.fromId}else i.classList.add("hide-name");if(e.viaBotId){o?o.append(" "):o=document.createElement("div");const e=document.createElement("span");e.append(Object(T.d)("ViaBot")," ",s),e.classList.add("is-via"),o.append(e)}o&&(o.classList.add("name"),U.append(o));if(this.chat.isAnyGroup()&&!N){let t=new fc;t.classList.add("user-avatar","avatar-40"),t.updateWithOptions({lazyLoadQueue:this.lazyLoadQueue,peerId:(R&&(this.peerId===a.a.myId||this.peerId===Me.e)||n?B:e.fromId)||Me.c,peerTitle:!B&&R&&R.from_name?R.from_name:void 0,loadPromises:L}),C.append(t)}}else i.classList.add("hide-name");"pinned"===this.chat.type&&(z=`${this.chat.peerId}_${e.mid}`);if(F&&F.mid===this.chat.threadId&&i.classList.add("is-thread-starter","is-group-last"),z&&("pinned"===this.chat.type||R.saved_from_msg_id)&&this.peerId!==Me.e){const e=document.createElement("div");e.classList.add("bubble-beside-button","goto-original","tgico-arrow_next"),S.append(e),i.dataset.savedFrom=z,i.classList.add("with-beside-button")}if(i.classList.add(N?"is-out":"is-in"),n&&this.renderMessagesQueue(e,i,t,L),D){aa.renderReplies({bubble:i,bubbleContainer:S,message:F,messageDiv:w,loadPromises:L,lazyLoadQueue:this.lazyLoadQueue})&&(k=!0)}return u&&this.appendReactionsElementToBubble(i,e),k&&(i.classList.add("can-have-tail"),S.append(oo())),i}appendReactionsElementToBubble(e,t,s){if(this.peerId.isUser())return;const i=this.appMessagesManager.getGroupsFirstMessage(t);if(!i.reactions||!i.reactions.results.length)return;const n=new ta;if(n.init(i,"block"),n.render(s),e.classList.contains("is-message-empty"))e.querySelector(".bubble-content-wrapper").append(n);else{const s=e.querySelector(".message");if(e.classList.contains("is-multiple-documents")){const e=s.lastElementChild;let i=e.querySelector(".document-message"),a=i&&i.querySelector(".time");a||(a=aa.setTime({chatType:this.chat.type,message:t})),n.append(a),i||(i=document.createElement("div"),i.classList.add("document-message"),e.querySelector(".document-wrapper").prepend(i)),i.append(n)}else{const t=Array.from(e.querySelectorAll(".time")).pop();n.append(t),s.append(n)}}}safeRenderMessage(e,t,s,i,n){try{return this.renderMessage(e,t,s,i,n)}catch(e){this.log.error("renderMessage error:",e)}}performHistoryResult(e,t,s,i){return eo(this,void 0,void 0,(function*(){let s,n;e=e.slice(),i&&e.unshift(i),this.chatInner.parentElement&&(this.messagesQueueOnRender=()=>{if(s=new Ja(this.scrollable,t),this.getRenderedLength()&&!this.chat.setPeerPromise){const e=this.getViewportSlice();this.deleteViewportSlice(e,!0)}s.save();const e=s.getSaved();n=e.scrollHeight!==e.clientHeight}),this.needReflowScroll&&(ca(this.scrollable.container),this.needReflowScroll=!1);const a=e=>{const s="number"==typeof e?this.chat.getMessage(e):e;s.pFlags.local?this.processLocalMessageRender(s):this.safeRenderMessage(s,t,!0)},o=e.length;if(t)for(let t=0;t<o;++t)a(e[t]);else for(let t=o-1;t>=0;--t)a(e[t]);if("scheduled"!==this.chat.type){const t=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),s=t.history.first,i=t.history.last;!s.isEnd(ra.a.Bottom)||s.length&&!e.includes(s[0])||this.setLoaded("bottom",!0,!1),!i.isEnd(ra.a.Top)||i.length&&!e.includes(i[i.length-1])||this.setLoaded("top",!0,!1)}else this.setLoaded("top",!0),this.setLoaded("bottom",!0);return yield this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional()),s&&(s.restore(!(1===e.length&&!t)),this.onRenderScrollSet(s.getSaved())),!0}))}onRenderScrollSet(e){if(!this.bubblesContainer.classList.contains("has-sticky-dates")){if(!this.preloader.detached||(null!=e||(e={scrollHeight:this.scrollable.scrollHeight,clientHeight:this.scrollable.container.clientHeight}),e.scrollHeight!==e.clientHeight)){const e=this.getMiddleware(),t=()=>{e()&&this.bubblesContainer.classList.add("has-sticky-dates")};return void(this.willScrollOnLoad?t():setTimeout(t,600))}}this.willScrollOnLoad=void 0}requestHistory(e,t,s){if("chat"===this.chat.type||"discussion"===this.chat.type)return this.appMessagesManager.getHistory(this.peerId,e,t,s,this.chat.threadId);if("pinned"===this.chat.type){return this.appMessagesManager.getSearch({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:t,backLimit:s}).then(e=>({history:e.history.map(e=>e.mid)}))}return"scheduled"===this.chat.type?this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>({history:e.slice().reverse()})):void 0}animateAsLadder(e,t,s,i,n){return eo(this,void 0,void 0,(function*(){if(this.chat.setPeerPromise&&!this.resolveLadderAnimation)return void(this.resolveLadderAnimation=this.animateAsLadder.bind(this,e,t,s,i,n));if(!Object.keys(this.bubbles).length)return;let a,o=Object(li.a)(this.bubbles,"desc");s&&t.length&&(o=o.filter(e=>!t.includes(e))),a=i?n||Math.max(...o):e||Math.max(...o);const r=o.slice(o.findIndex(e=>a>e)),l=s?[]:[a],c=s?[]:o.slice(0,o.findIndex(e=>a>=e)).reverse();le.b&&this.log("getHistory: targeting mid:",a,n,e,r.map(e=>this.appMessagesIdsManager.getServerMessageId(e)),c.map(e=>this.appMessagesIdsManager.getServerMessageId(e)));const d=[];this.chatInner.classList.add("zoom-fading");const h=s?10:40,p=s?0:1,u=(e,t=0)=>{const s=Object(ie.a)();let i=0;return e.forEach((n,a)=>{if(!this.bubbles[n]||this.skippedMids.has(n))return void this.log.warn("animateAsLadder: no bubble by mid:",n);const o=this.bubbles[n].lastElementChild;if(i=(a+t||.1)*h,o.classList.add("zoom-fade"),o.style.transitionDelay=i+"ms",a===e.length-1){const e=t=>{t.target===o&&(s.resolve(),o.removeEventListener("transitionend",e))};o.addEventListener("transitionend",e)}d.push(o)}),e.length||s.resolve(),{lastMsDelay:i,animationPromise:s}},g=u(r,p),m=u(l),b=u(c,p),v=[g.animationPromise,m.animationPromise,b.animationPromise],f=[g.lastMsDelay,m.lastMsDelay,b.lastMsDelay];let y;return this.onAnimateLadder&&(yield this.onAnimateLadder()),Object(Le.b)(()=>{this.setStickyDateManually(),d.forEach(e=>{e.classList.remove("zoom-fade")})}),(r.length||l.length||c.length)&&(y=Promise.all(v),Object(Ds.b)(y,Math.max(...f)+200).then(()=>{Object(Le.b)(()=>{d.forEach(e=>{e.style.transitionDelay=""}),this.chatInner.classList.remove("zoom-fading")})})),y}))}renderEmptyPlaceholder(e,t,s,i){const n="empty-bubble-placeholder";let a,o;if(t.classList.add(n,n+"-"+e),"group"===e?a=Object(T.d)("GroupEmptyTitle1"):"saved"===e?a=Object(T.d)("ChatYourSelfTitle"):"noMessages"===e||"greeting"===e?a=Object(T.d)("NoMessages"):"noScheduledMessages"===e?a=Object(T.d)("NoScheduledMessages"):"restricted"===e&&(a=document.createElement("span"),a.innerText=this.appPeersManager.getRestrictionReasonText(this.peerId)),a.classList.add("center",n+"-title"),i.push(a),"group"===e)i.push(Object(T.d)("GroupEmptyTitle2")),o=[Object(T.d)("GroupDescription1"),Object(T.d)("GroupDescription2"),Object(T.d)("GroupDescription3"),Object(T.d)("GroupDescription4")];else if("saved"===e)o=[Object(T.d)("ChatYourSelfDescription1"),Object(T.d)("ChatYourSelfDescription2"),Object(T.d)("ChatYourSelfDescription3"),Object(T.d)("ChatYourSelfDescription4")];else if("greeting"===e){const e=Object(T.d)("NoMessagesGreetingsDescription");e.classList.add("center",n+"-subtitle"),Object(Lt.a)(this.messagesQueue,e=>e.bubble===t);const a=document.createElement("div");a.classList.add(n+"-sticker");const o=this.getMiddleware(),r=this.appStickersManager.getGreetingSticker().then(e=>{if(!o())return;const t=[];return xs({doc:e,div:a,middleware:o,lazyLoadQueue:this.lazyLoadQueue,group:tc,play:!0,loop:!0,withThumb:!0,loadPromises:t}),Object(l.b)(a,e=>{Object(c.a)(e),za.onMediaClick({target:e.target})}),Promise.all(t)});this.renderMessagesQueue(s,t,!1,[r]),i.push(e,a)}o&&(i.push(...o.map(e=>{const t=document.createElement("span");return t.classList.add(n+"-list-item"),t.append(e),t})),"group"===e?o.forEach(e=>{const t=document.createElement("span");t.classList.add("tgico-check"),e.prepend(t)}):"saved"===e&&o.forEach(e=>{const t=document.createElement("span");t.classList.add(n+"-list-bullet"),t.innerText="•",e.prepend(t)})),i.length>1&&t.classList.add("has-description"),i.forEach(e=>e.classList.add(n+"-line"))}processLocalMessageRender(e){const t=!!e.pFlags.sponsored,s=this.safeRenderMessage(e,void 0,void 0,void 0,t);s.classList.add("is-group-last","is-group-first"),t||(s.classList.add("bubble-first"),s.classList.remove("can-have-tail","is-in"));const i=[],n=this.appPeersManager.isBot(this.peerId);if(this.chat.isRestricted)this.renderEmptyPlaceholder("restricted",s,e,i);else{if(t){let t,i,n,o;s.classList.add("avoid-selection");const r=this.sponsoredMessage=e.sponsoredMessage,c=this.appPeersManager.getPeerId(r.from_id);r.channel_post?(t="OpenChannelPost",i=this.appMessagesIdsManager.generateMessageId(r.channel_post)):r.start_param||this.appUsersManager.isBot(c.toUserId())?(t="Chat.Message.ViewBot",n=r.start_param):t=this.appPeersManager.isAnyGroup(c)?"Chat.Message.ViewGroup":"Chat.Message.ViewChannel",o=r.chat_invite?()=>{new Xa(r.chat_invite_hash,r.chat_invite).show()}:r.chat_invite_hash?()=>{const e={_:$a.JOIN_CHAT,invite:r.chat_invite_hash};this.chat.appImManager.processInternalLink(e)}:()=>{a.a.dispatchEvent("history_focus",{peerId:c,mid:i,startParam:n})};const d=Object(B.a)("btn-primary btn-primary-transparent bubble-view-button",{text:t});return this.observer.observe(d,this.viewsObserverCallback),o&&Object(l.b)(d,o),void s.querySelector(".bubble-content").prepend(d)}if(n&&"message"===e._){const e=document.createElement("b");e.append(Object(T.d)("BotInfoTitle")),i.push(e,"\n\n")}else this.appPeersManager.isAnyGroup(this.peerId)&&this.appPeersManager.getPeer(this.peerId).pFlags.creator?this.renderEmptyPlaceholder("group",s,e,i):"scheduled"===this.chat.type?this.renderEmptyPlaceholder("noScheduledMessages",s,e,i):a.a.myId===this.peerId?this.renderEmptyPlaceholder("saved",s,e,i):this.appPeersManager.isUser(this.peerId)&&!n&&this.chat.canSend()&&"chat"===this.chat.type?this.renderEmptyPlaceholder("greeting",s,e,i):this.renderEmptyPlaceholder("noMessages",s,e,i)}if(i.length){s.querySelector(".message, .service-msg").prepend(...i)}const o=t?"append":"prepend";this.messagesQueueOnRenderAdditional?this.onAnimateLadder=()=>{if(this.chatInner[o](s),this.onAnimateLadder=void 0,!this.messagesQueuePromise)return Object(Le.d)()}:this.chatInner[o](s),this.emptyPlaceholderMid=e.mid}generateLocalMessageId(e=0){let t=("scheduled"===this.chat.type?-1:0)+e;const s=-Math.abs(t);return{id:s,mid:-Math.abs(this.appMessagesIdsManager.generateMessageId(s))}}generateLocalFirstMessage(e,t,s=0){const{id:i,mid:n}=this.generateLocalMessageId(s),a={_:e?"messageService":"message",date:0,id:i,mid:n,peer_id:this.appPeersManager.getOutputPeer(this.peerId),pFlags:{local:!0}};return e||(a.message=""),Object(ys.a)(a),t&&t(a),this.appMessagesManager.saveMessages([a],{storage:new Map}),a.mid=n,a}getViewportSlice(){return function({overflowElement:e,selector:t,extraSize:s}){const i=e.getBoundingClientRect(),n=Array.from(e.querySelectorAll(t)),a=[],o=[],r=[];let l=!1;for(const t of n){const s=t.getBoundingClientRect(),n=Qa(t,e,!1,s,i);let c;!!n?(l=!0,c=o):c=l?r:a,c.push({element:t,rect:s,visibleRect:n})}if(s&&o.length){const e=o[0].rect.top-s,t=o[o.length-1].rect.bottom+s;for(let t=a.length-1;t>=0;--t){const s=a[t];s.rect.top>=e&&(a.splice(t,1),o.unshift(s))}for(let e=0,s=r.length;e<s;++e){const i=r[e];i.rect.bottom<=t&&(r.splice(e--,1),--s,o.push(i))}}return{invisibleTop:a,visible:o,invisibleBottom:r}}({overflowElement:this.scrollable.container,selector:".bubbles-date-group .bubble:not(.is-date)",extraSize:2*Math.max(700,St.a.height)})}deleteViewportSlice(e,t){const{invisibleTop:s,invisibleBottom:i}=e,n=s.concat(i);if(!n.length)return;s.length&&this.setLoaded("top",!1),i.length&&this.setLoaded("bottom",!1);const a=n.map(({element:e})=>+e.dataset.mid);let o;!!s.length==!!i.length||t||(o=new Ja(this.scrollable,!!s.length),o.save()),this.deleteMessagesByIds(a,!1,!0),o?o.restore():s.length&&(this.scrollable.lastScrollPosition=this.scrollable.scrollTop)}sliceViewport(e){if(ae.g||this.isHeavyAnimationInProgress&&!e)return;const t=this.getViewportSlice();this.deleteViewportSlice(t)}setLoaded(e,t,s=!0){if(this.scrollable.loadedAll[e]!==t){if(this.scrollable.loadedAll[e]=t,"bottom"===e&&this.appPeersManager.isBroadcast(this.peerId)&&!this.chat.isRestricted){const{mid:e}=this.generateLocalMessageId(1);if(t){const t=this.getMiddleware(()=>this.scrollable.loadedAll.bottom&&!this.bubbles[e]&&this.getSponsoredMessagePromise===s),s=this.getSponsoredMessagePromise=this.chat.apiManager.invokeApiCacheable("channels.getSponsoredMessages",{channel:this.appChatsManager.getChannelInput(this.peerId.toChatId())},{cacheSeconds:300}).then(e=>{if(!t())return;this.appUsersManager.saveApiUsers(e.users),this.appChatsManager.saveApiChats(e.chats);const s=e.messages.shift();if(!s)return;e.messages.push(s);const i=this.generateLocalFirstMessage(!1,e=>{e.message=s.message,e.from_id=s.from_id,e.entities=s.entities,e.pFlags.sponsored=!0,e.sponsoredMessage=s},1);return Promise.all([this.getHistoryTopPromise,this.messagesQueuePromise]).then(()=>{if(!t())return;this.performHistoryResult([i],!1,!0)})}).finally(()=>{this.getSponsoredMessagePromise=void 0})}else this.deleteMessagesByIds([e]),this.getSponsoredMessagePromise=void 0}if("top"===e&&t&&this.appPeersManager.isBot(this.peerId)&&!this.chat.isRestricted){this.log("inject bot description");const e=this.getMiddleware();return Promise.resolve(this.appProfileManager.getProfile(this.peerId.toUserId())).then(t=>{var s;if(!e())return;if(!(null===(s=t.bot_info)||void 0===s?void 0:s.description))return void this.checkIfEmptyPlaceholderNeeded();const i=this.generateLocalFirstMessage(!1,e=>{e.message=t.bot_info.description});this.processLocalMessageRender(i)})}this.checkIfEmptyPlaceholderNeeded()}}checkIfEmptyPlaceholderNeeded(){if(this.scrollable.loadedAll.top&&this.scrollable.loadedAll.bottom&&void 0===this.emptyPlaceholderMid&&(this.chat.isRestricted||!this.appMessagesManager.getHistoryStorage(this.peerId).count||Object.keys(this.bubbles).length&&!this.getRenderedLength()||"scheduled"===this.chat.type&&!Object.keys(this.bubbles).length)){this.log("inject empty peer placeholder");const e=this.generateLocalFirstMessage(!0);return this.processLocalMessageRender(e),!0}return!1}getHistory(e=0,t=!1,s=!1,i=0,n=!1){const o=this.peerId,r=this.appPeersManager.isBroadcast(o),l=Math.min(30,St.a.height/40|0);let c=r?20:Object.keys(this.bubbles).length>0?Math.max(35,l):l;if(void 0!==io){if(!io)return{cached:!1,promise:Promise.resolve(!0)};Object.keys(this.bubbles).length>0&&--io}let d,h=0;if(s&&(h=c,t||(c=0)),i&&!s)if("pinned"===this.chat.type)d=[i];else{const t=this.appMessagesManager.getHistoryStorage(o,this.chat.threadId).history.slice;if(t.length<c&&!t.isEnd(ra.a.Both)){d=t.slice();for(let e=d.length-1;e>=0;--e){if(!this.chat.getMessage(d[e]).grouped_id)break;d.splice(e,1)}e=d[d.length-1]||e}}let p,u=this.requestHistory(e,c,h);const g=(null==d?void 0:d.length)&&u instanceof Promise,m=this.isFirstLoad&&h&&u instanceof Promise||g;g&&(p=u,u={history:d}),this.isFirstLoad=!1;const b=e=>eo(this,void 0,void 0,(function*(){if("offsetIdOffset"in e&&e.history.isEnd(ra.a.Top)){if("discussion"===this.chat.type){const t=this.appMessagesManager.threadsServiceMessagesIdsStorage[this.peerId+"_"+this.chat.threadId];t&&e.history.push(t),e.history.push(...this.chat.getMidsByMid(this.chat.threadId).reverse())}yield this.setLoaded("top",!0)}})),v=e=>Object(Ds.c)().then(()=>b(e)).then(()=>this.performHistoryResult(e.history||[],t,s,!g&&i)),f=e=>{const s=e.then(e=>(t?this.getHistoryTopPromise!==s:this.getHistoryBottomPromise!==s)?(this.log.warn("getHistory: peer changed"),Promise.reject()):n?(this.scrollable.onScroll(),!0):v(e),e=>{throw this.log.error("getHistory error:",e),e});return s};let y,w;if(u instanceof Promise)w=!1,y=f(u);else{if(n)return this.scrollable.onScroll(),null;w=!0,y=v(u)}const S=g?f(p):y;if(m&&a.a.settings.animationsEnabled){let s=g?2:1;this.messagesQueueOnRenderAdditional=()=>{if(this.log("ship went past rocks of magnets"),--s)return;this.messagesQueueOnRenderAdditional=void 0;this.animateAsLadder(i,d,g,h,e).then(()=>{setTimeout(()=>{this.loadMoreHistory(t,!0)},0)})}}else this.messagesQueueOnRenderAdditional=void 0;return t?this.getHistoryTopPromise=S:this.getHistoryBottomPromise=S,S.then(()=>{t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0}),n?null:(y.then(()=>{"chat"===this.chat.type&&setTimeout(()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)},0)}),{cached:w,promise:y})}setUnreadDelimiter(){if("chat"!==this.chat.type&&"discussion"!==this.chat.type)return;if(this.attachedUnreadBubble)return;const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);let t=this.appMessagesManager.getReadMaxIdIfUnread(this.peerId,this.chat.threadId);if(t&&(t=Object.keys(this.bubbles).filter(e=>!this.bubbles[e].classList.contains("is-out")).map(e=>+e).sort((e,t)=>e-t).find(e=>e>t),t&&this.bubbles[t])){let s=this.bubbles[t];this.firstUnreadBubble&&this.firstUnreadBubble!==s&&(this.firstUnreadBubble.classList.remove("is-first-unread"),this.firstUnreadBubble=null),t!==e.maxId&&s.classList.add("is-first-unread"),this.firstUnreadBubble=s,this.attachedUnreadBubble=!0}}deleteEmptyDateGroups(){const e=this.stickyIntersector?3:1;let t=!1;for(const s in this.dateMessages){const i=this.dateMessages[s];i.container.childElementCount===e&&(i.container.remove(),this.stickyIntersector&&this.stickyIntersector.unobserve(i.container,i.div),delete this.dateMessages[s],t=!0)}t&&(this.checkIfEmptyPlaceholderNeeded(),this.setStickyDateManually())}}function oo(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 11 20"),e.setAttributeNS(null,"width","11"),e.setAttributeNS(null,"height","20"),e.classList.add("bubble-tail");const t=document.createElementNS("http://www.w3.org/2000/svg","use");return t.setAttributeNS(null,"href","#message-tail-filled"),e.append(t),e}class ro{constructor(e,t,s,n){var r;let l,c,d,h=[],p=[];const u=o.a.canPinMessage(e),g=(a,o,r)=>{setTimeout(()=>{let a;a=s&&!t?u?i.a.unpinAllMessages(e):i.a.hidePinnedMessages(e):i.a.updatePinnedMessage(e,t,s,r,o),n&&a.then(n)},300)};if(s){let s="UnpinMessage";t?(l="UnpinMessageAlertTitle",c="Chat.Confirm.Unpin"):u?(l="Popup.Unpin.AllTitle",c="Chat.UnpinAllMessagesConfirmation",d=[""+((null===(r=i.a.pinnedMessages[e])||void 0===r?void 0:r.count)||1)]):(l="Popup.Unpin.HideTitle",c="Popup.Unpin.HideDescription",s="Popup.Unpin.Hide"),h.push({langKey:s,isDanger:!0,callback:g})}else{l="PinMessageAlertTitle";const t="PinMessage";e.isAnyChat()?(h.push({langKey:t,callback:e=>g(0,!1,!e.size)}),G.a.isBroadcast(e.toChatId())?c="PinMessageAlertChannel":(c="PinMessageAlert",p.push({text:"PinNotify",checked:!0}))):(c="PinMessageAlertChat",e===a.a.myId?h.push({langKey:t,callback:g}):(h.push({langKey:t,callback:e=>g(0,!e.size)}),p.push({text:"PinAlsoFor",textArgs:[new wt.a({peerId:e}).element],checked:!0})))}Object(ht.a)(h);new ut("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:c,descriptionLangArgs:d,buttons:h,checkboxes:p}).show()}}function lo(e=window.getSelection()){if(!e||!e.rangeCount)return!0;const t=e.getRangeAt(0);return!t.toString()||!t.START_TO_END}class co extends ut{constructor(e,t,s,n){super("popup-report-messages-confirm",{noTitle:!0,descriptionLangKey:"ReportInfo",buttons:[{langKey:"ReportChat",callback:()=>{o.isValid()&&(n&&n(),i.a.reportMessages(e,t,s,o.value).then(e=>{e&&rt({langPackKey:"ReportSentInfo"})}))}}],body:!0});const a=document.createElement("div");xs({doc:gs.a.getAnimatedEmojiSticker(co.STICKER_EMOJI),div:a,emoji:co.STICKER_EMOJI,width:100,height:100,loop:!1,play:!0}).finally(()=>{this.show()}),this.header.append(a);const o=new O.b({label:"ReportHint",maxLength:512,placeholder:"ReportChatDescription"});o.input.addEventListener("input",()=>{this.buttons[0].element.toggleAttribute("disabled",!o.isValid())}),this.body.append(o.container)}}co.STICKER_EMOJI="👮‍♀️";class ho extends ut{constructor(e,t,s){super("popup-report-messages",{titleLangKey:"ChatTitle.ReportMessages",buttons:[],body:!0}),t=t.slice();const i=[["ReportChatSpam","inputReportReasonSpam"],["ReportChatViolence","inputReportReasonViolence"],["ReportChatChild","inputReportReasonChildAbuse"],["ReportChatPornography","inputReportReasonPornography"],["ReportChatOther","inputReportReasonOther"],["ReportChatPersonalDetails","inputReportReasonPersonalDetails"],["ReportChatIllegalDrugs","inputReportReasonIllegalDrugs"]];i.forEach(e=>{const t=Object(B.a)("btn-primary btn-transparent",{text:e[0]});this.body.append(t)});const n=gs.a.preloadAnimatedEmojiSticker(co.STICKER_EMOJI);Object(l.b)(this.body,a=>{const o=Object(Ce.a)(a.target,"btn-primary"),r=i[Object(Bs.a)(o)][1];n.then(()=>{this.hide(),new co(e,t,r,s)})},{listenerSetter:this.listenerSetter}),this.body.style.margin="0 -1rem",this.buttonsEl.style.marginTop=".5rem",this.show()}}class po extends ut{constructor(){super("popup-sponsored",{titleLangKey:"Chat.Message.Sponsored.What",descriptionLangKey:"Chat.Message.Ad.Text",descriptionLangArgs:[Object(T.d)("Chat.Message.Sponsored.Link")],buttons:[{langKey:"OK",isCancel:!0},{langKey:"Chat.Message.Ad.ReadMore",callback:()=>{window.open(T.c.format("Chat.Message.Sponsored.Link",!0))},isCancel:!0}]});const e=new P.b(void 0);e.onAdditionalScroll=()=>{e.container.classList.toggle("scrolled-top",!e.scrollTop),e.container.classList.toggle("scrolled-bottom",e.isScrolledDown)},this.description.replaceWith(e.container),e.container.append(this.description),e.container.classList.add("scrolled-top"),this.show()}}var uo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class go extends ht.b{constructor(e,t){super("popup-reacted-list",null,{closable:!0,overlayClosable:!0,body:!0}),this.appMessagesManager=e,this.message=t,this.init()}init(){return uo(this,void 0,void 0,(function*(){const e=this.appMessagesManager.getGroupsFirstMessage(this.message),t=this.appMessagesManager.canViewMessageReadParticipants(e),s=new ta,i=Object.assign(Object.assign({},e),{mid:0,id:0,reactions:Object.assign(Object.assign({_:"messageReactions",results:[]},e.reactions),{pFlags:{},recent_reactions:[]})});i.reactions.results=i.reactions.results.map(e=>Object.assign(Object.assign({},e),{pFlags:{}})),s.init(i,"block"),s.render(),s.classList.add("no-stripe"),s.classList.remove("has-no-reactions"),s.append(this.btnClose),this.header.append(s);const n=document.createElement("div");n.classList.add("tabs-container"),n.dataset.animation="tabs";const a=new Map;let o=!1;if(i.reactions.results.length){const e=this.createFakeReaction("reactions",i.reactions.results.reduce((e,t)=>e+t.count,0));s.prepend(e),i.reactions.results.unshift(e.reactionCount),o=!0}let r=!1;if(t)try{const t=yield this.appMessagesManager.getMessageReadParticipants(e.peerId,e.mid);if(!t.length)throw"";const n=this.createFakeReaction("checks",t.length);s.prepend(n),i.reactions.results.unshift(n.reactionCount),r=!0}catch(e){}i.reactions.results.forEach(t=>{const s=new P.b(void 0);s.container.classList.add("tabs-tab");const i=new Kn({noShadow:!0,noDelimiter:!0}),o=_c.createChatList({dialogSize:72});_c.setListClickListener(o,()=>{this.hide()},void 0,!1,!0),i.content.append(o),s.container.append(i.container);const r="checks"!==t.reaction,l="checks"===t.reaction;let c;["checks","reactions"].includes(t.reaction)&&(t.reaction=void 0);const d=new vt({scrollable:s,getPromise:()=>uo(this,void 0,void 0,(function*(){const s=yield this.appMessagesManager.getMessageReactionsListAndReadParticipants(e,void 0,t.reaction,c,r,l);return c=s.nextOffset,s.combined.forEach(({peerId:e,reaction:t})=>{const{dom:s}=_c.addDialogNew({dialog:e,autonomous:!0,container:o,avatarSize:54,rippleEnabled:!1,meAsSaved:!1,drawStatus:!1});if(t){const e=document.createElement("div");e.classList.add("reacted-list-reaction-icon");xs({doc:jt.a.getReactionCached(t).static_icon,div:e,width:24,height:24}),s.listEl.append(e)}Object(k.a)(s.lastMessageSpan,E.a.getUserStatusString(e.toUserId()))}),!c}))});a.set(s.container,d),n.append(s.container)}),this.body.append(n);const l=Object(J.a)(s,n,(e,t)=>{if(e===s.childElementCount-1)return!1;const i=s.children[e],n=l.prevId();-1!==n&&s.children[n].setIsChosen(!1),i.setIsChosen(!0);a.get(t).load()});l(0,!1),this.show()}))}createFakeReaction(e,t){const s=new Zn;s.init("block"),s.reactionCount={_:"reactionCount",count:t,reaction:e},s.setCanRenderAvatars(!1),s.renderCounter();const i=document.createElement("div");return i.classList.add("reaction-counter","reaction-sticker-icon","tgico-"+e),s.prepend(i),s}}const mo="btn-menu-reactions-reaction",bo=!ae.g;class vo{constructor(e,t,s){this.appReactionsManager=e,this.type=t,this.onScroll=()=>{this.reactionsMap.forEach((e,t)=>{this.onScrollProcessItem(t,e)})},this.onMouseMove=e=>{var t;const s=Object(Ce.a)(e.target,mo);if(!s)return;const i=this.reactionsMap.get(s);if(!i)return;if(!(null===(t=i.appear)||void 0===t?void 0:t.paused))return;const n=i.select;n&&n.paused&&(n.autoplay=!0,n.restart())};const i=this.widthContainer=document.createElement("div");i.classList.add("btn-menu-reactions-container"),i.classList.add("btn-menu-reactions-container-"+t);const n=this.container=document.createElement("div");n.classList.add("btn-menu-reactions");const a=this.scrollable="vertical"===t?new P.b(void 0):new P.a(void 0);n.append(a.container),a.onAdditionalScroll=this.onScroll,a.setListeners(),a.container.classList.add("no-scrollbar"),["big"].forEach(e=>{const t=document.createElement("div");t.classList.add("btn-menu-reactions-bubble","btn-menu-reactions-bubble-"+e),n.append(t)}),this.reactionsMap=new Map,this.animationGroup="CHAT-MENU-REACTIONS-"+Date.now(),I.a.setOverrideIdleGroup(this.animationGroup,!0),he.a||n.addEventListener("mousemove",this.onMouseMove),Object(l.b)(n,e=>{const t=Object(Ce.a)(e.target,mo);if(!t)return;const s=this.reactionsMap.get(t);s&&this.appReactionsManager.sendReaction(this.message,s.reaction)}),i.append(n),this.middleware=null!=s?s:Object(Rs.a)()}init(e){this.message=e;const t=this.middleware.get(),s=this.appReactionsManager.getAvailableReactionsByMessage(e);Object(zt.a)(s,e=>{if(!t()||!e.length)return;e.forEach(e=>{this.renderReaction(e)});const i=()=>{this.container.classList.add("is-visible")};s instanceof Promise?Object(Le.b)(i):i()})}cleanup(){this.middleware.clean(),this.scrollable.removeListeners(),this.reactionsMap.clear(),I.a.setOverrideIdleGroup(this.animationGroup,!1),I.a.checkAnimations(!0,this.animationGroup,!0)}canUseAnimations(){return a.a.settings.animationsEnabled&&!ae.e}renderReaction(e){const t=document.createElement("div");t.classList.add(mo);const s=document.createElement("div");s.classList.add(mo+"-scale");const i=document.createElement("div");let n;i.classList.add(mo+"-appear"),this.canUseAnimations()&&(n=document.createElement("div"),n.classList.add(mo+"-select","hide"));const a={selectWrapper:n,appearWrapper:i,reaction:e.reaction};this.reactionsMap.set(t,a);const o=this.middleware.get(),r=28*(he.a?1:1.25),l={width:r,height:r,skipRatio:1,needFadeIn:!1,withThumb:!1,group:this.animationGroup,middleware:o};if(this.canUseAnimations()){let t=!0;xs(Object.assign({doc:e.appear_animation,div:i,play:!0},l)).then(e=>{Object(ys.a)(e),a.appear=e,e.addEventListener("enterFrame",o=>{e.maxFrame===o&&s.then(e=>{Object(ys.a)(e),i.classList.add("hide"),n.classList.remove("hide"),t&&(a.select=e,t=!1)},Se.a)})},Se.a);const s=xs(Object.assign({doc:e.select_animation,div:n},l)).then(e=>(Object(ys.a)(e),oe.a.waitForFirstFrame(e))).catch(Se.a)}else delete l.needFadeIn,delete l.withThumb,xs(Object.assign({doc:e.static_icon,div:i},l));s.append(i),n&&s.append(n),t.append(s),this.scrollable.append(t)}onScrollProcessItem(e,t){const s=e.firstElementChild,i=Qa(e,this.scrollable.container);let n;if(i)if(i.overflow.left||i.overflow.right){const e=Math.abs(i.rect.left-i.rect.right);n="scale("+Math.min(Math.pow(e,2)/Math.pow(36,2),1)+")"}else n="";else{if(!t.appearWrapper.classList.contains("hide")||!t.appear)return;t.select&&t.select.stop(),t.appear.stop(),t.appear.autoplay=!0,t.appearWrapper.classList.remove("hide"),t.selectWrapper.classList.add("hide"),n=""}bo&&(s.style.transform=n)}}class fo{constructor(e,t,s,i,n,a,o,r){this.attachTo=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=i,this.appPollsManager=n,this.appDocsManager=a,this.appMessagesIdsManager=o,this.appReactionsManager=r,this.onContextMenu=e=>{let t,s;try{s=Object(Ce.a)(e.target,"bubble-content-wrapper"),t=s?s.parentElement:Object(Ce.a)(e.target,"bubble")}catch(e){}if(!t||t.classList.contains("bubble-first"))return;let i=this.element;if((e instanceof MouseEvent||e.hasOwnProperty("preventDefault"))&&e.preventDefault(),i&&i.classList.contains("active"))return!1;(e instanceof MouseEvent||e.hasOwnProperty("cancelBubble"))&&(e.cancelBubble=!0);let n=+t.dataset.mid;if(!n)return;const a=this.isSponsored=n<0;if(this.isSelectable=this.chat.selection.canSelectBubble(t),this.peerId=this.chat.peerId,this.target=e.target,this.isTextSelected=!lo(),this.isAnchorTarget="A"===this.target.tagName&&("_blank"===this.target.target||this.target.classList.contains("anchor-url")),this.isUsernameTarget="A"===this.target.tagName&&this.target.classList.contains("mention"),this.chat.selection.isSelecting&&!s){if(a)return;const e=this.chat.getMidsByMid(n);if(e.length>1){const t=this.chat.selection.isMidSelected(this.peerId,n)?n:e.find(e=>this.chat.selection.isMidSelected(this.peerId,e));t&&(n=t)}}this.isOverBubble=!!s;const o=Object(Ce.a)(this.target,"grouped-item");this.isTargetAGroupedItem=!!o,this.mid=o?+o.dataset.mid:n,this.isSelected=this.chat.selection.isMidSelected(this.peerId,this.mid),this.message=this.chat.getMessage(this.mid),this.noForwards=!a&&!this.appMessagesManager.canForward(this.message),this.viewerPeerId=void 0,this.canOpenReactedList=void 0;const r=this.init();i=r.element;const{cleanup:l,destroy:c,menuPadding:d}=r,h=t.classList.contains("is-in")?"left":"right";Object(ee.e)(e.touches?e.touches[0]:e,i,h,d),Object(ee.d)(i,()=>{this.mid=0,this.peerId=void 0,this.target=null,this.viewerPeerId=void 0,this.canOpenReactedList=void 0,l(),setTimeout(()=>{c()},300)})},this.onSendScheduledClick=()=>{this.chat.selection.isSelecting?Object(l.d)(this.chat.selection.selectionSendNowBtn):new ei(this.peerId,this.chat.getMidsByMid(this.mid))},this.onReplyClick=()=>{this.chat.input.initMessageReply(this.mid)},this.onEditClick=()=>{this.chat.input.initMessageEditing(this.mid)},this.onCopyClick=()=>{if(lo()){tt((this.chat.selection.isSelecting?[...this.chat.selection.selectedMids.get(this.peerId)].sort((e,t)=>e-t):[this.mid]).reduce((e,t)=>{const s=this.chat.getMessage(t);return e+((null==s?void 0:s.message)?s.message+"\n":"")},"").trim())}else document.execCommand("copy")},this.onCopyAnchorLinkClick=()=>{tt(this.target.href)},this.onCopyLinkClick=()=>{let e;"discussion"===this.chat.type&&(e=this.appMessagesManager.getMessageByPeer(this.peerId,this.chat.threadId));const t=this.appPeersManager.getPeerUsername(e?e.fromId:this.peerId),s=this.appMessagesIdsManager.getServerMessageId(this.mid);let i,n="https://t.me/";t?(n+=t+"/"+(e?this.appMessagesIdsManager.getServerMessageId(e.fwd_from.channel_post):s),e&&(n+="?comment="+s),i="LinkCopied"):(n+="c/"+this.peerId.toChatId()+"/"+s,e&&(n+="?thread="+this.appMessagesIdsManager.getServerMessageId(e.mid)),i="LinkCopiedPrivateInfo"),ot(T.c.format(i,!0)),tt(n)},this.onPinClick=()=>{new ro(this.peerId,this.mid)},this.onUnpinClick=()=>{new ro(this.peerId,this.mid,!0)},this.onRetractVote=()=>{this.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.appPollsManager.stopPoll(this.message)},this.onForwardClick=()=>{if(this.chat.selection.isSelecting)Object(l.d)(this.chat.selection.selectionForwardBtn);else{const e=this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid);new Xs({[this.peerId]:e})}},this.onSelectClick=()=>{this.chat.selection.toggleByElement(Object(Ce.a)(this.target,"grouped-item")||Object(Ce.a)(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=()=>{this.chat.selection.isSelecting?Object(l.d)(this.chat.selection.selectionDeleteBtn):new Js(this.peerId,this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid),this.chat.type)},this.listenerSetter=new R.a,this.middleware=Object(Rs.a)(),he.a?Object(l.b)(e,e=>{if(t.selection.isSelecting)return;t.log("touchend",e);!e.target.closest([".name",".peer-title",".reply",".document","audio-element","avatar-element","a",".bubble-beside-button","replies-element","[data-saved-from]:not(.bubble)","poll-element","attachment"].join(", "))&&(Object(c.a)(e),this.onContextMenu(e))},{listenerSetter:this.chat.bubbles.listenerSetter}):Object(ee.a)(e,this.onContextMenu,this.chat.bubbles.listenerSetter)}cleanup(){this.listenerSetter.removeAll(),this.reactionsMenu&&this.reactionsMenu.cleanup(),this.middleware.clean()}destroy(){this.cleanup()}filterButtons(e){return this.isSponsored?e.filter(e=>e.isSponsored):e.filter(e=>{let t;return this.chat.selection.isSelecting&&!e.withSelection?t=!1:(this.isOverBubble||he.a,t=e.verify()),t})}setButtons(){this.buttons=[{icon:"send2",text:"MessageScheduleSend",onClick:this.onSendScheduledClick,verify:()=>"scheduled"===this.chat.type&&!this.message.pFlags.is_outgoing},{icon:"send2",text:"Message.Context.Selection.SendNow",onClick:this.onSendScheduledClick,verify:()=>"scheduled"===this.chat.type&&this.isSelected&&!this.chat.selection.selectionSendNowBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"schedule",text:"MessageScheduleEditTime",onClick:()=>{this.chat.input.scheduleSending(()=>{Object(ys.a)(this.message),this.appMessagesManager.editMessage(this.message,this.message.message,{scheduleDate:this.chat.input.scheduleDate,entities:this.message.entities}),this.chat.input.onMessageSent(!1,!1)},new Date(1e3*this.message.date))},verify:()=>"scheduled"===this.chat.type},{icon:"reply",text:"Reply",onClick:this.onReplyClick,verify:()=>this.chat.canSend()&&!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&"scheduled"!==this.chat.type},{icon:"edit",text:"Edit",onClick:this.onEditClick,verify:()=>this.appMessagesManager.canEditMessage(this.message,"text")&&!!this.chat.input.messageInput},{icon:"copy",text:"Copy",onClick:this.onCopyClick,verify:()=>!(this.noForwards||!this.message.message||this.isTextSelected||this.isAnchorTarget&&this.message.message===this.target.innerText)},{icon:"copy",text:"Chat.CopySelectedText",onClick:this.onCopyClick,verify:()=>!this.noForwards&&!!this.message.message&&this.isTextSelected},{icon:"copy",text:"Message.Context.Selection.Copy",onClick:this.onCopyClick,verify:()=>{if(!this.isSelected||this.noForwards)return!1;for(const[e,t]of this.chat.selection.selectedMids)for(const s of t)if(this.appMessagesManager.getMessageByPeer(e,s).message)return!0;return!1},notDirect:()=>!0,withSelection:!0},{icon:"copy",text:"CopyLink",onClick:this.onCopyAnchorLinkClick,verify:()=>this.isAnchorTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Username",onClick:()=>{tt(this.target.innerHTML)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{tt(this.target.innerHTML)},verify:()=>this.target.classList.contains("anchor-hashtag"),withSelection:!0},{icon:"link",text:"MessageContext.CopyMessageLink1",onClick:this.onCopyLinkClick,verify:()=>this.appPeersManager.isChannel(this.peerId)&&!this.message.pFlags.is_outgoing},{icon:"pin",text:"Message.Context.Pin",onClick:this.onPinClick,verify:()=>!this.message.pFlags.is_outgoing&&"messageService"!==this.message._&&!this.message.pFlags.pinned&&this.appPeersManager.canPinMessage(this.peerId)&&"scheduled"!==this.chat.type},{icon:"unpin",text:"Message.Context.Unpin",onClick:this.onUnpinClick,verify:()=>this.message.pFlags.pinned&&this.appPeersManager.canPinMessage(this.peerId)},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>{this.appDocsManager.saveDocFile(this.message.media.document)},verify:()=>{var e;if(this.message.pFlags.is_outgoing)return!1;const t=null===(e=this.message.media)||void 0===e?void 0:e.document;if(!t)return!1;let s=!!he.a;const i=!t.type||!["gif","video","sticker"].includes(t.type);return i&&(s=s||!!Object(Ce.a)(this.target,"document")||!!Object(Ce.a)(this.target,"audio")),i&&s}},{icon:"checkretract",text:"Chat.Poll.Unvote",onClick:this.onRetractVote,verify:()=>{var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return t&&t.chosenIndexes.length&&!t.pFlags.closed&&!t.pFlags.quiz}},{icon:"stop",text:"Chat.Poll.Stop",onClick:this.onStopPoll,verify:()=>{var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return this.appMessagesManager.canEditMessage(this.message,"poll")&&t&&!t.pFlags.closed&&!this.message.pFlags.is_outgoing}},{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>!(this.noForwards||"scheduled"===this.chat.type||this.message.pFlags.is_outgoing&&this.message.pFlags.out||"messageService"===this.message._)},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.chat.selection.selectionForwardBtn&&this.isSelected&&!this.chat.selection.selectionForwardBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"flag",text:"ReportChat",onClick:()=>{new ho(this.peerId,[this.mid])},verify:()=>!this.message.pFlags.out&&"message"===this.message._&&!this.message.pFlags.is_outgoing&&this.appPeersManager.isChannel(this.peerId),notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.message.action&&!this.isSelected&&this.isSelectable,notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,notDirect:()=>!0,withSelection:!0},{onClick:()=>{if(this.viewerPeerId)this.chat.appImManager.setInnerPeer({peerId:this.viewerPeerId});else{if(!this.canOpenReactedList)return!1;new go(this.appMessagesManager,this.message)}},verify:()=>{var e,t;return!this.peerId.isUser()&&(!!(null===(t=null===(e=this.message.reactions)||void 0===e?void 0:e.recent_reactions)||void 0===t?void 0:t.length)||this.appMessagesManager.canViewMessageReadParticipants(this.message))},notDirect:()=>!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.appMessagesManager.canDeleteMessage(this.message)},{icon:"delete danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.chat.selection.selectionDeleteBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"info",text:"Chat.Message.Sponsored.What",onClick:()=>{new po},verify:()=>!1,isSponsored:!0}]}init(){this.cleanup(),this.setButtons();const e=this.filterButtons(this.buttons),t=this.element=$s(e,this.listenerSetter);t.id="bubble-contextmenu",t.classList.add("contextmenu");const s=e.find(e=>!e.icon);if(s){const e=this.message.reactions,t=null==e?void 0:e.recent_reactions,i=!!(null==t?void 0:t.length),n=this.appMessagesManager.canViewMessageReadParticipants(this.message)?this.appPeersManager.getPeer(this.peerId).participants_count:void 0,a=e?e.results.reduce((e,t)=>e+t.count,0):void 0;s.element.classList.add("tgico-"+(i?"reactions":"checks"));const o=new T.c.IntlElement({key:i?void 0===n?"Chat.Context.ReactedFast":"Chat.Context.Reacted":"NobodyViewed",args:i?void 0===n?[a]:[n,n]:void 0,element:s.textElement});let r;r=i?void 0===n?Object(T.d)("Chat.Context.ReactedFast",[a]):Object(T.d)(t.length===n?"Chat.Context.ReactedFast":"Chat.Context.Reacted",[t.length,n]):Object(T.d)("Loading"),r.classList.add("btn-menu-item-text-fake"),s.element.append(r);const l=3,c=.875;o.element.style.visibility="hidden",o.element.style.paddingRight=i?c*Math.min(l,t.length)+"rem":"1rem";const d=this.middleware.get();this.appMessagesManager.getMessageReactionsListAndReadParticipants(this.message).then(e=>{if(!d())return;r&&r.remove();const a=e.combined,h=void 0===n?e.reactionsCount:i?a.filter(e=>e.reaction).length:a.length;let p;if(1===a.length)p=new wt.a({peerId:a[0].peerId,onlyFirstName:!0,dialog:!1}).element,(!i||e.readParticipants.length<=1)&&(this.viewerPeerId=a[0].peerId);else if(i){const e=h===a.length||void 0===n;p=Object(T.d)(e?"Chat.Context.ReactedFast":"Chat.Context.Reacted",e?[h]:[h,a.length])}else a.length?p=Object(T.d)("MessageSeen",[a.length]):o.element.style.visibility="";if(p&&(p.style.paddingRight=c*Math.min(l,h)+"rem",p.classList.add("btn-menu-item-text-fake"),s.element.append(p)),a.length){const e=new ns({avatarSize:24});e.render(t?t.map(e=>this.appPeersManager.getPeerId(e.peer_id)):a.map(e=>e.peerId)),s.element.append(e.container),this.canOpenReactedList=!0}})}let i,n;if("message"===this.message._&&!this.chat.selection.isSelecting&&!this.message.pFlags.is_outgoing&&!this.message.pFlags.is_scheduled){const e=ae.b||he.a?"horizontal":"vertical";n=this.reactionsMenu=new vo(this.appReactionsManager,e,this.middleware),n.init(this.appMessagesManager.getGroupsFirstMessage(this.message)),t.prepend(n.widthContainer);const s=42+8;i="vertical"===e?{top:24,left:s}:{top:s,right:36,left:24}}return this.chat.container.append(t),{element:t,cleanup:()=>{this.cleanup(),n&&n.cleanup()},destroy:()=>{t.remove()},menuPadding:i}}}var yo=s(194),wo=s.n(yo),So=s(175);class Co{constructor(e){this.sendMenuButtons=[{icon:"mute",text:"Chat.Send.WithoutSound",onClick:e.onSilentClick,verify:()=>"schedule"===this.type},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:e.onScheduleClick,verify:()=>"schedule"===this.type},{icon:"schedule",text:"Chat.Send.SetReminder",onClick:e.onScheduleClick,verify:()=>"reminder"===this.type}],this.sendMenu=$s(this.sendMenuButtons,e.listenerSetter),this.sendMenu.classList.add("menu-send",e.openSide),Object(ee.a)(e.onContextElement,t=>{e.onOpen&&!e.onOpen()||(this.sendMenuButtons.forEach(e=>{e.element.classList.toggle("hide",!e.verify())}),Object(c.a)(t),Object(ee.d)(this.sendMenu))},e.listenerSetter)}setPeerId(e){this.type=e===a.a.myId?"reminder":"schedule"}}var Lo=s(96),Io=s(117);class Mo extends ht.b{constructor(e){if(super("popup-create-poll popup-new-media",null,{closable:!0,withConfirm:"Create",body:!0}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=e=>{const t=e.target,s=Object(bt.a)(t,"LABEL"),i=Object(Io.a)(t);i||(t.parentElement.classList.add("is-filled"),s.classList.remove("hidden-widget"),s.firstElementChild.removeAttribute("disabled"));!s.nextElementSibling&&!i&&this.questions.childElementCount<10&&this.appendMoreField(),this.handleChange()},this.onDeleteClick=e=>{const t=e.target,s=Object(bt.a)(t,"LABEL"),i=Object(Bs.a)(s);this.correctAnswers&&this.correctAnswers[0][0]===i&&(this.correctAnswers=void 0),s.remove(),this.optionInputFields.splice(i,1),this.optionInputFields.forEach((e,t)=>{e.options.labelOptions.length=0,e.options.labelOptions.push(t+1);T.c.weakMap.get(e.label.firstElementChild).update()}),this.handleChange()},Object(T.b)(this.title,"NewPoll"),this.questionInputField=new O.b({placeholder:"AskAQuestion",label:"AskAQuestion",name:"question",maxLength:255}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()}),this.optionInputFields=[],"scheduled"!==this.chat.type){const e=new Co({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},openSide:"bottom-left",onContextElement:this.btnConfirm});e.setPeerId(this.chat.peerId),this.header.append(e.sendMenu)}this.header.append(this.questionInputField.container);const t=document.createElement("hr"),s=document.createElement("div");s.classList.add("caption"),Object(T.b)(s,"PollOptions"),this.questions=document.createElement("form"),this.questions.classList.add("poll-create-questions");const i=document.createElement("div");i.classList.add("poll-create-settings");const n=document.createElement("div");n.classList.add("caption"),Object(T.b)(n,"Settings"),this.chat.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new pt.a({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,i.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new pt.a({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new pt.a({text:"NewPoll.Quiz",name:"quiz"}),this.listenerSetter.add(this.multipleCheckboxField.input)("change",()=>{const e=this.multipleCheckboxField.input.checked;this.quizCheckboxField.input.toggleAttribute("disabled",e)}),this.listenerSetter.add(this.quizCheckboxField.input)("change",()=>{const e=this.quizCheckboxField.input.checked;Array.from(this.questions.children).map(t=>{t.classList.toggle("radio-field",e)}),e||(this.correctAnswers=void 0,this.quizSolutionField.setValueSilently("")),a.forEach(t=>t.classList.toggle("hide",!e)),this.multipleCheckboxField.input.toggleAttribute("disabled",e),this.handleChange()}),i.append(this.multipleCheckboxField.label,this.quizCheckboxField.label);const a=[],o=document.createElement("div");o.classList.add("caption"),Object(T.b)(o,"AccDescrQuizExplanation");const r=document.createElement("hr"),c=document.createElement("div");c.classList.add("poll-create-questions"),this.quizSolutionField=new O.b({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:200}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()});const d=document.createElement("div");d.classList.add("subtitle"),Object(T.b)(d,"AddAnExplanationInfo"),c.append(this.quizSolutionField.container,d),a.push(r,o,c),a.forEach(e=>e.classList.add("hide")),this.body.parentElement.insertBefore(t,this.body),this.body.append(s,this.questions,document.createElement("hr"),n,i,...a),Object(l.b)(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new P.b(this.body),this.appendMoreField(),this.onEscape=()=>!this.getFilledAnswers().length,this.handleChange()}getFilledAnswers(){return Array.from(this.questions.children).map((e,t)=>{const s=e.querySelector(".input-field-input");return s instanceof HTMLInputElement?s.value:Object(Lo.a)(s,!1).value}).filter(e=>!!e.trim())}validate(){var e;const t=this.questionInputField.value;if(!t)return!1;if(t.length>255)return!1;if(this.quizCheckboxField.input.checked&&!(null===(e=this.correctAnswers)||void 0===e?void 0:e.length))return!1;const s=this.getFilledAnswers();if(s.length<2)return!1;if(s.find(e=>e.length>100))return!1;const{value:i}=Object(Lo.a)(this.quizSolutionField.input,!1);return!(i.length>200)}handleChange(){const e=this.validate();this.btnConfirm.toggleAttribute("disabled",!e)}send(e=!1){const t=this.questionInputField.value,s=this.getFilledAnswers(),{value:i,entities:n}=Object(Lo.a)(this.quizSolutionField.input);if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending(()=>{this.send(!0)});this.hide();const a={};this.anonymousCheckboxField&&!this.anonymousCheckboxField.input.checked&&(a.public_voters=!0),this.multipleCheckboxField.input.checked&&(a.multiple_choice=!0),this.quizCheckboxField.input.checked&&(a.quiz=!0);const o={_:"poll",pFlags:a,question:t,answers:s.map((e,t)=>({_:"pollAnswer",text:e,option:new Uint8Array([t])})),id:void 0},r=this.chat.appPollsManager.getInputMediaPoll(o,this.correctAnswers,i,n);this.chat.appMessagesManager.sendOther(this.chat.peerId,r,Object.assign({},this.chat.getMessageSendingParams())),"reply"===this.chat.input.helperType&&this.chat.input.clearHelper(),this.chat.input.onMessageSent(!1,!1)}appendMoreField(){const e=this.tempId++,t=this.questions.childElementCount+1,s=new O.b({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:100});this.listenerSetter.add(s.input)("input",this.onInput);const i=new nt({text:"",name:"question"});i.main.append(s.container),Object(l.b)(s.input,c.a,{listenerSetter:this.listenerSetter}),i.label.classList.add("hidden-widget"),i.input.disabled=!0,this.quizCheckboxField.input.checked||i.label.classList.remove("radio-field"),this.listenerSetter.add(i.input)("change",()=>{if(i.input.checked){const e=Object(Bs.a)(i.label);this.correctAnswers=[new Uint8Array([e])],this.handleChange()}});const n=document.createElement("span");n.classList.add("btn-icon","tgico-close"),s.container.append(n),Object(l.b)(n,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew({element:this.questions.lastElementChild,position:"center"}),this.optionInputFields.push(s)}}var Eo=s(120);function Po(e){const t=e.src;return fetch(t).then(e=>e.arrayBuffer()).then(e=>{const t=new Uint8Array(e);let s=0;for(let e=0,i=t.length;e<i;++e)if(33==t[e]&&249==t[e+1]&&4==t[e+2]&&0==t[e+7]){const i=t[e+5]<<8|255&t[e+4];s+=i<2?10:i}return s/1e3})}let ko;function To(){return ko}class xo extends ht.b{constructor(e,t,s){if(super("popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Modal.Send",confirmShortcutIsSendShortcut:!0,body:!0}),this.chat=e,this.files=t,this.onKeyDown=e=>{const t=e.target;if(t!==this.input){if("INPUT"===t.tagName||t.hasAttribute("contenteditable"))return;this.input.focus(),Object(Eo.a)(this.input)}},this.attachFile=e=>{const t=this.willAttach,s=this.shouldCompress(e.type),i={};i.file=e;const n=document.createElement("div");n.classList.add("popup-item"),i.itemDiv=n;const a=s?this.attachMedia(e,i,n):this.attachDocument(e,i,n);return t.sendFileDetails.push(i),a},this.willAttach={type:s,sendFileDetails:[],group:!1},Object(l.b)(this.btnConfirm,()=>this.send(),{listenerSetter:this.listenerSetter}),"scheduled"!==this.chat.type){const e=new Co({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},openSide:"bottom-left",onContextElement:this.btnConfirm,listenerSetter:this.listenerSetter});e.setPeerId(this.chat.peerId),this.header.append(e.sendMenu)}this.mediaContainer=document.createElement("div"),this.mediaContainer.classList.add("popup-photo");const i=new P.b(null);i.container.append(this.mediaContainer),this.inputField=new O.b({placeholder:"PreviewSender.CaptionPlaceholder",label:"Caption",name:"photo-caption",maxLength:a.a.config.caption_length_max}),this.input=this.inputField.input,this.inputField.value=this.wasInputValue=this.chat.input.messageInputField.input.innerHTML,this.chat.input.messageInputField.value="",this.body.append(i.container),this.container.append(this.inputField.container),this.attachFiles(),this.addEventListener("close",()=>{this.files=[],ko=void 0}),ko=this}appendDrops(e){this.body.append(e)}get type(){return this.willAttach.type}set type(e){this.willAttach.type=e}appendGroupCheckboxField(){var e;const t=this.files.length>1;t&&!this.groupCheckboxField?(this.groupCheckboxField=new pt.a({text:"PreviewSender.GroupItems",name:"group-items"}),this.container.append(...[this.groupCheckboxField.label,null===(e=this.mediaCheckboxField)||void 0===e?void 0:e.label,this.inputField.container].filter(Boolean)),this.willAttach.group=!0,this.groupCheckboxField.setValueSilently(this.willAttach.group),this.listenerSetter.add(this.groupCheckboxField.input)("change",()=>{const e=this.groupCheckboxField.checked;this.willAttach.group=e,this.attachFiles()})):this.groupCheckboxField&&this.groupCheckboxField.label.classList.toggle("hide",!t)}appendMediaCheckboxField(){var e;const t=!!this.files.find(e=>g.has(e.type));t&&!this.mediaCheckboxField?(this.mediaCheckboxField=new pt.a({text:"PreviewSender.CompressFile",name:"compress-items"}),this.container.append(...[null===(e=this.groupCheckboxField)||void 0===e?void 0:e.label,this.mediaCheckboxField.label,this.inputField.container].filter(Boolean)),this.mediaCheckboxField.setValueSilently("media"===this.willAttach.type),this.listenerSetter.add(this.mediaCheckboxField.input)("change",()=>{const e=this.mediaCheckboxField.checked;this.willAttach.type=e?"media":"document",this.attachFiles()})):this.mediaCheckboxField&&this.mediaCheckboxField.label.classList.toggle("hide",!t)}addFiles(e){const t=e.filter(e=>!this.files.find(t=>t.lastModified===e.lastModified&&t.name===e.name&&t.size===e.size));t.length&&(this.files.push(...t),this.attachFiles())}send(e=!1){if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending(()=>{this.send(!0)});let t=this.inputField.value;if(t.length>a.a.config.caption_length_max)return void ot(T.c.format("Error.PreviewSender.CaptionTooLong",!0));this.hide();const s=this.willAttach;s.isMedia="media"===s.type||void 0;const{sendFileDetails:i,isMedia:n}=s,{peerId:o,input:r}=this.chat;i.forEach(e=>{e.itemDiv=void 0});const{length:l}=i,c=this.chat.getMessageSendingParams();this.iterate(e=>{t&&e.length!==l&&(this.chat.appMessagesManager.sendText(o,t,Object.assign(Object.assign({},c),{clearDraft:!0})),t=void 0);const i=Object.assign(Object.assign({},s),{sendFileDetails:e});this.chat.appMessagesManager.sendAlbum(o,i.sendFileDetails.map(e=>e.file),Object.assign(Object.assign(Object.assign({},c),{caption:t,isMedia:n,clearDraft:!0}),i)),t=void 0}),r.replyToMsgId=this.chat.threadId,r.onMessageSent()}attachMedia(e,t,s){s.classList.add("popup-item-media");let i;if(e.type.startsWith("video/")){const n=Cs(),a=document.createElement("source");a.src=t.objectURL=URL.createObjectURL(e),n.autoplay=!0,n.controls=!1,n.muted=!0,n.addEventListener("timeupdate",()=>{n.pause()},{once:!0}),i=Object(pe.e)(n).then(()=>{t.width=n.videoWidth,t.height=n.videoHeight,t.duration=Math.floor(n.duration);const e=n.webkitAudioDecodedByteCount;return void 0!==e&&(t.noSound=!e),s.append(n),Object(pe.c)(n).then(e=>{t.thumb=Object.assign({url:URL.createObjectURL(e.blob)},e)})}),n.append(a)}else{const n=new Image;i=new Promise(i=>{n.onload=()=>{t.width=n.naturalWidth,t.height=n.naturalHeight,s.append(n),"image/gif"===e.type?(t.noSound=!0,Promise.all([Po(n).then(e=>{t.duration=Math.ceil(e)}),Object(pe.b)(n).then(e=>{t.thumb=Object.assign({url:URL.createObjectURL(e.blob)},e)})]).then(()=>{i()})):i()}}),n.src=t.objectURL=URL.createObjectURL(e)}return i}attachDocument(e,t,s){s.classList.add("popup-item-document");const i=e.type.startsWith("image/"),n=e.type.startsWith("audio/");(i||n||e.size<2e7)&&(t.objectURL=URL.createObjectURL(e));const a={_:"document",file:e,file_name:e.name||"",size:e.size,type:i?"photo":"doc"};if(t.objectURL){const s=ce.a.getCacheContext(a);s.url=t.objectURL,s.downloaded=e.size}const o=Es({message:{_:"message",pFlags:{is_outgoing:!0},mid:0,peerId:0,media:{_:"messageMediaDocument",document:a}}});return new Promise(e=>{const n=()=>{s.append(o),e()};if(i){const e=new Image;e.src=t.objectURL,e.onload=()=>{t.width=e.naturalWidth,t.height=e.naturalHeight,n()},e.onerror=n}else n()})}shouldCompress(e){return"media"===this.willAttach.type&&g.has(e)}onRender(){this.element.classList.contains("active")||(this.listenerSetter.add(document.body)("keydown",this.onKeyDown),this.addEventListener("close",()=>{this.wasInputValue&&(this.chat.input.messageInputField.value=this.wasInputValue)}),this.show())}setTitle(){const{willAttach:e,title:t,files:s}=this;let i;const n=[];if("document"===e.type)i="PreviewSender.SendFile",n.push(s.length);else{let e=0,t=0,a=0;s.forEach(s=>{s.type.startsWith("image/")?++e:s.type.startsWith("video/")?++t:++a}),[e,t,a].filter(e=>e>0).length>1?(i="PreviewSender.SendFile",n.push(s.length)):e?(i="PreviewSender.SendPhoto",n.push(e)):t&&(i="PreviewSender.SendVideo",n.push(t))}Object(k.a)(t,Object(T.d)(i,n))}appendMediaToContainer(e,t){if(this.shouldCompress(t.file.type)){const s=Object(Ma.a)(t.width,t.height,380,320);e.style.width=s.width+"px",e.style.height=s.height+"px"}this.mediaContainer.append(e)}iterate(e){const{sendFileDetails:t}=this.willAttach;if(!this.willAttach.group)return void t.forEach(t=>e([t]));const s=t.length;for(let i=0;i<s;){const n=t[i].file.type;let a=0;for(;a<10&&i<s;++i,++a){const e=t[i].file.type;if(this.shouldCompress(n)!==this.shouldCompress(e))break}e(t.slice(i-a,i))}}attachFiles(){const{files:e,willAttach:t,mediaContainer:s}=this;t.sendFileDetails.length=0,this.appendGroupCheckboxField(),this.appendMediaCheckboxField(),Promise.all(e.map(this.attachFile)).then(()=>{s.innerHTML="",e.length&&(this.setTitle(),this.iterate(e=>{if(this.shouldCompress(e[0].file.type)&&e.length>1){const t=document.createElement("div");t.classList.add("popup-item-album","popup-item"),t.append(...e.map(e=>e.itemDiv)),_s({container:t,items:e.map(e=>({w:e.width,h:e.height})),maxWidth:380,minWidth:100,spacing:4}),s.append(t)}else e.forEach(e=>{this.appendMediaToContainer(e.itemDiv,e)})}))}).then(()=>{this.onRender()})}}const Ao=["ArrowUp","ArrowDown"],Oo=["ArrowLeft","ArrowRight"];function jo({list:e,type:t,onSelect:s,once:i,waitForKey:n}){let a=(null==n?void 0:n.length)?new Set(n):void 0;const o=new Set("xy"===t?Ao.concat(Oo):"x"===t?Oo:Ao);let r;const d=()=>r||e.querySelector(".active")||e.firstElementChild,h=(e,s)=>{if(r===e)return;let i=!1;r&&(i=!0,r.classList.remove("active")),r=e,r&&(r.classList.add("active"),i&&m&&s&&Object(ft.b)({container:m,element:r,position:"center",forceDuration:100,axis:"x"===t?"x":"y"}))},p=(t,s)=>{let i;return i=s?t.nextElementSibling||e.firstElementChild:t.previousElementSibling||e.lastElementChild,i};let u;u="xy"===t?(t,s)=>"ArrowUp"===s||"ArrowDown"===s?((t,s)=>{const i=s?"nextElementSibling":"previousElementSibling",n=s?"firstElementChild":"lastElementChild",a=t.getBoundingClientRect();let o=t[i]||e[n];for(;o!==t;){const t=o.getBoundingClientRect();if(t.x===a.x&&t.y!==a.y)break;o=o[i]||e[n]}return o})(t,"ArrowDown"===s):p(t,"ArrowRight"===s):(e,t)=>p(e,"ArrowRight"===t||"ArrowDown"===t);let g=s=>{const i=s.key;if(o.has(i)){if(Object(c.a)(s),e.childElementCount>1){let e=d();e=u(e,i),h(e,!0)}}else("Enter"===i||"xy"!==t&&"Tab"===i)&&(Object(c.a)(s),f(d()))};const m=Object(Ce.a)(e,"scrollable");e.classList.add("navigable-list");const b=t=>{const s=Object(ii.a)(t.target,e);s&&h(s,!1)},v=t=>{Object(c.a)(t);const s=Object(ii.a)(t.target,e);s&&(h(s,!1),f(d()))},f=e=>{const t=s(e);(void 0!==t?!t:i)&&S()};let y=!1;const w=()=>{y||(y=!0,document.addEventListener("keydown",g,{capture:!0,passive:!1}),e.addEventListener("mousemove",b,{passive:!0}),Object(l.b)(e,v))},S=()=>{y&&(y=!1,document.removeEventListener("keydown",g,{capture:!0}),e.removeEventListener("mousemove",b),Object(l.c)(e,v))},C=()=>{a||h(e.firstElementChild,!1)};if(a){const e=g;g=t=>{a.has(t.key)&&(Object(c.a)(t),document.removeEventListener("keydown",g,{capture:!0}),g=e,document.addEventListener("keydown",g,{capture:!0,passive:!1}),a=void 0,C())}}else C();return w(),{attach:w,detach:S,resetTarget:C}}class _o extends D.a{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach&&this.detach();const e=this.list,{attach:t,detach:s,resetTarget:i}=jo({list:e,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.attach=t,this.detach=s,this.resetTarget=i,ae.e||this.navigationItem||(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},F.a.pushItem(this.navigationItem)),this.addEventListener("hidden",()=>{this.resetTarget=void 0,this.attach=void 0,this.detach=void 0,e.innerHTML="",s(),this.navigationItem&&(F.a.removeItem(this.navigationItem),this.navigationItem=void 0)},{once:!0})},Object(w.a)(this,e),this.container=document.createElement("div"),this.container.classList.add("autocomplete-helper","z-depth-1"),e.appendTo.append(this.container),this.attachNavigation(),this.controller&&this.controller.addHelper(this)}toggleListNavigation(e){e?this.attach&&this.attach():this.detach&&this.detach()}attachNavigation(){this.addEventListener("visible",this.onVisible)}toggle(e,t=!1,s){if(this.init)return;if(void 0===e&&(e=this.container.classList.contains("is-visible")&&!this.container.classList.contains("backwards")),this.hidden===e)return void(e||this.dispatchEvent("visible"));this.hidden=e,e?(this.navigationItem&&(F.a.removeItem(this.navigationItem),this.navigationItem=void 0),!t&&this.controller&&this.controller.hideOtherHelpers(),this.detach&&this.detach()):(this.controller&&this.controller.hideOtherHelpers(this),this.dispatchEvent("visible"));const i=this.controller||e?0:2;e&&this.dispatchEvent("hiding"),Object(is.a)(this.container,"is-visible",!e,a.a.settings.animationsEnabled&&!s?300:0,()=>{this.hidden&&this.dispatchEvent("hidden")},i)}}class Fo extends _o{constructor(e,t){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>!za.onMediaClick({target:e},!0),waitForKey:["ArrowUp","ArrowDown"]}),this.container.classList.add("stickers-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0),a.a.dispatchEvent("choosing_sticker",!0)}),this.addEventListener("hidden",()=>{this.onChangeScreen&&(b.b.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0),a.a.dispatchEvent("choosing_sticker",!1)})}checkEmoticon(e){const t=this.controller.getMiddleware();this.lazyLoadQueue&&this.lazyLoadQueue.clear(),gs.a.preloadAnimatedEmojiSticker(e),gs.a.getStickersByEmoticon(e).then(e=>{if(!t())return;this.init&&(this.init(),this.init=null);const s=this.list.cloneNode();let i;this.lazyLoadQueue.clear(),i=e.length?new Promise(t=>{const i=[];e.forEach(e=>{s.append(this.superStickerRenderer.renderSticker(e,void 0,i))}),Promise.all(i).finally(t)}):Promise.resolve(),i.then(()=>{this.list.replaceWith(s),this.list=s,this.onChangeScreen||(this.onChangeScreen=()=>{const e=this.list.childElementCount*b.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"},b.b.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!e.length),this.scrollable.scrollTop=0})})}init(){this.list=document.createElement("div"),this.list.classList.add("stickers-helper-stickers","super-stickers"),this.container.append(this.list),this.scrollable=new P.b(this.container),this.lazyLoadQueue=new Z.d,this.superStickerRenderer=new xa(this.lazyLoadQueue,tc)}}const Do=()=>{const e=new Date;return e.setHours(0,0,0,0),e},Ro=()=>{const e=new Date;return e.setFullYear(e.getFullYear()+1),e.setDate(e.getDate()-1),e};class Bo extends Xn{constructor(e,t,s){var i;if(super((i=e).getTime()>Ro().getTime()?new Date:i,t,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:Do(),maxDate:Ro(),withTime:!0,showOverflowMonths:!0,confirmShortcutIsSendShortcut:!0}),this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm),s){const e=Object(B.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"Schedule.SendWhenOnline"});this.body.append(e),Object(l.b)(e,()=>{t(2147483646),this.hide()})}}}var No=s(171),Uo=s(107);function Ho(e,t=!0){const s=[],i=[],n=window.getSelection();let a,o;if(n&&n.rangeCount){const t=n.getRangeAt(0),s=t.startOffset;if(t.startContainer&&t.startContainer==t.endContainer&&s==t.endOffset){const i=s-1,n=e.childNodes;if(t.startContainer===e&&n[i]){a=n[i],o=0;for(let e=0;e<t.endOffset;++e){const t=n[e],s=t.nodeValue||t.alt;s&&(o+=s.length)}}else a=t.startContainer,o=s}}const r=t?[]:void 0;Object(Uo.a)(e,s,i,a,o,r),i.length&&s.push(i.join(""));let l=s.join("\n");const c=l.indexOf("");return-1!=c&&(l=l.substr(0,c)+l.substr(c+1)),l=l.replace(/\u00A0/g," "),r&&X.b.combineSameEntities(r),{value:l,entities:r,caretPos:c}}class zo extends _o{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:e=>{s.onEmojiSelected(La(e),!0)}}),this.appEmojiManager=i,this.container.classList.add("emoji-helper")}init(){this.list=document.createElement("div"),this.list.classList.add("emoji-helper-emojis","super-emojis"),this.container.append(this.list),this.scrollable=new P.a(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollLeft=0},0)})}render(e,t){if(this.init){if(!e.length)return;this.init(),this.init=null}(e=e.slice(0,80)).length&&(this.list.innerHTML="",e.forEach(e=>{Ca(e,this.list,!1,!0)})),this.waitForKey=t?["ArrowUp","ArrowDown"]:void 0,this.toggle(!e.length)}checkQuery(e,t){const s=this.controller.getMiddleware();this.appEmojiManager.getBothEmojiKeywords().then(()=>{if(!s())return;const i=e.replace(/^:/,""),n=this.appEmojiManager.searchEmojis(i);this.render(n,":"!==t)})}}class Vo extends _o{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Vo.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Vo.BASE_CLASS+"-list",this.className+"-list"),this.container.append(this.list),this.scrollable=new P.b(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0)})}render(e,t){if(this.init){if(!e.length)return;this.init(),this.init=null}e.length&&(this.list.innerHTML="",e.forEach(e=>{const t=Vo.listElement({className:this.className,peerId:e.peerId,name:e.name,description:e.description});this.list.append(t)})),t||this.toggle(!e.length)}static listElement(e){const t=Vo.BASE_CLASS_LIST_ELEMENT;e.className+="-list-element";const s=document.createElement("div");s.classList.add(t,e.className),s.dataset.peerId=""+e.peerId;const i=new fc;i.classList.add("avatar-30",t+"-avatar",e.className+"-avatar"),i.updateWithOptions({isDialog:!1,peerId:e.peerId});const n=document.createElement("div");if(n.classList.add(t+"-name",e.className+"-name"),e.name?Object(m.a)(n,X.b.wrapEmojiText(e.name)):n.append(new wt.a({peerId:e.peerId,dialog:!1,onlyFirstName:!1,plainText:!1}).element),s.append(i,n),e.description){const i=document.createElement("div");i.classList.add(t+"-description",e.className+"-description"),Object(m.a)(i,X.b.wrapEmojiText(e.description)),s.append(i)}return s}}function Ko(e,t){const s=[].concat(e.bot_info);let i;void 0!==t&&(i=new ua.a({ignoreCase:!0}));const n=new Map;let a;if(s.forEach(e=>{e.commands.forEach((t,s)=>{const a="/"+t.command;n.set(t.command,{peerId:e.user_id.toPeerId(!1),command:t.command,name:a,description:t.description,index:s}),i&&i.indexObject(t.command,a)})}),i){const e=i.search(t);a=Array.from(e).map(e=>n.get(e))}else a=[...n.values()];return a=a.sort((e,t)=>n.get(e.command).index-n.get(t.command).index),a}Vo.BASE_CLASS="autocomplete-peer-helper",Vo.BASE_CLASS_LIST_ELEMENT=Vo.BASE_CLASS+"-list-element";class Go extends Vo{constructor(e,t,s,i,n){super(e,t,"commands-helper",e=>{const t=e.querySelector(`.${Vo.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return s.getReadyToSend(()=>{s.messageInput.innerHTML=t,s.sendMessage(!0)})}),this.appProfileManager=i,this.appUsersManager=n}checkQuery(e,t){if(!this.appUsersManager.isBot(t))return!1;const s=this.controller.getMiddleware();return Promise.resolve(this.appProfileManager.getProfileByPeerId(t)).then(t=>{if(!s())return;const i=Ko(t,e);this.render(i)}),!0}}class Wo{constructor(){this.helpers=new Set,this.middleware=Object(Rs.a)()}toggleListNavigation(e){for(const t of this.helpers)t.toggleListNavigation(e)}getMiddleware(){return this.middleware.clean(),this.middleware.get()}addHelper(e){this.helpers.add(e)}hideOtherHelpers(e){this.helpers.forEach(t=>{t!==e&&t.toggle(!0,!0)}),e||this.middleware.clean()}}class qo extends Vo{constructor(e,t,s,i,n){super(e,t,"mentions-helper",e=>{const t=n.getUser(e.dataset.peerId.toUserId());let i,a="";t.username?a="@"+t.username:(a=t.first_name||t.last_name,i={_:"messageEntityMentionName",length:a.length,offset:0,user_id:t.id}),a+=" ",s.insertAtCaret(a,i)}),this.appProfileManager=i,this.appUsersManager=n}checkQuery(e,t,s){const i=e.trim();if(e.length!==i.length)return!1;const n=this.controller.getMiddleware();return this.appProfileManager.getMentions(t&&t.toChatId(),i,s).then(e=>{if(!n())return;const t=i.slice(1).toLowerCase();this.render(e.map(e=>{const s=this.appUsersManager.getUser(e);if(!s.username||s.username.toLowerCase()!==t)return{peerId:e,description:s.username?"@"+s.username:void 0}}).filter(Boolean))}),!0}}var Qo=s(32);class $o extends Na{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=e=>{const t=e.touches[0].target;Object(ii.a)(t,this.element)||t===this.btnHover||(Object(c.a)(e),this.toggle(!1))},Object(w.a)(this,e),this.element.classList.add($o.BASE_CLASS),this.element.style.display="none",this.attachButtonListener(this.btnHover,this.listenerSetter),this.listenerSetter.add(a.a)("history_reply_markup",({peerId:e})=>{this.peerId===e&&(this.checkAvailability()&&this.isActive()&&this.render(),Object(Ds.c)().then(()=>{this.checkForceReply()}))})}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",()=>{this.render(),he.a&&(this.touchListener=this.listenerSetter.add(document.body)("touchstart",this.onBodyTouchStart,{passive:!1,capture:!0}),this.listenerSetter.add(this)("close",()=>{this.listenerSetter.remove(this.touchListener)},{once:!0}))}),this.listenerSetter.add(this.element)("click",e=>{const t=Object(Ce.a)(e.target,"btn");if(!t)return;const s=t.dataset.type,{peerId:i}=this;switch(s){case"keyboardButtonRequestPhone":Mn({titleLangKey:"ShareYouPhoneNumberTitle",button:{langKey:"OK"},descriptionLangKey:"AreYouSureShareMyContactInfoBot"}).then(()=>{this.appMessagesManager.sendContact(i,a.a.myId)});break;default:this.appMessagesManager.sendText(i,t.dataset.text)}this.toggle(!1)}),super.init()}checkForceReply(){const e=this.getReplyMarkup();"replyKeyboardForceReply"!==e._||e.pFlags.hidden||e.pFlags.used||(e.pFlags.used=!0,this.chatInput.initMessageReply(e.mid))}getReplyMarkup(){var e;return null!==(e=this.appMessagesManager.getHistoryStorage(this.peerId).replyMarkup)&&void 0!==e?e:{_:"replyKeyboardHide"}}render(e=this.getReplyMarkup()){this.element.innerHTML="";for(const t of e.rows){const e=document.createElement("div");e.classList.add($o.BASE_CLASS+"-row");for(const s of t.buttons){const t=document.createElement("button");t.classList.add($o.BASE_CLASS+"-button","btn"),Object(m.a)(t,X.b.wrapEmojiText(s.text)),t.dataset.text=s.text,t.dataset.type=s._,e.append(t)}this.element.append(e)}}checkAvailability(e=this.getReplyMarkup()){var t;const s="replyKeyboardHide"===e._||!(null===(t=e.rows)||void 0===t?void 0:t.length);return this.btnHover.classList.toggle("hide",s),s&&this.toggle(!1),!s}setPeer(e){this.peerId=e,this.checkAvailability(),this.checkForceReply()}}$o.BASE_CLASS="reply-keyboard";var Yo=s(189),Xo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Jo extends _o{constructor(e,t,s,i,n){super({appendTo:e,controller:t,listType:"xy",waitForKey:["ArrowUp","ArrowDown"],onSelect:e=>{if(!e)return!1;const{peerId:t,botId:s,queryId:i}=this.list.dataset;return this.chat.input.getReadyToSend(()=>{const n=this.appInlineBotsManager.generateQId(i,e.dataset.resultId);this.appInlineBotsManager.sendInlineResult(t.toPeerId(),s,n,Object.assign(Object.assign({},this.chat.getMessageSendingParams()),{clearDraft:!0})),this.chat.input.onMessageSent(!0,!0)})}}),this.chat=s,this.appUsersManager=i,this.appInlineBotsManager=n,this._checkQuery=(e,t,s)=>Xo(this,void 0,void 0,(function*(){const i=this.controller.getMiddleware(),n=yield this.appUsersManager.resolveUsername(t);if(!i())throw"PEER_CHANGED";if("user"!==n._)throw"NOT_A_BOT";const a=this.appInlineBotsManager.getInlineResults(e,n.id,s).then(t=>{var s;if(!i())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const a=this.list.cloneNode();a.dataset.peerId=""+e,a.dataset.botId=""+n.id,a.dataset.queryId=""+t.query_id;const o=new Pa(null,"INLINE-HELPER",this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const r=[],c=!!t.pFlags.gallery;for(const e of t.results){const t=document.createElement("div");t.classList.add("inline-helper-result"),t.dataset.resultId=e.id;const n=c?void 0:document.createElement("div");if(n&&(n.classList.add("inline-helper-result-preview"),t.append(n)),a.append(t),c)t.classList.add("grid-item");else{n.classList.add("empty"),Object(m.a)(n,X.b.wrapEmojiText([...e.title.trim()][0]));const s=document.createElement("div");s.classList.add("inline-helper-result-title"),Object(m.a)(s,X.b.wrapEmojiText(e.title));const i=document.createElement("div");i.classList.add("inline-helper-result-description"),Object(m.a)(i,X.b.wrapRichText(e.description,{noCommands:!0,noLinks:!0})),t.append(s,i);const o=document.createElement("div");o.classList.add("inline-helper-separator"),a.append(o)}if("botInlineResult"===e._){if(e.thumb&&0===e.thumb.mime_type.indexOf("image/")){let s;n?(s=document.createElement("div"),n.append(s)):s=t,s.classList.add("media-container"),c&&s.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:t,load:()=>ce.a.download({dcId:4,location:{_:"inputWebFileLocation",access_hash:e.thumb.access_hash,url:e.thumb.url},size:e.thumb.size,mimeType:e.thumb.mime_type}).then(e=>{const t=new Image;t.classList.add("media-photo"),Object(Yo.a)(e).then(e=>{ks(s,t,e,!0)})})})}}else{const a=e.document||e.photo;if(["sticker","gif"].includes(null===(s=a)||void 0===s?void 0:s.type)&&c)Object(ys.a)(a),"gif"===a.type?o.add(a,t):"sticker"===a.type&&(t.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(a,t,r),2===a.sticker&&this.superStickerRenderer.observeAnimatedDiv(t));else if(a){const e=c?48:void 0;c&&t.classList.add("no-border-radius"),Ps({photo:a,container:c?t:n,boxWidth:e,boxHeight:e,middleware:i,lazyLoadQueue:this.lazyLoadQueue,loadPromises:r})}}}return Promise.all(r).then(()=>{if(!i())return void o.clear();a.classList.toggle("is-gallery",c),a.classList.toggle("super-stickers",c),this.container.classList.toggle("is-gallery",c);const s=this.list.parentElement;if(s.textContent="",t.switch_pm){const i=Object(B.a)("btn-primary btn-secondary btn-primary-transparent primary");Object(m.a)(i,X.b.wrapEmojiText(t.switch_pm.text)),Object(l.b)(i,s=>{this.appInlineBotsManager.switchToPM(e,n.id,t.switch_pm.start_param)}),s.append(i)}s.append(this.list=a),this.gifsMasonry&&this.gifsMasonry.detach(),this.gifsMasonry=o,o.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const e=this.list.childElementCount*b.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"}else this.list.style.width=""},b.b.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!t.results.length&&!t.switch_pm),this.scrollable.scrollTop=0})});return{user:n,renderPromise:a}})),this.container.classList.add("inline-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0)}),this.checkQuery=Object(lt.a)(this._checkQuery,200,!0,!0),this.addEventListener("hidden",()=>{this.onChangeScreen&&(b.b.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0)})}init(){this.list=document.createElement("div"),this.list.classList.add("inline-helper-results"),this.container.append(this.list),this.scrollable=new P.b(this.container),this.lazyLoadQueue=new Z.d,this.superStickerRenderer=new xa(this.lazyLoadQueue,"INLINE-HELPER")}}var Zo=s(31);class er extends Vo{constructor(e,t,s){super(e,void 0,"bot-commands",e=>{const s=e.querySelector(`.${Vo.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return t.getReadyToSend(()=>{t.messageInput.innerHTML=s,t.sendMessage(!0),this.toggle(!0)})}),this.chatInput=t,this.appProfileManager=s}setUserId(e,t){var s;if(this.userId!==e||!(null===(s=this.list)||void 0===s?void 0:s.childElementCount))return this.userId=e,Object(zt.a)(this.appProfileManager.getProfile(e),e=>{if(!t())return;const s=Ko(e),i=50*s.length+8+24;this.container.style.setProperty("--height",i+"px"),this.render(s)});this.toggle(!1)}}class tr{constructor(e,t,s,i,n,o,r,d,h,p,u,g,m,b,v){this.chat=e,this.appMessagesManager=t,this.appMessagesIdsManager=s,this.appDocsManager=i,this.appChatsManager=n,this.appPeersManager=o,this.appWebPagesManager=r,this.appImManager=d,this.appDraftsManager=h,this.serverTimeManager=p,this.appNotificationsManager=u,this.appEmojiManager=g,this.appUsersManager=m,this.appInlineBotsManager=b,this.appProfileManager=v,this.lastUrl="",this.lastTimeType=0,this.replyElements={},this.willSendWebPage=null,this.recording=!1,this.recordCanceled=!1,this.recordStartTime=0,this.lockRedo=!1,this.canRedoFromHTML="",this.undoHistory=[],this.executedHistory=[],this.canUndoFromHTML="",this.onCancelRecordClick=e=>{e&&Object(c.a)(e),this.recordCanceled=!0,this.recorder.stop(),So.a.setKeepAlive(!1)},this.onEmoticonsOpen=()=>{const e=he.a?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!0)},this.onEmoticonsClose=()=>{const e=he.a?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!1)},this.scheduleSending=(e=this.sendMessage.bind(this,!0),t=new Date)=>{const{peerId:s}=this.chat,i=this.chat.bubbles.getMiddleware(),n=a.a.myId!==s&&s.isUser()&&this.appUsersManager.isUserOnlineVisible(s);new Bo(t,t=>{if(!i())return;t<=10+(Date.now()/1e3|0)&&(t=void 0),this.scheduleDate=t,e(),"scheduled"!==this.chat.type&&t&&setTimeout(()=>{i()&&this.appImManager.openScheduled(s)},0)},n).show()},this.prepareDocumentExecute=()=>(this.executedHistory.push(this.messageInput.innerHTML),()=>this.canUndoFromHTML=this.messageInput.innerHTML),this.undoRedo=(e,t,s)=>{Object(c.a)(e);let i=this.messageInput.innerHTML;if(i&&i!==s){this.lockRedo=!0;let e=0;do{document.execCommand(t,!1,null);const s=this.messageInput.innerHTML;if(i===s){if(++e>2)break}else e=0;i=s}while(i!==s);this.lockRedo=!1}},this.handleMarkdownShortcut=e=>{const t={KeyB:"bold",KeyI:"italic",KeyU:"underline",KeyS:"strikethrough",KeyM:"monospace",KeyP:"spoiler"};this.appImManager.markupTooltip&&(t.KeyK="link");const s=e.code,i=t[s];if(document.getSelection().toString().trim().length&&i&&("KeyK"===s?this.appImManager.markupTooltip.showLinkEditor():this.applyMarkdown(i),Object(c.a)(e)),"KeyZ"===s){let t=this.messageInput.innerHTML;e.shiftKey?this.undoHistory.length&&(this.executedHistory.push(t),t=this.undoHistory.pop(),this.undoRedo(e,"redo",t),t=this.messageInput.innerHTML,this.canRedoFromHTML=this.undoHistory.length?t:"",this.canUndoFromHTML=t):!this.executedHistory.length||this.canUndoFromHTML&&t!==this.canUndoFromHTML||(this.undoHistory.push(t),t=this.executedHistory.pop(),this.undoRedo(e,"undo",t),this.canUndoFromHTML=this.canRedoFromHTML=this.messageInput.innerHTML)}},this.onMessageInput=e=>{var t;const{value:s,entities:i,caretPos:n}=Ho(this.messageInputField.input),a=X.b.parseMarkdown(s,i,!0),o=X.b.mergeEntities(i,X.b.parseEntities(a));this.canRedoFromHTML&&!this.lockRedo&&this.messageInput.innerHTML!==this.canRedoFromHTML&&(this.canRedoFromHTML="",this.undoHistory.length=0);const r=(!(null===(t=this.editMessage)||void 0===t?void 0:t.media)||"messageMediaWebPage"===this.editMessage.media._)&&o.filter(e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._);if(r.length)for(const e of r){let t;if("messageEntityTextUrl"===e._)t=e.url;else if(t=s.slice(e.offset,e.offset+e.length),!t.includes("http://")&&!t.includes("https://"))continue;if(this.lastUrl!==t){this.lastUrl=t;const e=this.getWebPagePromise=ct.a.invokeApiHashable({method:"messages.getWebPage",processResult:e=>this.appWebPagesManager.saveWebPage(e),params:{url:t}}).then(s=>{this.getWebPagePromise===e&&(this.getWebPagePromise=void 0),this.lastUrl===t&&("webPage"===s._?(this.setTopInfo("webpage",()=>{},s.site_name||s.title||"Webpage",s.description||s.url||""),delete this.noWebPage,this.willSendWebPage=s):this.willSendWebPage&&this.onHelperCancel())})}break}else this.lastUrl&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.helperType?this.helperFunc():this.clearHelper());if(!s.trim())this.lastTimeType&&this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"}),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.hide(),document.activeElement===this.messageInput&&setTimeout(()=>{document.activeElement===this.messageInput&&this.resetCurrentFormatting()},0);else{const e=Date.now();e-this.lastTimeType>=6e3&&(this.lastTimeType=e,this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageTypingAction"})),this.botCommands&&this.botCommands.toggle(!0)}this.botCommands&&this.updateBotCommandsToggle(),this.editMsgId||this.saveDraftDebounced(),this.checkAutocomplete(s,n,o),this.updateSendBtn()},this.onEmojiSelected=(e,t)=>{this.insertAtCaret(e,X.b.getEmojiEntityFromEmoji(e),t)},this.onBtnSendClick=e=>{if(Object(c.a)(e),!this.recorder||this.recording||!this.isInputEmpty()||this.forwarding||this.editMsgId)this.recording?Date.now()-this.recordStartTime<500?this.onCancelRecordClick():this.recorder.stop():this.sendMessage();else{if(this.chat.peerId.isAnyChat()&&!this.chat.canSend("send_media"))return void ot("Posting media content isn't allowed in this group.");this.chatInput.classList.add("is-locked"),Object(ti.a)(),this.recorder.start().then(()=>{this.releaseMediaPlayback=fe.setSingleMedia(),this.recordCanceled=!1,this.setRecording(!0),So.a.setKeepAlive(!0);const e=()=>{new ut("popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{Object(l.d)(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",t=>{Object(Ce.a)(t.target,"chat-input")||Object(Ce.a)(t.target,"popup-cancel-record")||(Object(c.a)(t),e())},{capture:!0,passive:!1}),F.a.pushItem(this.recordingNavigationItem={type:"voice",onPop:()=>(setTimeout(()=>{e()},0),!1)}),this.recordStartTime=Date.now();const t=this.recorder.sourceNode,s=t.context.createAnalyser();t.connect(s),s.fftSize=32;const i=new Uint8Array(s.frequencyBinCount),n=255*i.length;let a=()=>{if(!this.recording)return;s.getByteFrequencyData(i);let e=0;i.forEach(t=>{e+=t});let t=Math.min(1,e/n+.36);this.recordRippleEl.style.transform=`scale(${t})`;let o=Date.now()-this.recordStartTime,r=o%1e3,l=Te(o/1e3)+","+("00"+Math.round(r/10)).slice(-2);this.recordTimeEl.innerText=l,Object(Le.b)(a)};a()}).catch(e=>{switch(e.name){case"NotAllowedError":ot("Please allow access to your microphone");break;case"NotReadableError":ot(e.message);break;default:console.error("Recorder start error:",e,e.name,e.message),ot(e.message)}this.setRecording(!1),this.chatInput.classList.remove("is-locked")})}},this.onHelperCancel=(e,t)=>{if(e&&Object(c.a)(e),this.willSendWebPage){const e=this.lastUrl;let t=!1;if(this.helperType&&(this.helperFunc(),t=!0),this.lastUrl=e,this.noWebPage=!0,this.willSendWebPage=null,t)return}if("edit"===this.helperType&&!t){const e=this.editMessage,t=X.b.parseMarkdown(this.messageInputField.value,[]);if(e.message!==t)return void new ut("discard-editing",{buttons:[{langKey:"Alert.Confirm.Discard",callback:()=>{this.onHelperCancel(void 0,!0)}}],descriptionLangKey:"Chat.Edit.Cancel.Text"}).show()}this.clearHelper(),this.updateSendBtn()},this.onHelperClick=e=>{if(Object(c.a)(e),Object(Ce.a)(e.target,"reply"))if("forward"===this.helperType){const{forwardElements:e}=this;e&&he.a&&!e.container.classList.contains("active")&&Object(ee.d)(e.container)}else"reply"===this.helperType?this.chat.setMessageId(this.replyToMsgId):"edit"===this.helperType&&this.chat.setMessageId(this.editMsgId)},this.listenerSetter=new R.a}construct(){this.chatInput=document.createElement("div"),this.chatInput.classList.add("chat-input"),this.chatInput.style.display="none",this.inputContainer=document.createElement("div"),this.inputContainer.classList.add("chat-input-container"),this.rowsWrapperWrapper=document.createElement("div"),this.rowsWrapperWrapper.classList.add("rows-wrapper-wrapper"),this.rowsWrapper=document.createElement("div"),this.rowsWrapper.classList.add("rows-wrapper","chat-input-wrapper"),this.rowsWrapperWrapper.append(this.rowsWrapper);const e=oo();this.rowsWrapper.append(e);const t=this.fakeRowsWrapper=document.createElement("div");t.classList.add("fake-wrapper","fake-rows-wrapper");const s=this.fakeSelectionWrapper=document.createElement("div");s.classList.add("fake-wrapper","fake-selection-wrapper"),this.inputContainer.append(this.rowsWrapperWrapper,t,s),this.chatInput.append(this.inputContainer),this.goDownBtn=Q({icon:"arrow_down",className:"bubbles-corner-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),Object(l.b)(this.goDownBtn,e=>{Object(c.a)(e),this.chat.bubbles.onGoDownClick()},{listenerSetter:this.listenerSetter});const i=this.controlContainer=document.createElement("div");i.classList.add("chat-input-control","chat-input-wrapper"),this.inputContainer.append(i)}constructPeerHelpers(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper"),this.replyElements.iconBtn=N(""),this.replyElements.cancelBtn=N("close reply-cancel",{noRipple:!0}),this.replyElements.container.append(this.replyElements.iconBtn,this.replyElements.cancelBtn);const e=()=>(i=!0,this.canToggleHideAuthor()),t=()=>{i=!1},s=this.forwardElements={};let i=!1;const n=[s.showSender={text:"Chat.Alert.Forward.Action.Show1",onClick:e,checkboxField:new pt.a({checked:!0})},s.hideSender={text:"Chat.Alert.Forward.Action.Hide1",onClick:e,checkboxField:new pt.a({checked:!1})},s.showCaption={text:"Chat.Alert.Forward.Action.ShowCaption",onClick:t,checkboxField:new pt.a({checked:!0})},s.hideCaption={text:"Chat.Alert.Forward.Action.HideCaption",onClick:t,checkboxField:new pt.a({checked:!1})},s.changePeer={text:"Chat.Alert.Forward.Action.Another",onClick:()=>{this.changeForwardRecipient()},icon:"replace"}],o=s.container=$s(n,this.listenerSetter),r=Array.from(o.children);if([{elements:r.slice(0,2),onChange:(e,t)=>{const n=!!+e;i&&(this.forwardWasDroppingAuthor=!n);const a=this.replyElements.container.querySelector(".reply-title");if(a){const e=a.firstElementChild,t=T.c.weakMap.get(e),i=s.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden";t.key=i,t.update()}}},{elements:r.slice(2,4),onChange:e=>{const t=!!+e;let i;i=t&&void 0!==this.forwardWasDroppingAuthor?this.forwardWasDroppingAuthor?s.hideSender:s.showSender:t?s.showSender:s.hideSender,i.checkboxField.checked=!0}}].forEach(e=>{const t=Je(e.elements.map(e=>({container:e,input:e.querySelector("input")})),e.onChange),s=document.createElement("hr");t.append(s),o.append(t)}),o.append(s.changePeer.element),!he.a){this.forwardHover=new Na({element:o})}s.modifyArgs=n.slice(0,-1),this.replyElements.container.append(o),s.modifyArgs.forEach((e,t)=>{const{input:s}=e.checkboxField;s.type="radio",s.name=t<2?"author":"caption",s.value=""+ +!(t%2)}),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper"),this.sendAsContainer=document.createElement("div"),this.sendAsContainer.classList.add("new-message-send-as-container"),this.sendAsCloseBtn=document.createElement("div"),this.sendAsCloseBtn.classList.add("new-message-send-as-close","new-message-send-as-avatar","tgico-close");const d=[{text:"SendMessageAsTitle",onClick:void 0}];let h;const p=e=>{e&&(h=this.sendAsAvatar);const t=this.sendAsAvatar!==h,s=!e&&t?2:0;Object(is.a)(this.sendAsCloseBtn,"is-visible",e,300,void 0,s),t||Object(is.a)(h,"is-visible",!e,300,void 0,s)};if(bi({noRipple:!0,listenerSetter:this.listenerSetter,container:this.sendAsContainer},"top-right",d,()=>{p(!0)},()=>{p(!1)}),d[0].element.classList.add("btn-menu-item-header"),this.sendAsBtnMenu=this.sendAsContainer.firstElementChild,this.sendAsBtnMenu.classList.add("scrollable","scrollable-y"),this.sendAsContainer.append(this.sendAsCloseBtn),this.btnToggleEmoticons=N("none toggle-emoticons",{noRipple:!0}),this.inputMessageContainer=document.createElement("div"),this.inputMessageContainer.classList.add("input-message-container"),"chat"===this.chat.type){this.goDownUnreadBadge=document.createElement("span"),this.goDownUnreadBadge.classList.add("badge","badge-24","badge-primary"),this.goDownBtn.append(this.goDownUnreadBadge),this.goMentionBtn=Q({icon:"mention",className:"bubbles-corner-button bubbles-go-mention"}),this.goMentionUnreadBadge=document.createElement("span"),this.goMentionUnreadBadge.classList.add("badge","badge-24","badge-primary"),this.goMentionBtn.append(this.goMentionUnreadBadge),this.inputContainer.append(this.goMentionBtn),Object(l.b)(this.goMentionBtn,e=>{Object(c.a)(e),this.appMessagesManager.goToNextMention(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.btnScheduled=N("scheduled btn-scheduled float hide",{noRipple:!0}),Object(l.b)(this.btnScheduled,e=>{this.appImManager.openScheduled(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.a)("scheduled_new",({peerId:e})=>{this.chat.peerId===e&&this.btnScheduled.classList.remove("hide")}),this.listenerSetter.add(a.a)("scheduled_delete",({peerId:e})=>{this.chat.peerId===e&&this.appMessagesManager.getScheduledMessages(this.chat.peerId).then(e=>{this.btnScheduled.classList.toggle("hide",!e.length)})}),this.btnToggleReplyMarkup=N("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new $o({appendTo:this.rowsWrapper,listenerSetter:this.listenerSetter,appMessagesManager:this.appMessagesManager,btnHover:this.btnToggleReplyMarkup,chatInput:this}),this.listenerSetter.add(this.replyKeyboard)("open",()=>this.btnToggleReplyMarkup.classList.add("active")),this.listenerSetter.add(this.replyKeyboard)("close",()=>this.btnToggleReplyMarkup.classList.remove("active")),this.botCommands=new er(this.rowsWrapper,this,this.appProfileManager),this.botCommandsToggle=document.createElement("div"),this.botCommandsToggle.classList.add("new-message-bot-commands");const e=document.createElement("div");e.classList.add("new-message-bot-commands-icon-scale");const t=this.botCommandsIcon=document.createElement("div");t.classList.add("animated-menu-icon","animated-menu-close-icon"),e.append(t),this.botCommandsToggle.append(e),Object(l.b)(this.botCommandsToggle,e=>{Object(c.a)(e);t.classList.contains("state-back")?(this.botCommands.toggle(!0),t.classList.remove("state-back")):(this.botCommands.setUserId(this.chat.peerId.toUserId(),this.chat.bubbles.getMiddleware()),t.classList.add("state-back"))},{listenerSetter:this.listenerSetter}),this.botCommands.addEventListener("visible",()=>{t.classList.add("state-back")}),this.botCommands.addEventListener("hiding",()=>{t.classList.remove("state-back")})}this.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>{this.fileInput.value="";const e=[...g].join(", ");this.fileInput.setAttribute("accept",e),this.willAttachType="media",this.fileInput.click()},verify:()=>this.chat.canSend("send_media")},{icon:"document",text:"Chat.Input.Attach.Document",onClick:()=>{this.fileInput.value="",this.fileInput.removeAttribute("accept"),this.willAttachType="document",this.fileInput.click()},verify:()=>this.chat.canSend("send_media")},{icon:"poll",text:"Poll",onClick:()=>{new Mo(this.chat).show()},verify:e=>e.isAnyChat()&&this.chat.canSend("send_polls")}],this.attachMenu=bi({noRipple:!0,listenerSetter:this.listenerSetter},"top-left",this.attachMenuButtons),this.attachMenu.classList.add("attach-file","tgico-attach"),this.attachMenu.classList.remove("tgico-more"),this.recordTimeEl=document.createElement("div"),this.recordTimeEl.classList.add("record-time"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=!0,this.fileInput.style.display="none",this.newMessageWrapper.append(...[this.sendAsContainer,this.botCommandsToggle,this.btnToggleEmoticons,this.inputMessageContainer,this.btnScheduled,this.btnToggleReplyMarkup,this.attachMenu,this.recordTimeEl,this.fileInput].filter(Boolean)),this.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new Wo,this.stickersHelper=new Fo(this.rowsWrapper,this.autocompleteHelperController),this.emojiHelper=new zo(this.rowsWrapper,this.autocompleteHelperController,this,this.appEmojiManager),this.commandsHelper=new Go(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.mentionsHelper=new qo(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.inlineHelper=new Jo(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.appUsersManager,this.appInlineBotsManager),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=N("delete btn-circle z-depth-1 btn-record-cancel"),this.btnSendContainer=document.createElement("div"),this.btnSendContainer.classList.add("btn-send-container"),this.recordRippleEl=document.createElement("div"),this.recordRippleEl.classList.add("record-ripple"),this.btnSend=N("none btn-circle z-depth-1 btn-send animated-button-icon"),this.btnSend.insertAdjacentHTML("afterbegin",'\n <span class="tgico tgico-send"></span>\n <span class="tgico tgico-schedule"></span>\n <span class="tgico tgico-check"></span>\n <span class="tgico tgico-microphone_filled"></span>\n '),this.btnSendContainer.append(this.recordRippleEl,this.btnSend),"scheduled"!==this.chat.type&&(this.sendMenu=new Co({onSilentClick:()=>{this.sendSilent=!0,this.sendMessage()},onScheduleClick:()=>{this.scheduleSending(void 0)},listenerSetter:this.listenerSetter,openSide:"top-left",onContextElement:this.btnSend,onOpen:()=>!this.isInputEmpty()||!!Object.keys(this.forwarding).length}),this.btnSendContainer.append(this.sendMenu.sendMenu)),this.inputContainer.append(this.btnCancelRecord,this.btnSendContainer),Ka.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(Ka)("open",this.onEmoticonsOpen),this.listenerSetter.add(Ka)("close",this.onEmoticonsClose),this.attachMessageInputField(),this.listenerSetter.add(a.a)("settings_updated",()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery="",this.checkAutocomplete()),this.messageInputField&&this.messageInputField.onFakeInput()}),this.listenerSetter.add(a.a)("draft_updated",({peerId:e,threadId:t,draft:s,force:i})=>{this.chat.threadId===t&&this.chat.peerId===e&&this.setDraft(s,!0,i)}),this.listenerSetter.add(a.a)("peer_changing",e=>{this.chat===e&&this.saveDraft()}),this.listenerSetter.add(a.a)("chat_changing",({from:e,to:t})=>{this.chat===e?this.autocompleteHelperController.toggleListNavigation(!1):this.chat===t&&this.autocompleteHelperController.toggleListNavigation(!0)}),this.sendAsContainer&&this.listenerSetter.add(a.a)("peer_full_update",e=>{e.isChannel()&&this.chat.peerId===e&&this.updateSendAs()}),"scheduled"===this.chat.type?this.listenerSetter.add(a.a)("scheduled_delete",({peerId:e,mids:t})=>{this.chat.peerId===e&&t.includes(this.editMsgId)&&this.onMessageSent()}):(this.listenerSetter.add(a.a)("history_delete",({peerId:e,msgs:t})=>{this.chat.peerId===e&&(t.has(this.editMsgId)&&this.onMessageSent(),this.replyToMsgId&&t.has(this.replyToMsgId)&&this.clearHelper("reply"))}),this.listenerSetter.add(a.a)("dialogs_multiupdate",e=>{e[this.chat.peerId]&&(this.startParam===Me.a?this.setStartParam():this.center(!0))}));try{this.recorder=new wo.a({encoderSampleRate:48e3,monitorGain:0,numberOfChannels:1,recordingGain:1,reuseWorker:!0})}catch(e){console.error("Recorder constructor error:",e)}this.updateSendBtn(),this.listenerSetter.add(this.fileInput)("change",e=>{let t=e.target.files;t.length&&(new xo(this.chat,Array.from(t).slice(),this.willAttachType),this.fileInput.value="")},!1),Object(l.b)(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.recorder&&(Object(l.b)(this.btnCancelRecord,this.onCancelRecordClick,{listenerSetter:this.listenerSetter}),this.recorder.onstop=()=>{this.setRecording(!1),this.chatInput.classList.remove("is-locked"),this.recordRippleEl.style.transform=""},this.recorder.ondataavailable=e=>{if(this.releaseMediaPlayback&&(this.releaseMediaPlayback(),this.releaseMediaPlayback=void 0),this.recordingOverlayListener&&(this.listenerSetter.remove(this.recordingOverlayListener),this.recordingOverlayListener=void 0),this.recordingNavigationItem&&(F.a.removeItem(this.recordingNavigationItem),this.recordingNavigationItem=void 0),this.recordCanceled)return;const{peerId:t,threadId:s}=this.chat,i=this.replyToMsgId,n=(Date.now()-this.recordStartTime)/1e3|0,a=new Blob([e],{type:"audio/ogg"});So.a.decode(e,!0).then(e=>{So.a.setKeepAlive(!1),this.appMessagesManager.sendFile(t,a,{isVoiceMessage:!0,isMedia:!0,duration:n,waveform:e.waveform,objectURL:e.url,replyToMsgId:i,threadId:s,clearDraft:!0}),this.onMessageSent(!1,!0)})}),Object(l.b)(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),Object(l.b)(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter}),this.saveDraftDebounced=Object(lt.a)(()=>this.saveDraft(),2500,!1,!0),this.botStartBtn=Object(B.a)("btn-primary btn-transparent text-bold chat-input-control-button"),this.botStartBtn.append(Object(T.d)("BotStart")),Object(l.b)(this.botStartBtn,()=>{const{startParam:e}=this;if(void 0===e)return;const t=this.toggleBotStartBtnDisability=Object(gt.a)([this.botStartBtn],!0),s=this.chat.peerId,i=this.chat.bubbles.getMiddleware(()=>this.chat.peerId===s&&this.startParam===e&&this.toggleBotStartBtnDisability===t);this.appMessagesManager.startBot(s.toUserId(),void 0,e).then(()=>{i()&&(t(),this.toggleBotStartBtnDisability=void 0,this.setStartParam())})},{listenerSetter:this.listenerSetter}),this.controlContainer.append(this.botStartBtn)}constructPinnedHelpers(){this.pinnedControlBtn=Object(B.a)("btn-primary btn-transparent text-bold chat-input-control-button",{icon:"unpin"}),this.controlContainer.append(this.pinnedControlBtn),this.listenerSetter.add(this.pinnedControlBtn)("click",()=>{const e=this.chat.peerId;new ro(e,0,!0,()=>{this.chat.appImManager.setPeer();const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)})}),this.chatInput.classList.add("type-pinned")}center(e=!1){const t=this.getNeededFakeContainer();if(!t&&!this.inputContainer.classList.contains("is-centering"))return;if(t===this.fakeWrapperTo)return;const s=t||this.fakeWrapperTo,i=!!t,n=this.fakeWrapperTo;let a,o="",r="";const l=s.getBoundingClientRect(),c=this.fakeRowsWrapper.getBoundingClientRect(),d=c.width,h=l.width;if(d!==h){const e=h/d,t=(d-h)/2;if(a=l.left-c.left-t,i&&(o=`translateX(${a}px) scaleX(${e})`,e<1)){const t=12;r=t+t*(1-e)+"px"}}this.fakeWrapperTo=t;const p=e?200:0;return Object(is.a)(this.inputContainer,"is-centering",i,p),Object(is.a)(this.rowsWrapperWrapper,"is-centering-to-control",!!(i&&t&&t.classList.contains("chat-input-control")),p),this.rowsWrapper.style.transform=o,this.rowsWrapper.style.borderRadius=r,{transform:o,borderRadius:r,needTranslateX:n&&(t&&t.classList.contains("chat-input-control")&&n===this.fakeSelectionWrapper||n.classList.contains("chat-input-control"))?-.5*a:a,widthFrom:d,widthTo:h}}setStartParam(e){this.startParam!==e&&(this.startParam=e,this.center(!0))}getNeededFakeContainer(){return this.chat.selection.isSelecting?this.fakeSelectionWrapper:void 0!==this.startParam||!this.chat.canSend()||"pinned"===this.chat.type||this.chat.isStartButtonNeeded()?this.controlContainer:void 0}getReadyToSend(e){return"scheduled"===this.chat.type?(this.scheduleSending(e),!0):(e(),!1)}setUnreadCount(){if(!this.goDownUnreadBadge)return;const e=this.appMessagesManager.getDialogOnly(this.chat.peerId),t=null==e?void 0:e.unread_count;if(this.goDownUnreadBadge.innerText=""+(t||""),this.goDownUnreadBadge.classList.toggle("badge-gray",this.appNotificationsManager.isPeerLocalMuted(this.chat.peerId,!0)),this.goMentionUnreadBadge&&"chat"===this.chat.type){const t=!(!(null==e?void 0:e.unread_mentions_count)||!e.unread_count);this.goMentionUnreadBadge.innerText=t?""+e.unread_mentions_count:"",this.goMentionBtn.classList.toggle("is-visible",t)}}saveDraft(){if(!this.chat.peerId||this.editMsgId||"scheduled"===this.chat.type)return;const{value:e,entities:t}=Object(Lo.a)(this.messageInputField.input);let s;(e.length||this.replyToMsgId)&&(s={_:"draftMessage",date:Object(ne.h)(!0)+this.serverTimeManager.serverTimeOffset,message:e,entities:t.length?t:void 0,pFlags:{no_webpage:this.noWebPage},reply_to_msg_id:this.replyToMsgId}),this.appDraftsManager.syncDraft(this.chat.peerId,this.chat.threadId,s)}destroy(){this.listenerSetter.removeAll()}cleanup(e=!0){this.chat.peerId||(this.chatInput.style.display="none",this.goDownBtn.classList.add("hide")),si(),this.lastTimeType=0,this.startParam=void 0,this.toggleBotStartBtnDisability&&(this.toggleBotStartBtnDisability(),this.toggleBotStartBtnDisability=void 0),this.messageInput&&(this.clearInput(),e&&this.clearHelper())}setDraft(e,t=!0,s=!1){return!(!s&&!Object(Io.a)(this.messageInput)||"scheduled"===this.chat.type)&&(e||(e=this.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId))?(this.messageInputField.value!==e.rMessage||this.replyToMsgId!==e.reply_to_msg_id)&&(t&&this.clearHelper(),this.noWebPage=e.pFlags.no_webpage,e.reply_to_msg_id&&this.initMessageReply(e.reply_to_msg_id),this.setInputValue(e.rMessage,t,t),!0):(s&&(this.chat.container.classList.contains("is-helper-active")&&this.t(),this.messageInputField.inputFake.textContent="",this.messageInputField.onFakeInput(!1),(this.chat.bubbles.messagesQueuePromise||Promise.resolve()).then(()=>{Object(Le.b)(()=>{this.onMessageSent()})})),!1))}finishPeerChange(e){const t=this.chat.peerId,{forwardElements:s,btnScheduled:i,replyKeyboard:n,sendMenu:a,goDownBtn:o,chatInput:r,sendAsContainer:l,botCommandsToggle:c}=this;r.style.display="";const d=this.appPeersManager.isBroadcast(t);if(o.classList.toggle("is-broadcast",d),o.classList.remove("hide"),this.goDownUnreadBadge&&this.setUnreadCount(),"pinned"===this.chat.type&&r.classList.toggle("can-pin",this.appPeersManager.canPinMessage(t)),s&&(this.forwardWasDroppingAuthor=!1,s.showCaption.checkboxField.setValueSilently(!0),s.showSender.checkboxField.setValueSilently(!0)),i){i.classList.add("hide");const e=this.chat.bubbles.getMiddleware();this.appMessagesManager.getScheduledMessages(t).then(t=>{e()&&i.classList.toggle("hide",!t.length)})}if(this.newMessageWrapper&&this.updateOffset(null,!1,!0),c&&(this.hasBotCommands=void 0,this.botCommands.toggle(!0,void 0,!0),this.updateBotCommandsToggle(!0),c.remove(),this.appPeersManager.isBot(t))){const e=t.toUserId(),s=this.chat.bubbles.getMiddleware(),i=this.appProfileManager.getProfile(e);Object(zt.a)(i,e=>{s()&&this.updateBotCommands(e,!(i instanceof Promise))})}l&&(this.sendAsAvatar&&(this.sendAsAvatar.remove(),this.sendAsAvatar=void 0),l.remove(),this.sendAsPeerId=void 0,this.updatingSendAsPromise=void 0,this.updateSendAs(!0)),n&&n.setPeer(t),a&&a.setPeerId(t),this.messageInput?this.updateMessageInput():this.pinnedControlBtn&&this.pinnedControlBtn.append(Object(T.d)(this.appPeersManager.canPinMessage(this.chat.peerId)?"Chat.Input.UnpinAll":"Chat.Pinned.DontShow")),this.startParam=e,this.center(!1)}updateOffset(e,t,s,i){e?this.newMessageWrapper.dataset.offset=e:delete this.newMessageWrapper.dataset.offset,Object(is.a)(this.newMessageWrapper,"has-offset",t,s?0:300,void 0,i)}updateBotCommands(e,t){this.hasBotCommands=e.bot_info&&e.bot_info.commands.length,this.updateBotCommandsToggle(t)}updateBotCommandsToggle(e){const{botCommandsToggle:t,hasBotCommands:s}=this,i=!!s&&this.isInputEmpty();if(!s){if(!t.parentElement)return;t.remove()}const n=i,a=t.parentElement?0:2;t.parentElement||this.newMessageWrapper.prepend(t),this.updateOffset("commands",n,e,a)}updateSendAsButtons(e){const t=e.map((e,t)=>{const s=document.createElement("div"),i=document.createElement("div");return i.classList.add("btn-menu-item-subtitle"),e.isUser()?i.append(Object(T.d)("Chat.SendAs.PersonalAccount")):e===this.chat.peerId?i.append(Object(T.d)("VoiceChat.DiscussionGroup")):i.append(this.appProfileManager.getChatMembersString(e.toChatId())),s.append(new wt.a({peerId:e}).element,i),{onClick:t?()=>{const t=this.chat.peerId;if(t.isChannel()){const s=this.appProfileManager.getCachedFullChat(t.toChatId());if(s){s.default_send_as=this.appPeersManager.getOutputPeer(e),this.sendAsPeerId=e,this.updateSendAsAvatar(e),this.updateMessageInputPlaceholder();const t=this.chat.bubbles.getMiddleware(),i=()=>{if(this.sendAsPeerId!==e||!t())return;const s=this.sendAsPeerIds.slice();Object(V.a)(s,e),s.unshift(e),this.updateSendAsButtons(s)};a.a.settings.animationsEnabled?setTimeout(i,250):i()}}ct.a.invokeApi("messages.saveDefaultSendAs",{peer:this.appPeersManager.getInputPeerById(t),send_as:this.appPeersManager.getInputPeerById(e)})}:void 0,textElement:s}}),s=$s(t);t.forEach((t,s)=>{const i=e[s],n=new fc;n.classList.add("avatar-32","btn-menu-item-icon"),n.updateWithOptions({peerId:i}),s||n.classList.add("active"),t.element.prepend(n)}),Array.from(this.sendAsBtnMenu.children).slice(1).forEach(e=>e.remove()),this.sendAsBtnMenu.append(...Array.from(s.children))}updateSendAsAvatar(e,t){const s=this.sendAsAvatar;if(s&&s.peerId===e)return;s||(t=!0);let i=t?0:2;const n=t?0:300,a=this.sendAsAvatar=new fc;a.classList.add("new-message-send-as-avatar","avatar-30"),a.updateWithOptions({isDialog:!1,peerId:e}),Object(is.a)(a,"is-visible",!0,n,void 0,i),s&&Object(is.a)(s,"is-visible",!1,n,()=>{s.remove()},i),this.sendAsContainer.append(a)}getDefaultSendAs(){return Object(zt.a)(this.appProfileManager.getChannelFull(this.chat.peerId.toChatId()),e=>e.default_send_as?this.appPeersManager.getPeerId(e.default_send_as):void 0)}updateSendAs(e){const t=this.chat.peerId;if(!t.isChannel()||this.updatingSendAsPromise)return;const s=this.chat.bubbles.getMiddleware(()=>!this.updatingSendAsPromise||this.updatingSendAsPromise===r),{sendAsContainer:i}=this,n=t.toChatId(),a=this.getDefaultSendAs();a instanceof Promise&&(e=void 0);const o=Object(zt.a)(a,t=>{if(!s()||void 0===t)return;this.sendAsPeerId=t,this.updateSendAsAvatar(t,e),this.updateMessageInputPlaceholder(),this.appChatsManager.getSendAs(n).then(e=>{if(!s())return;const i=e.map(e=>this.appPeersManager.getPeerId(e));this.sendAsPeerIds=i.slice(),Object(V.a)(i,t),i.unshift(t),this.updateSendAsButtons(i)});let a=0;i.parentElement||(this.newMessageWrapper.prepend(i),a=2),this.updateOffset("as",!0,e,a),this.updatingSendAsPromise=void 0}),r=this.updatingSendAsPromise=Promise.resolve(o);return r}updateMessageInputPlaceholder(){const e=T.c.weakMap.get(this.messageInput);if(e){const{peerId:t,threadId:s}=this.chat;let i;i=s?"Comment":this.appPeersManager.isBroadcast(t)?"ChannelBroadcast":void 0!==this.sendAsPeerId&&this.sendAsPeerId!==a.a.myId||this.appMessagesManager.isAnonymousSending(t)?"SendAnonymously":"Message",e.compareAndUpdate({key:i})}}updateMessageInput(){const{chatInput:e,attachMenu:t,messageInput:s}=this,{peerId:i,threadId:n}=this.chat,a=this.chat.canSend();e.classList.contains("is-hidden")!==!a&&(e.classList.add("no-transition"),e.classList.toggle("is-hidden",!a),e.offsetLeft,e.classList.remove("no-transition")),this.updateMessageInputPlaceholder();const o=this.attachMenuButtons.filter(e=>{const t=e.verify(i,n);return e.element.classList.toggle("hide",!t),t});a?(s.setAttribute("contenteditable","true"),this.setDraft(void 0,!1),s.innerHTML||this.messageInputField.onFakeInput()):s.removeAttribute("contenteditable"),t.toggleAttribute("disabled",!o.length),t.classList.toggle("btn-disabled",!o.length),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new O.b({placeholder:"Message",name:"message",animate:!0}),this.messageInputField.input.classList.replace("input-field-input","input-message-input"),this.messageInputField.inputFake.classList.replace("input-field-input","input-message-input"),this.messageInput=this.messageInputField.input,this.messageInput.classList.add("no-scrollbar"),this.attachMessageInputListeners(),Zo.a&&Object(Zo.b)(this.messageInput),e?(e.input.replaceWith(this.messageInputField.input),e.inputFake.replaceWith(this.messageInputField.inputFake)):this.inputMessageContainer.append(this.messageInputField.input,this.messageInputField.inputFake)}attachMessageInputListeners(){this.listenerSetter.add(this.messageInput)("keydown",e=>{const t=e.key;if(Object(No.a)(e))Object(c.a)(e),this.sendMessage();else if(e.ctrlKey||e.metaKey)this.handleMarkdownShortcut(e);else if(("PageUp"===t||"PageDown"===t)&&!e.shiftKey)if(e.preventDefault(),"PageUp"===t){const e=document.createRange(),t=window.getSelection();e.setStart(this.messageInput.childNodes[0]||this.messageInput,0),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}else Object(Eo.a)(this.messageInput)}),he.a&&Object(l.b)(this.messageInput,e=>{this.appImManager.selectTab(1),Ka.toggle(!1)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.messageInput)("input",this.onMessageInput),this.listenerSetter.add(this.messageInput)("keyup",()=>{this.checkAutocomplete()}),"chat"!==this.chat.type&&"discussion"!==this.chat.type||this.listenerSetter.add(this.messageInput)("focusin",()=>{this.chat.bubbles.scrollable.loadedAll.bottom&&this.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId)})}applyMarkdown(e,t){const s={bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",monospace:()=>document.execCommand("fontName",!1,"var(--font-monospace)"),link:t?()=>document.execCommand("createLink",!1,t):()=>document.execCommand("unlink",!1,null),spoiler:()=>document.execCommand("fontName",!1,"spoiler")};if(!s[e])return!1;const i=s[e],n=this.prepareDocumentExecute(),a=[];if(a.push(document.execCommand("styleWithCSS",!1,"true")),"monospace"===e||"spoiler"===e){let t=!1;const s=window.getSelection();if(!s.isCollapsed){const i=s.getRangeAt(0),n=Uo.b[e],a=i.commonAncestorContainer;(a.parentNode.matches(n.match)||a instanceof HTMLElement&&a.matches(n.match))&&(t=!0)}t?a.push(this.resetCurrentFormatting()):a.push("function"==typeof i?i():document.execCommand(i,!1,null))}else a.push("function"==typeof i?i():document.execCommand(i,!1,null));return a.push(document.execCommand("styleWithCSS",!1,"false")),n(),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.setActiveMarkupButton(),!0}resetCurrentFormatting(){return document.execCommand("fontName",!1,"Roboto")}insertAtCaret(e,t,s=!0){const{value:i,caretPos:n,entities:a}=Ho(this.messageInput),o=n>=0?n:i.length,r=i.substr(0,o),l=i.substr(o),c=s?r.match(tr.AUTO_COMPLETE_REG_EXP):null,d=c?c.index+(c[0].length-c[2].length):r.length,h=r.slice(0,d)+e+l,p=X.b.parseEntities(i);X.b.mergeEntities(a,p);const u=t?Math.max(t.length,e.length):e.length,g=[];t&&(g.push(t),t.offset=d);const m=c?u-c[2].length:u;a.forEach(e=>{e.offset>=d&&(e.offset+=m)}),X.b.mergeEntities(a,g);{const e={_:"messageEntityCaret",offset:d+u,length:0};let t=0;for(let s=a.length;t<s;++t){if(a[t].offset>e.offset)break}a.splice(t,0,e)}const b=Object(fn.a)(X.b.wrapDraftText(h,{entities:a}));this.messageInputField.setValueSilently(b,!0);const v=this.messageInput.querySelector(".composer-sel");v&&(!function(e){const t=e;if(1===(e=e.previousSibling).nodeType){const s=document.createTextNode("");e.parentNode.insertBefore(s,t.nextSibling&&t.nextSibling.nodeType!==e.nodeType?t.nextSibling:t),e=s}if(window.getSelection&&document.createRange){const t=document.createRange();e&&(t.setStartAfter(e),t.insertNode(e),t.setStart(e,e.nodeValue.length)),t.collapse(!0);const s=window.getSelection();s.removeAllRanges(),s.addRange(t)}}(v),v.remove()),this.onMessageInput()}checkAutocomplete(e,t,s){if(void 0===e){const i=Ho(this.messageInputField.input,!0);e=i.value,t=i.caretPos,s=i.entities}if(-1===t&&(t=e.length),void 0===s){const t=X.b.parseMarkdown(e,s,!0);s=X.b.mergeEntities(s,X.b.parseEntities(t))}if(e=e.slice(0,t),this.previousQuery===e)return;this.previousQuery=e;const i=e.match(tr.AUTO_COMPLETE_REG_EXP);let n;if(i){const t=s[0];let o=i[2];const r=o[0];if(this.stickersHelper&&a.a.settings.stickers.suggest&&this.chat.canSend("send_stickers")&&"messageEntityEmoji"===(null==t?void 0:t._)&&t.length===e.length&&!t.offset)n=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if("@"===r){const e=this.chat.threadId?this.appMessagesIdsManager.getServerMessageId(this.chat.threadId):void 0;this.mentionsHelper.checkQuery(o,this.chat.peerId.isUser()?Me.c:this.chat.peerId,e)&&(n=this.mentionsHelper)}else i[1]||"/"!==r?a.a.settings.emoji.suggest&&(o=o.replace(/^\s*/,""),e.match(/^\s*:(.+):\s*$/)||e.match(/:[;!@#$%^&*()-=|]/)||!o||(n=this.emojiHelper,this.emojiHelper.checkQuery(o,r))):this.commandsHelper.checkQuery(o,this.chat.peerId)&&(n=this.commandsHelper)}n=this.checkInlineAutocomplete(e,n),this.autocompleteHelperController.hideOtherHelpers(n)}checkInlineAutocomplete(e,t){let s=!1;if(!t){const i=e.match(/^@([a-zA-Z\\d_]{3,32})\s/);if(i){const n=i[1],a=e.slice(i[0].length);s=i[0].length===e.length,t=this.inlineHelper,this.btnPreloader?Object(is.a)(this.btnPreloader,"show",!0,400):(this.btnPreloader=N("none btn-preloader float show disable-hover",{noRipple:!0}),Object(ee.f)(this.btnPreloader,!0),this.inputMessageContainer.parentElement.insertBefore(this.btnPreloader,this.inputMessageContainer.nextSibling)),this.inlineHelper.checkQuery(this.chat.peerId,n,a).then(({user:e,renderPromise:t})=>{s&&e.bot_inline_placeholder&&(this.messageInput.dataset.inlinePlaceholder=e.bot_inline_placeholder),t.then(()=>{Object(is.a)(this.btnPreloader,"show",!1,400)})}).catch(Se.a)}}return s||delete this.messageInput.dataset.inlinePlaceholder,t!==this.inlineHelper&&this.btnPreloader&&Object(is.a)(this.btnPreloader,"show",!1,400),t}setRecording(e){this.recording!==e&&(Object(is.a)(this.chatInput,"is-recording",e,200),this.recording=e,this.updateSendBtn())}changeForwardRecipient(){if(this.helperWaitingForward)return;this.helperWaitingForward=!0;const e=Object(ue.a)(this.forwarding),t=this.helperFunc;this.clearHelper(),this.updateSendBtn();let s=!1;new Xs(e,()=>{s=!0}).addEventListener("close",()=>{this.helperWaitingForward=!1,s||t()})}clearInput(e=!0,t=!0,s=""){if(document.activeElement===this.messageInput&&ae.f){const e=document.createElement("input");document.body.append(e),Object(Qo.a)(e),this.messageInputField.setValueSilently(s),Object(Qo.a)(this.messageInput),e.remove()}else this.messageInputField.setValueSilently(s);he.a||(this.canRedoFromHTML="",this.undoHistory.length=0,this.executedHistory.length=0,this.canUndoFromHTML="");let i=!1;e&&(i=this.setDraft(void 0,!1)),!i&&t&&this.onMessageInput()}isInputEmpty(){return Object(Io.a)(this.messageInput)}updateSendBtn(){let e;const t=this.isInputEmpty();e=this.editMsgId?"edit":!this.recorder||this.recording||!t||this.forwarding?"scheduled"===this.chat.type?"schedule":"send":"record",["send","record","edit","schedule"].forEach(t=>{this.btnSend.classList.toggle(t,e===t)}),this.btnScheduled&&this.btnScheduled.classList.toggle("show",t),this.btnToggleReplyMarkup&&this.btnToggleReplyMarkup.classList.toggle("show",t)}onMessageSent(e=!0,t){"scheduled"!==this.chat.type&&this.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId,!0),this.scheduleDate=void 0,this.sendSilent=void 0;const s=this.messageInputField.value;X.b.parseEntities(s).filter(e=>"messageEntityEmoji"===e._).forEach(e=>{const t=Object(se.a)(e.unicode);this.appEmojiManager.pushRecentEmoji(t)}),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.clearInput()),(t||e)&&this.clearHelper(),this.updateSendBtn()}sendMessage(e=!1){const{editMsgId:t,chat:s}=this;if("scheduled"===s.type&&!e&&!t)return void this.scheduleSending();const{peerId:i}=s,{noWebPage:n}=this,a=this.chat.getMessageSendingParams(),{value:o,entities:r}=Object(Lo.a)(this.messageInputField.input);if(t){const e=this.editMessage;if(!o.trim()&&!e.media)return void new Js(i,[t],s.type);this.appMessagesManager.editMessage(e,o,{entities:r,noWebPage:n}),this.onMessageSent()}else o.trim()&&(this.appMessagesManager.sendText(i,o,Object.assign(Object.assign({entities:r},a),{noWebPage:n,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,clearDraft:!0})),this.onMessageSent(!1,!1));if(this.forwarding){const e=Object(ue.a)(this.forwarding);setTimeout(()=>{for(const t in e)this.appMessagesManager.forwardMessages(i,t.toPeerId(),e[t],Object.assign(Object.assign({},a),{dropAuthor:this.forwardElements&&this.forwardElements.hideSender.checkboxField.checked,dropCaptions:this.isDroppingCaptions()}));o||this.onMessageSent()},0)}}sendMessageWithDocument(e,t=!1,s=!1){var i;const n="sticker"===(e=this.appDocsManager.getDoc(e)).type?"send_stickers":"gif"===e.type?"send_gifs":"send_media";return this.chat.peerId.isAnyChat()&&!this.chat.canSend(n)?(ot("Posting media content isn't allowed in this group."),!1):"scheduled"!==this.chat.type||t?!!e&&(this.appMessagesManager.sendFile(this.chat.peerId,e,Object.assign(Object.assign({},this.chat.getMessageSendingParams()),{isMedia:!0,clearDraft:s||void 0})),this.onMessageSent(s,!0),"sticker"===e.type&&(null===(i=Ka.stickersTab)||void 0===i||i.pushRecentSticker(e)),!0):(this.scheduleSending(()=>this.sendMessageWithDocument(e,!0,s)),!1)}canToggleHideAuthor(){const{forwardElements:e}=this;if(!e)return!1;const t=e.hideCaption.checkboxField;return!t.checked||Object(bt.a)(t.label,"FORM").classList.contains("hide")}isDroppingCaptions(){return!this.canToggleHideAuthor()}initMessageEditing(e){const t=this.chat.getMessage(e);let s=Object(fn.a)(X.b.wrapDraftText(t.message,{entities:t.totalEntities}));const i=()=>{const n=this.appMessagesManager.wrapMessageForReply(t,void 0,[t.mid]);this.setTopInfo("edit",i,Object(T.d)("AccDescrEditing"),n,s,t),this.editMsgId=e,this.editMessage=t,s=void 0};i()}initMessagesForward(e){const t=()=>{const s=Object.keys(e).map(e=>e.toPeerId()),i=new Set;let n=0,o=0;s.forEach(t=>{const s=e[t];s.forEach(e=>{var s;const n=this.appMessagesManager.getMessageByPeer(t,e);!(null===(s=n.fwd_from)||void 0===s?void 0:s.from_name)||n.fromId||n.fwdFromId?i.add("P"+n.fromId):i.add("N"+n.fwd_from.from_name),n.media&&n.message&&++o}),n+=s.length});const r=i.size>2,l=[...i].map(e=>{const t=e[0];if(e=e.slice(1),"P"===t){const t=e.toPeerId();return t===a.a.myId?Object(T.d)("Chat.Accessory.Forward.You"):new wt.a({peerId:t,dialog:!1,onlyFirstName:r}).element}return r?e.split(" ")[0]:e}),{forwardElements:c}=this;Object(bt.a)(c.showCaption.checkboxField.label,"FORM").classList.toggle("hide",!o);const d=c.hideCaption.checkboxField.checked;o&&d?c.hideSender.checkboxField.setValueSilently(!0):void 0!==this.forwardWasDroppingAuthor&&(this.forwardWasDroppingAuthor?c.hideSender:c.showSender).checkboxField.setValueSilently(!0);const h=c.showSender.checkboxField.checked?"Chat.Accessory.Forward":"Chat.Accessory.Hidden",p=Object(T.d)(h,[n]),u=document.createDocumentFragment();let g,m;if(l.length<3?u.append(...Object(T.f)(l,!1)):u.append(l[0],Object(T.d)("AndOther",[l.length-1])),1===s.length){const t=s[0],i=e[t];if(g=this.appMessagesManager.getMessageByPeer(t,i[0]),m=!!g.grouped_id,m){const e=this.appMessagesManager.getMidsByMessage(g);(e.length!==n||e.find(e=>!i.includes(e)))&&(m=!1)}}const b=document.createDocumentFragment();if(m||1===n){const t=e[s[0]],i=this.appMessagesManager.wrapMessageForReply(g,void 0,t);b.append(u,": ",i)}else b.append(Object(T.d)("Chat.Accessory.Forward.From"),": ",u);let v=this.setTopInfo("forward",t,p,b);c.modifyArgs.forEach((e,t)=>{const i=e.textElement,n=T.c.weakMap.get(i);n.args=[t<2?s.length:o],n.update()}),this.forwardHover&&this.forwardHover.attachButtonListener(v,this.listenerSetter),this.forwarding=e};t()}initMessageReply(e){if(this.replyToMsgId===e)return;let t=this.chat.getMessage(e);const s=()=>{let i;"messageEmpty"===t._?(i=Object(T.d)("Loading"),this.chat.appMessagesManager.wrapSingleMessage(this.chat.peerId,e).then(i=>{this.replyToMsgId===e&&(t=i,"messageEmpty"===t._?this.clearHelper("reply"):s())})):i=new wt.a({peerId:t.fromId,dialog:!1}).element,this.setTopInfo("reply",s,i,t&&t.message,void 0,t),this.replyToMsgId=e};s()}clearHelper(e){"edit"===this.helperType&&"edit"!==e&&this.clearInput(),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null),"reply"!==e&&(this.replyToMsgId=void 0,this.forwarding=void 0),this.editMsgId=this.editMessage=void 0,this.helperType=this.helperFunc=void 0,this.chat.container.classList.contains("is-helper-active")&&(F.a.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"),this.t())}t(){Object(is.a)(this.chat.container,"is-toggling-helper",!0,150,()=>{this.chat.container.classList.remove("is-toggling-helper")})}setInputValue(e,t=!0,s=!0){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),Object(Le.b)(()=>{s&&Object(Eo.a)(this.messageInput),this.onMessageInput(),this.messageInput.scrollTop=this.messageInput.scrollHeight})}setTopInfo(e,t,s="",i="",n,a){if(this.willSendWebPage&&"reply"===e)return;"webpage"!==e&&(this.clearHelper(e),this.helperType=e,this.helperFunc=t);const o=this.replyElements.container,r=o.lastElementChild.previousElementSibling,l=r.classList.contains("reply");this.replyElements.iconBtn.replaceWith(this.replyElements.iconBtn=N(("webpage"===e?"link":e)+" active reply-icon",{noRipple:!0}));const c=js(s,i,a);return l?r.replaceWith(c):o.insertBefore(c,o.lastElementChild),"webpage"===e&&(c.style.cursor="default"),this.chat.container.classList.contains("is-helper-active")||(this.chat.container.classList.add("is-helper-active"),this.t()),ae.e||F.a.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),void 0!==n&&this.setInputValue(n),setTimeout(()=>{this.updateSendBtn()},0),c}}tr.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;class sr{constructor(e){this.floating=!1,Object(w.a)(this,e);const{divAndCaption:t,className:s}=this;t.container.classList.add("pinned-container","hide"),t.title.classList.add("pinned-container-title"),t.subtitle.classList.add("pinned-container-subtitle"),t.content.classList.add("pinned-container-content"),this.btnClose=document.createElement("button"),this.btnClose.classList.add("pinned-container-close",`pinned-${s}-close`,"btn-icon","tgico-close"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("pinned-container-wrapper"),Object(te.a)(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add("pinned-container-wrapper-utils"),this.wrapperUtils.append(this.btnClose),this.wrapper.append(...Array.from(t.container.children),this.wrapperUtils),t.container.append(this.wrapper),this.attachOnCloseEvent(this.btnClose)}attachOnCloseEvent(e){Object(l.b)(e,e=>{Object(c.a)(e),((this.onClose?this.onClose():null)||Promise.resolve(!0)).then(e=>{e&&this.toggle(!0)})},{listenerSetter:this.listenerSetter})}toggle(e){const t=this.divAndCaption.container.classList.contains("hide");if(void 0===e)e=!t;else if(e===t)return;const s=(this.floating||b.b.isMobile)&&!e;this.divAndCaption.container.classList.toggle("is-floating",s),this.divAndCaption.container.classList.toggle("hide",e),this.topbar.container.classList.toggle("is-pinned-floating",s),this.topbar.container.classList.toggle(`is-pinned-${this.className}-shown`,!e),this.topbar.setFloating(),this.topbar.setUtilsWidth()}isVisible(){return!this.divAndCaption.container.classList.contains("hide")}isFloating(){return this.divAndCaption.container.classList.contains("is-floating")}fill(e,t,s){this.divAndCaption.container.dataset.peerId=""+s.peerId,this.divAndCaption.container.dataset.mid=""+s.mid,this.divAndCaption.fill(e,t,s),this.topbar.setUtilsWidth()}}class ir extends Ae{constructor(e,t=!1){super({step:.01,min:0,max:1,vertical:t},1),this.listenerSetter=e,this.vertical=t,this.onMuteClick=e=>{e&&Object(c.a)(e),fe.muted=!fe.muted},this.setVolume=()=>{const{volume:e,muted:t}=fe;let s;s=!e||t?0:e>.5?3:e>0&&e<.25?1:2,ir.ICONS.forEach(e=>this.icon.classList.remove("tgico-"+e)),this.icon.classList.add("tgico-"+ir.ICONS[s]),this.mousedown||this.setProgress(t?0:e)},this.setListeners(),this.setHandlers({onScrub:e=>{const t=Math.max(Math.min(e,1),0);fe.muted=!1,fe.volume=t}});const s=this.btn=document.createElement("div");s.classList.add("btn-icon","player-volume");const i=this.icon=document.createElement("span");i.classList.add("player-volume__icon"),s.append(i,this.container),Object(l.b)(i,this.onMuteClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.a)("media_playback_params",this.setVolume),this.setVolume()}}ir.ICONS=["volume_off","volume_mute","volume_down","volume_up"];class nr extends sr{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new Be("pinned-audio",(e,t)=>{Object(k.a)(this.divAndCaption.title,e),Object(k.a)(this.divAndCaption.subtitle,t)}),onClose:()=>{fe.stop()},floating:!0}),this.topbar=e,this.chat=t,this.appMessagesManager=s,this.onPlaybackParams=e=>{this.fasterEl.classList.toggle("active",e.playbackRate>1),this.repeatEl.classList.remove("tgico-audio_repeat","tgico-audio_repeat_single"),this.repeatEl.classList.add(e.loop?"tgico-audio_repeat_single":"tgico-audio_repeat"),this.repeatEl.classList.toggle("active",e.loop||e.round)},this.onPause=()=>{this.toggleEl.classList.remove("flip-icon")},this.onStop=()=>{this.toggle(!0)},this.onMediaPlay=({doc:e,message:t,media:s,playbackParams:i})=>{var n,a;let o,r;const l="voice"!==e.type&&"round"!==e.type;if(l){const t=e.attributes.find(e=>"documentAttributeAudio"===e._);o=X.b.wrapEmojiText(null!==(a=null==t?void 0:t.title)&&void 0!==a?a:e.file_name),r=(null==t?void 0:t.performer)?X.b.wrapEmojiText(t.performer):Object(T.d)("AudioUnknownArtist")}else o=new wt.a({peerId:t.fromId,fromName:null===(n=t.fwd_from)||void 0===n?void 0:n.from_name}).element,r=Object(ne.d)(t.date);this.fasterEl.classList.toggle("hide",l),this.repeatEl.classList.toggle("hide",!l),this.onPlaybackParams(i),this.volumeSelector.setVolume(),this.progressLine.setMedia(s),this.fill(o,r,t),this.toggleEl.classList.toggle("flip-icon",!s.paused),this.toggle(!1)},this.divAndCaption.border.remove();const i=N("fast_rewind active",{noRipple:!0}),n=N("fast_forward active",{noRipple:!0}),o=(e,t)=>{Object(l.b)(e,e=>{Object(c.a)(e),t()},{listenerSetter:this.topbar.listenerSetter})};o(i,()=>{fe.previous()}),o(n,()=>{fe.next()}),this.toggleEl=N("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico","tgico"),o(this.toggleEl,()=>{fe.toggle()}),this.wrapper.prepend(this.wrapper.firstElementChild,i,this.toggleEl,n),this.volumeSelector=new ir(this.listenerSetter,!0);const r=document.createElement("div");r.classList.add("progress-line-container"),r.append(this.volumeSelector.container);const d=document.createElement("div");d.classList.add("pinned-audio-volume-tunnel"),this.volumeSelector.btn.classList.add("pinned-audio-volume","active"),this.volumeSelector.btn.prepend(d),this.volumeSelector.btn.append(r),this.repeatEl=N("audio_repeat",{noRipple:!0}),o(this.repeatEl,()=>{const e=fe.getPlaybackParams();e.round?e.loop?(fe.round=!1,fe.loop=!1):fe.loop=!fe.loop:fe.round=!0});const h=this.fasterEl=N("playback_2x",{noRipple:!0});o(h,()=>{fe.playbackRate=h.classList.contains("active")?1:1.75}),this.wrapperUtils.prepend(this.volumeSelector.btn,h,this.repeatEl);const p=document.createElement("div");p.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new Oe(void 0,void 0,!0,!0),this.progressLine.container.classList.add("pinned-audio-progress"),p.append(this.progressLine.container),this.wrapper.insertBefore(p,this.wrapperUtils),this.topbar.listenerSetter.add(a.a)("media_play",this.onMediaPlay),this.topbar.listenerSetter.add(a.a)("media_pause",this.onPause),this.topbar.listenerSetter.add(a.a)("media_stop",this.onStop),this.topbar.listenerSetter.add(a.a)("media_playback_params",this.onPlaybackParams);const u=fe.getPlayingDetails();u&&(this.onMediaPlay(u),this.onPlaybackParams(u.playbackParams))}destroy(){this.progressLine&&this.progressLine.removeListeners()}}var ar;!function(e){e[e.ONE=32]="ONE",e[e.TWO=15]="TWO",e[e.THREE=10]="THREE",e[e.FOUR=8]="FOUR",e[e.MORE=8]="MORE"}(ar||(ar={}));class or{constructor(){this.drawRect=(e,t,s,i,n)=>`M${e},${t+n}a${n},${n},0,0,1,${s},0v${i-2*n}a${n},${n},0,0,1,${-s},0Z`,this.getClipPath=(e,t,s)=>{let i="";if(2===s)i=this.drawRect(0,0,2,t,1)+this.drawRect(0,t+2,2,t,1);else for(let e=0;e<s;++e)i+=this.drawRect(0,(t+1)*e,2,t,1);return this.clipPath||(this.clipPath=document.createElementNS("http://www.w3.org/2000/svg","clipPath"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.clipPath.append(this.path)),this.clipPath.id=e,this.path.setAttributeNS(null,"d",i),this.clipPath},this.getBarHeight=(e,t)=>{let s;return e<=1?s=ar.ONE:2===e?s=ar.TWO:3===e?s=ar.THREE:4===e?s=ar.FOUR:e>3&&(s=ar.MORE),s},this.getMarkHeight=(e,t)=>{let s;return e<=1?s=ar.ONE:2===e?s=ar.TWO:3===e?s=ar.THREE:4===e?s=ar.FOUR:e>3&&(s=ar.MORE),s},this.getMarkTranslateY=(e,t,s)=>1===s?0:2===s?e?t+1:0:3===s?e?1===e?t+1:2*t+2+1:0:(t+1)*e,this.getTrackTranslateY=(e,t,s,i)=>t<=4||e<=1?0:e>=t-2?i-ar.ONE-s:(e-2)*s+1*e,this.getTrackHeight=(e,t)=>e<=3?ar.ONE:t*e+1*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add("pinned-message-border"),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),1===e)return this.count!==e&&(this.wrapper.className="pinned-message-border-wrapper-1",this.border.classList.remove("pinned-message-border-mask"),this.wrapper.innerHTML=this.wrapper.style.cssText=""),this.border;const s=this.getBarHeight(e,t),i=this.getMarkHeight(e,t),n=this.getTrackHeight(e,s),a="clipPath_"+e,o=this.getClipPath(a,s,e),r=this.getMarkTranslateY(t,s,e),l=this.getTrackTranslateY(t,e,s,n);return this.border.classList.toggle("pinned-message-border-mask",e>4),t<=1?(this.border.classList.add("mask-bottom"),this.border.classList.remove("mask-top")):t>=e-2?(this.border.classList.add("mask-top"),this.border.classList.remove("mask-bottom")):this.border.classList.add("mask-top","mask-bottom"),this.wrapper.className="pinned-message-border-wrapper",this.wrapper.style.cssText=`clip-path: url(#${a}); width: 2px; height: ${n}px; transform: translateY(-${l}px);`,this.svg||(this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttributeNS(null,"height","0"),this.svg.setAttributeNS(null,"width","0"),this.defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),this.defs.append(o),this.svg.append(this.defs),this.mark=document.createElement("div"),this.mark.classList.add("pinned-message-border-mark")),this.svg.parentElement||this.wrapper.append(this.svg,this.mark),this.mark.style.cssText=`height: ${i}px; transform: translateY(${r}px);`,this.count=e,this.index=t,this.border}}var rr=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class lr{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=lr.BASE_CLASS}getRow(e,t=!1){if(this.rows[e])return this.rows[e].element;const s=document.createElement("div"),i=!Object.keys(this.rows).length&&!t;return s.className=lr.BASE_CLASS+"-row"+(i?"":" is-hiding hide"),this.rows[e]={element:s,new:!0},this.container.append(s),s}clearRow(e){this.rows[e]&&(this.rows[e].element.remove(),delete this.rows[e])}clearRows(e){this.clearTimeout&&clearTimeout(this.clearTimeout),this.clearTimeout=window.setTimeout(()=>{for(const t in this.rows)+t!==e&&this.clearRow(+t)},lr.DURATION)}setNewRow(e,t=!1){const s=this.rows[e];s.new&&(t?(s.element.classList.remove("hide"),s.element.offsetLeft):s.element.classList.remove("is-hiding","hide"),delete s.new),this.clearRows(e)}animate(e,t,s=e>t,i=!1){if(e===t)return this.setNewRow(e);const n=this.rows[e],a=this.rows[t];if(!a&&!i)return this.setNewRow(e);const o=["from-top","from-bottom"];s||o.reverse(),n.element.classList.add(o[0]),n.element.classList.remove(o[1]),a&&(a.element.classList.add(o[1]),a.element.classList.remove(o[0])),n.new&&this.setNewRow(e,!0),n.element.classList.toggle("is-hiding",!1),a&&a.element.classList.toggle("is-hiding",!0),this.clearRows(e)}}lr.DURATION=200,lr.BASE_CLASS="animated-super";class cr{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=cr.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=cr.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=cr.BASE_CLASS+"-decimal-placeholder";const i=new lr;return i.container.className=cr.BASE_CLASS+"-decimal-wrapper",t.append(s,i.container),this.container.append(t),this.decimals[e]={container:t,placeholder:s,animatedSuper:i}}clear(e){this.clearTimeout&&clearTimeout(this.clearTimeout);const t=(""+e).length;t>=this.decimals.length||(this.clearTimeout=window.setTimeout(()=>{this.decimals.splice(t,this.decimals.length-t).forEach(e=>{e.container.remove()})},lr.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach(t=>{const s=+t.placeholder.innerText||0;t.animatedSuper.getRow(cr.EMPTY_INDEX,!0);t.animatedSuper.animate(cr.EMPTY_INDEX,s,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.clear(e)}setCount(e){const t=Array.from(""+this.previousNumber).map(e=>+e);Array.from(""+e).map(e=>+e).forEach((s,i)=>{var n;const a=this.getDecimal(i),o=a.animatedSuper.getRow(s,!0),r=null!==(n=t[i])&&void 0!==n?n:cr.EMPTY_INDEX;o.innerText=a.placeholder.innerText=""+s,a.animatedSuper.animate(s,r,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.hideLeft(e),this.previousNumber=e}}cr.EMPTY_INDEX=-1,cr.BASE_CLASS="animated-counter";class dr{constructor(e,t,s,i){this.topbar=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=i,this.pinnedMaxMid=0,this.pinnedMid=0,this.pinnedIndex=-1,this.wasPinnedIndex=0,this.wasPinnedMediaIndex=0,this.locked=!1,this.waitForScrollBottom=!1,this.count=0,this.mids=[],this.offsetIndex=0,this.loading=!1,this.loadedBottom=!1,this.loadedTop=!1,this.scrollDownListenerSetter=null,this.hidden=!1,this.getCurrentIndexPromise=null,this.isStatic=!1,this.debug=!1,this.listenerSetter=new R.a;const n=new Ue("pinned-message");this.pinnedMessageContainer=new sr({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:n,onClose:()=>rr(this,void 0,void 0,(function*(){return i.canPinMessage(this.topbar.peerId)?new ro(this.topbar.peerId,this.pinnedMid,!0):new ro(this.topbar.peerId,0,!0),!1}))}),this.pinnedMessageBorder=new or,n.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new lr,n.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new lr,this.animatedMedia.container.classList.add("pinned-message-media-container"),n.content.prepend(this.animatedMedia.container),this.animatedCounter=new cr(!0),n.title.append(Object(T.d)("PinnedMessage")," ",this.animatedCounter.container);const o=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(o),n.container.prepend(o),this.btnOpen=N("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),Object(l.b)(this.btnOpen,e=>{Object(c.a)(e),this.topbar.openPinned(!0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.a)("peer_pinned_messages",({peerId:e})=>{e===this.topbar.peerId&&(this.hidden&&this.pinnedMessageContainer.toggle(this.hidden=!1),this.loadedTop=this.loadedBottom=!1,this.pinnedIndex=-1,this.pinnedMid=0,this.count=0,this.mids=[],this.offsetIndex=0,this.pinnedMaxMid=0,this.setCorrectIndex(0))}),this.listenerSetter.add(a.a)("peer_pinned_hidden",({peerId:e})=>{e===this.topbar.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)}),this.setPinnedMessage=Object(lt.a)(()=>this._setPinnedMessage(),100,!0,!0),this.setCorrectIndexThrottled=Object(ws.a)(this.setCorrectIndex.bind(this),100,!1),this.isStatic="discussion"===this.chat.type}destroy(){this.pinnedMessageContainer.divAndCaption.container.remove(),this.pinnedMessageContainer.toggle(!0),this.listenerSetter.removeAll(),this.unsetScrollDownListener(!1)}setCorrectIndex(e){if(this.isStatic)return;if(this.locked||this.hidden)return;if((this.loadedBottom||this.loadedTop)&&!this.count)return;let t=this.chat.bubbles.getBubbleByPoint("bottom");if(!t)return;const s=t.dataset.mid;t&&void 0!==s&&this.testMid(+s,e)}testMid(e,t){if(this.isStatic)return;if(this.hidden)return;let s=this.mids.findIndex(t=>t<=e);if(-1===s||this.isNeededMore(s)){if(!(this.loadedTop&&e<this.mids[this.mids.length-1]))return void(this.getCurrentIndexPromise||(this.getCurrentIndexPromise=this.getCurrentIndex(e,void 0!==t)));s=this.mids.length-1+this.offsetIndex}else s+=this.offsetIndex;if(this.pinnedIndex!==s){if(this.waitForScrollBottom&&void 0!==t&&(0===this.pinnedIndex||this.pinnedIndex>s))return;this.pinnedIndex=s,this.pinnedMid=this.mids.find(t=>t<=e)||this.mids[this.mids.length-1],this.setPinnedMessage()}}isNeededMore(e){return this.count>dr.LOAD_COUNT&&(!this.loadedBottom&&e<=dr.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=dr.LOAD_OFFSET)}getCurrentIndex(e,t=!0){return rr(this,void 0,void 0,(function*(){if(!this.loading){this.loading=!0;try{let s=!1;const i=[this.appMessagesManager.getSearch({peerId:this.topbar.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:dr.LOAD_COUNT,backLimit:dr.LOAD_COUNT}).then(e=>(s=!0,e))];if(!this.pinnedMaxMid){const e=this.appMessagesManager.getPinnedMessage(this.topbar.peerId).then(e=>{e.maxId&&(this.pinnedMaxMid=e.maxId,!s&&t&&(this.mids=[this.pinnedMaxMid],this.count=e.count,this.pinnedIndex=0,this.pinnedMid=this.mids[0],this.setPinnedMessage()))});i.push(e)}const n=(yield Promise.all(i))[0];let a=n.history.findIndex(t=>t.mid<=e);-1===a&&(a=n.history.length),this.offsetIndex=n.offset_id_offset?n.offset_id_offset-a:0,this.mids=n.history.map(e=>e.mid).slice(),this.count=n.count,this.count||this.pinnedMessageContainer.toggle(!0),this.loadedTop=this.offsetIndex+this.mids.length===this.count,this.loadedBottom=!this.offsetIndex,this.debug&&this.chat.log("[PM]: getCurrentIndex result:",e,n,a,this.offsetIndex,this.loadedTop,this.loadedBottom)}catch(e){this.chat.log.error("[PM]: getCurrentIndex error",e)}this.loading=!1,this.locked?this.testMid(e):t&&this.setCorrectIndex(0),this.getCurrentIndexPromise=null}}))}setScrollDownListener(){this.waitForScrollBottom=!0,this.scrollDownListenerSetter||(this.scrollDownListenerSetter=new R.a,function(e,t,s,i){if(he.a){let n;const a={passive:!0};i.add(e)("touchstart",t=>{t.touches.length>1?r():(n=t.touches[0].clientY,i.add(e)("touchmove",o,a),i.add(e)("touchend",r,a))},a);const o=e=>{const i=e.touches[0].clientY,a=i<n;"bottom"===t&&a?s():"top"!==t||a||s(),n=i},r=()=>{i.removeManual(e,"touchmove",o,a),i.removeManual(e,"touchend",r,a)}}else i.add(e)("wheel",e=>{const i=e.deltaY>0;"bottom"===t&&i?s():"top"!==t||i||s()},{passive:!0})}(this.chat.bubbles.scrollable.container,"bottom",()=>{this.unsetScrollDownListener()},this.scrollDownListenerSetter))}unsetScrollDownListener(e=!0){this.waitForScrollBottom=!1,this.scrollDownListenerSetter&&(this.scrollDownListenerSetter.removeAll(),this.scrollDownListenerSetter=null),e&&this.setCorrectIndex(0)}handleFollowingPinnedMessage(){return rr(this,void 0,void 0,(function*(){this.locked=!0,this.debug&&this.chat.log("[PM]: handleFollowingPinnedMessage");try{this.setScrollDownListener();const e=this.chat.setPeerPromise;e instanceof Promise&&(yield e),yield Object(Ds.c)(),this.getCurrentIndexPromise&&(yield this.getCurrentIndexPromise),this.debug&&this.chat.log("[PM]: handleFollowingPinnedMessage: unlock"),this.locked=!1}catch(e){this.chat.log.error("[PM]: handleFollowingPinnedMessage error:",e),this.locked=!1,this.waitForScrollBottom=!1,this.setCorrectIndex(0)}}))}followPinnedMessage(e){return rr(this,void 0,void 0,(function*(){const t=this.chat.getMessage(e);t&&!t.deleted&&(this.chat.setMessageId(e),(this.chat.setPeerPromise||Promise.resolve()).then(()=>{this.handleFollowingPinnedMessage(),this.testMid(this.pinnedIndex>=this.count-1?this.pinnedMaxMid:e-1)}))}))}_setPinnedMessage(){return rr(this,void 0,void 0,(function*(){const e=this.count;if(e){const t=this.pinnedIndex,s=this.chat.getMessage(this.pinnedMid),i=0===t;this.animatedCounter.container.classList.toggle("is-last",i),i||this.animatedCounter.setCount(e-t),this.pinnedMessageContainer.toggle(!1);const n=t>this.wasPinnedIndex;this.debug&&this.chat.log("[PM]: setPinnedMessage: fromTop",n,t,this.wasPinnedIndex);const a=this.animatedSubtitle.getRow(t),o=this.animatedMedia.getRow(t);o.classList.add("pinned-message-media");const r=[],l=Ne({title:void 0,titleEl:null,subtitle:s.message,subtitleEl:a,message:s,mediaEl:o,loadPromises:r});yield Promise.all(r),this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-media",l),this.animatedSubtitle.animate(t,this.wasPinnedIndex),l?(this.animatedMedia.animate(t,this.wasPinnedMediaIndex),this.wasPinnedMediaIndex=t):this.animatedMedia.clearRows(),this.pinnedMessageBorder.render(e,e-t-1),this.wasPinnedIndex=t,this.pinnedMessageContainer.divAndCaption.container.dataset.mid=""+s.mid}else this.pinnedMessageContainer.toggle(!0),this.wasPinnedIndex=0;this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-many",this.count>1)}))}}dr.LOAD_COUNT=50,dr.LOAD_OFFSET=5;var hr=Wa,pr=s(43);class ur extends ut{constructor(e){super("popup-mute",{peerId:e,titleLangKey:"Notifications",buttons:[{langKey:"ChatList.Context.Mute",callback:()=>{i.a.mutePeer(e,-1===s?Me.b:Object(pr.a)(!0)+s)}}],body:!0});const t=[{time:3600,langKey:"ChatList.Mute.1Hour"},{time:14400,langKey:"ChatList.Mute.4Hours"},{time:28800,langKey:"ChatList.Mute.8Hours"},{time:86400,langKey:"ChatList.Mute.1Day"},{time:259200,langKey:"ChatList.Mute.3Days"},{time:-1,langKey:"ChatList.Mute.Forever"}].map(e=>new Ze({radioField:new nt({langKey:e.langKey,name:"mute-time",value:""+e.time})}));let s;const n=et(t,e=>{s=+e});t[t.length-1].radioField.checked=!0;const a=new Kn({noShadow:!0,noDelimiter:!0});a.content.append(n),this.body.append(a.container),this.show()}}class gr{constructor(e,t,s,i,n,a,o,r,l){this.chat=e,this.appSidebarRight=t,this.appMessagesManager=s,this.appPeersManager=i,this.appChatsManager=n,this.appNotificationsManager=a,this.appProfileManager=o,this.appUsersManager=r,this.appGroupCallsManager=l,this.verifyButtons=e=>{const t=!!e||!(!this.btnMore||!this.btnMore.classList.contains("menu-open"));e&&Object(c.a)(e);const s=e=>{e.forEach(e=>{e.element.classList.toggle("hide",!e.verify())})};t&&(s(this.menuButtons),this.menuButtons[this.menuButtons.length-1].element.lastChild.replaceWith(Object(T.d)(this.appPeersManager.getDeleteButtonText(this.peerId)))),s(this.buttonsToVerify)},this.verifyVideoChatButton=e=>{var t;if(!hr||this.peerId.isUser())return!1;const s=this.appGroupCallsManager.groupCall,i=this.peerId.toChatId();if((null==s?void 0:s.chatId)===i)return!1;if(e&&(this.peerId.isBroadcast()&&"group"===e||this.peerId.isAnyGroup()&&"broadcast"===e))return!1;return(null===(t=this.appChatsManager.getChatTyped(i).pFlags)||void 0===t?void 0:t.call_active)||this.appChatsManager.hasRights(i,"manage_call")},this.verifyCallButton=e=>{if(!qa||!this.peerId.isUser())return!1;const t=this.peerId.toUserId(),s=this.appProfileManager.getCachedFullUser(t);return!!s&&!!("voice"===e?s.pFlags.phone_calls_available:s.pFlags.video_calls_available)},this.onJoinGroupCallClick=()=>{this.chat.appImManager.joinGroupCall(this.peerId)},this.onMuteClick=()=>{new ur(this.peerId)},this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(e,t)=>{this.container.classList.toggle("is-pinned-floating",b.b.isMobile),this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-floating",t===b.a.mobile),this.onResize()},this.setUtilsWidth=(e=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),ae.g&&e&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame(()=>{ae.g&&e&&this.chatUtils.classList.remove("hide");const t=this.chatUtils.getBoundingClientRect().width;this.chat.log("utils width:",t),this.container.style.setProperty("--utils-width",t+"px"),this.setUtilsRAF=0})},this.setFloating=()=>{const e=[this.chatAudio,this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer].filter(Boolean).reduce((e,t)=>{const s=t.isFloating();return this.container.classList.toggle(`is-pinned-${t.className}-floating`,s),t.isVisible()?e+ +s:e},0);this.container.dataset.floating=""+e},this.setPeerStatus=(e=!1)=>{if(!this.subtitle)return;const t=this.peerId;this.chat.appImManager.setPeerStatus(this.peerId,this.subtitle,e,!1,()=>t===this.peerId)},this.listenerSetter=new R.a,this.menuButtons=[],this.buttonsToVerify=[]}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar"),this.container.dataset.floating="0",this.btnBack=N("left sidebar-close-button",{noRipple:!0}),this.chatInfoContainer=document.createElement("div"),this.chatInfoContainer.classList.add("chat-info-container"),this.chatInfo=document.createElement("div"),this.chatInfo.classList.add("chat-info");const e=document.createElement("div");e.classList.add("person");const t=document.createElement("div");t.classList.add("content");const s=document.createElement("div");s.classList.add("top"),this.title=document.createElement("div"),this.title.classList.add("user-title"),s.append(this.title);const i=document.createElement("div");i.classList.add("bottom"),this.subtitle&&i.append(this.subtitle),t.append(s,i),this.avatarElement&&e.append(this.avatarElement),e.append(t),this.chatInfo.append(e),this.chatUtils=document.createElement("div"),this.chatUtils.classList.add("chat-utils"),this.chatAudio=new nr(this,this.chat,this.appMessagesManager),this.menuButtons.length&&(this.btnMore=bi({listenerSetter:this.listenerSetter},"bottom-left",this.menuButtons,this.verifyButtons)),this.chatUtils.append(...[this.pinnedMessage?this.pinnedMessage.pinnedMessageContainer.divAndCaption.container:null,this.btnJoin,this.btnPinned,this.btnCall,this.btnGroupCall,this.btnMute,this.btnSearch,this.btnMore].filter(Boolean)),this.pushButtonToVerify(this.btnCall,this.verifyCallButton.bind(this,"voice")),this.pushButtonToVerify(this.btnGroupCall,this.verifyVideoChatButton),this.chatInfoContainer.append(this.btnBack,this.chatInfo,this.chatUtils),this.container.append(this.chatInfoContainer),this.chatAudio&&this.container.append(this.chatAudio.divAndCaption.container),this.listenerSetter.add(window)("resize",this.onResize),this.listenerSetter.add(b.b)("changeScreen",this.onChangeScreen),Object(l.b)(this.container,e=>{const t=Object(Ce.a)(e.target,"pinned-container");if(Object(ti.a)(),t){if(Object(c.a)(e),Object(Ce.a)(e.target,"progress-line"))return;const s=+t.dataset.mid;if(t.classList.contains("pinned-message"))this.pinnedMessage.followPinnedMessage(s);else{const e=t.dataset.peerId.toPeerId(),i=fe.getSearchContext();this.chat.appImManager.setInnerPeer({peerId:e,lastMsgId:s,type:i.isScheduled?"scheduled":i.threadId?"discussion":void 0,threadId:i.threadId})}}else b.b.activeScreen===b.a.medium&&document.body.classList.contains("is-left-column-shown")?n():Object(bt.a)(e.target,"AVATAR-ELEMENT")?this.appSidebarRight.toggleSidebar(!document.body.classList.contains("is-right-column-shown")):this.appSidebarRight.toggleSidebar(!0)},{listenerSetter:this.listenerSetter});const n=e=>{if(e&&Object(c.a)(e),b.b.activeScreen===b.a.medium&&document.body.classList.contains("is-left-column-shown"))this.chat.appImManager.setPeer({peerId:this.peerId});else{const e=0===this.chat.appImManager.chats.indexOf(this.chat);F.a.back(e?"im":"chat")}};Object(l.b)(this.btnBack,n,{listenerSetter:this.listenerSetter})}pushButtonToVerify(e,t){e&&this.buttonsToVerify.push({element:e,verify:t})}constructUtils(){this.menuButtons=[{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch()},verify:()=>b.b.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:()=>"chat"===this.chat.type&&a.a.myId!==this.peerId&&!this.appNotificationsManager.isPeerLocalMuted(this.peerId,!1)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:()=>{this.appMessagesManager.togglePeerMute(this.peerId)},verify:()=>"chat"===this.chat.type&&a.a.myId!==this.peerId&&this.appNotificationsManager.isPeerLocalMuted(this.peerId,!1)},{icon:"comments",text:"ViewDiscussion",onClick:()=>{const e=this.chat.bubbles.getMiddleware();Promise.resolve(this.appProfileManager.getChannelFull(this.peerId.toChatId())).then(t=>{e()&&t.linked_chat_id&&this.chat.appImManager.setInnerPeer({peerId:t.linked_chat_id.toPeerId(!0)})})},verify:()=>{var e;const t=this.appProfileManager.getCachedFullChat(this.peerId.toChatId());return"chat"===this.chat.type&&!!(null===(e=t)||void 0===e?void 0:e.linked_chat_id)}},{icon:"phone",text:"Call",onClick:this.onCallClick.bind(this,"voice"),verify:this.verifyCallButton.bind(this,"voice")},{icon:"videocamera",text:"VideoCall",onClick:this.onCallClick.bind(this,"video"),verify:this.verifyCallButton.bind(this,"video")},{icon:"videochat",text:"PeerInfo.Action.LiveStream",onClick:this.onJoinGroupCallClick,verify:this.verifyVideoChatButton.bind(this,"broadcast")},{icon:"videochat",text:"PeerInfo.Action.VoiceChat",onClick:this.onJoinGroupCallClick,verify:this.verifyVideoChatButton.bind(this,"group")},{icon:"select",text:"Chat.Menu.SelectMessages",onClick:()=>{const e=this.chat.selection;e.toggleSelection(!0,!0),M.c.getState().then(t=>{if(t.chatContextMenuHintWasShown)return;const s=e.toggleByElement.bind(e);e.toggleByElement=t=>{M.c.pushToState("chatContextMenuHintWasShown",!0),ot(Object(T.d)("Chat.Menu.Hint")),e.toggleByElement=s,e.toggleByElement(t)}})},verify:()=>!this.chat.selection.isSelecting&&!!this.chat.bubbles.getRenderedLength()},{icon:"select",text:"Chat.Menu.ClearSelection",onClick:()=>{this.chat.selection.cancelSelection()},verify:()=>this.chat.selection.isSelecting},{icon:"adduser",text:"AddContact",onClick:()=>{if(!this.appSidebarRight.isTabExists(Nt)){const e=new Nt(this.appSidebarRight);e.peerId=this.peerId,e.open(),this.appSidebarRight.toggleSidebar(!0)}},verify:()=>this.peerId.isUser()&&!this.appPeersManager.isContact(this.peerId)},{icon:"forward",text:"ShareContact",onClick:()=>{const e=this.peerId;new Pt({peerTypes:["dialogs","contacts"],onSelect:t=>new Promise((s,i)=>{new ut("",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new wt.a({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:()=>{s(),this.appMessagesManager.sendContact(t,e),this.chat.appImManager.setInnerPeer({peerId:t})}},{langKey:"Cancel",callback:()=>{i()},isCancel:!0}],peerId:t,overlayClosable:!0}).show()}),placeholder:"ShareModal.Search.Placeholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})},verify:()=>a.a.myId!==this.peerId&&this.peerId.isUser()&&this.appPeersManager.isContact(this.peerId)&&!!this.appUsersManager.getUser(this.peerId.toUserId()).phone},{icon:"lock",text:"BlockUser",onClick:()=>{new ut("",{peerId:this.peerId,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new wt.a({peerId:this.peerId}).element],buttons:[{langKey:"BlockUser",isDanger:!0,callback:()=>{this.appUsersManager.toggleBlock(this.peerId,!0).then(e=>{e&&rt({langPackKey:"UserBlocked"})})}}]}).show()},verify:()=>{var e;if(!this.peerId.isUser())return!1;const t=this.appProfileManager.getCachedFullUser(this.peerId.toUserId());return this.peerId!==a.a.myId&&t&&!(null===(e=t.pFlags)||void 0===e?void 0:e.blocked)}},{icon:"lockoff",text:"Unblock",onClick:()=>{this.appUsersManager.toggleBlock(this.peerId,!1).then(e=>{e&&rt({langPackKey:"UserUnblocked"})})},verify:()=>{var e;const t=this.appProfileManager.getCachedFullUser(this.peerId.toUserId());return!!(null===(e=null==t?void 0:t.pFlags)||void 0===e?void 0:e.blocked)}},{icon:"delete danger",text:"Delete",onClick:()=>{new Ot(this.peerId)},verify:()=>"chat"===this.chat.type&&!!this.appMessagesManager.getDialogOnly(this.peerId)}],this.btnSearch=N("search"),this.attachClickEvent(this.btnSearch,e=>{this.chat.initSearch()},!0)}attachClickEvent(e,t,s){Object(l.b)(e,e=>{Object(c.a)(e),!s&&Object(ti.a)(),t(e)},{listenerSetter:this.listenerSetter})}onCallClick(e){this.chat.appImManager.callUser(this.peerId.toUserId(),e)}constructPeerHelpers(){return this.avatarElement=new fc,this.avatarElement.isDialog=!0,this.avatarElement.classList.add("avatar-42","person-avatar"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("info"),this.pinnedMessage=new dr(this,this.chat,this.appMessagesManager,this.appPeersManager),this.btnJoin=Object(B.a)("btn-primary btn-color-primary chat-join hide"),this.btnCall=N("phone"),this.btnGroupCall=N("videochat"),this.btnPinned=N("pinlist"),this.btnMute=N("mute"),this.attachClickEvent(this.btnCall,this.onCallClick.bind(this,"voice")),this.attachClickEvent(this.btnGroupCall,this.onJoinGroupCallClick),this.attachClickEvent(this.btnPinned,()=>{this.openPinned(!0)}),this.attachClickEvent(this.btnMute,this.onMuteClick),this.attachClickEvent(this.btnJoin,()=>{const e=this.chat.bubbles.getMiddleware();this.btnJoin.setAttribute("disabled","true");const t=this.peerId.toChatId();let s;s=this.appChatsManager.isChannel(t)?this.appChatsManager.joinChannel(t):this.appChatsManager.addChatUser(t,a.a.myId),s.finally(()=>{e()&&this.btnJoin.removeAttribute("disabled")})}),this.listenerSetter.add(a.a)("chat_update",e=>{var t,s;if(this.peerId===e.toPeerId(!0)){const i=this.appChatsManager.getChat(e);this.btnJoin.classList.toggle("hide",!(null===(s=null===(t=i)||void 0===t?void 0:t.pFlags)||void 0===s?void 0:s.left)),this.setUtilsWidth(),this.verifyButtons()}}),this.listenerSetter.add(a.a)("dialog_notify_settings",e=>{e.peerId===this.peerId&&this.setMutedState()}),this.listenerSetter.add(a.a)("peer_typings",({peerId:e})=>{this.peerId===e&&this.setPeerStatus()}),this.listenerSetter.add(a.a)("user_update",e=>{this.peerId===e.toPeerId()&&this.setPeerStatus()}),this.listenerSetter.add(a.a)("peer_full_update",e=>{this.peerId===e&&this.verifyButtons()}),this.pinnedMessage&&this.chat.addEventListener("setPeer",(e,t)=>{const s=this.chat.bubbles.getMiddleware();M.c.getState().then(i=>{s()&&(this.pinnedMessage.hidden=!!i.hiddenPinnedMessages[this.chat.peerId],t?(this.pinnedMessage.unsetScrollDownListener(),this.pinnedMessage.testMid(e,0)):this.pinnedMessage.locked||(this.pinnedMessage.handleFollowingPinnedMessage(),this.pinnedMessage.testMid(e)))})}),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4),this}constructPinnedHelpers(){this.listenerSetter.add(a.a)("peer_pinned_messages",({peerId:e,mids:t})=>{e===this.peerId&&t&&this.setTitle()})}constructDiscussionHelpers(){this.pinnedMessage=new dr(this,this.chat,this.appMessagesManager,this.appPeersManager)}openPinned(e){this.chat.appImManager.setInnerPeer({peerId:this.peerId,lastMsgId:e?+this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.dataset.mid:0,type:"pinned"})}destroy(){this.listenerSetter.removeAll(),window.clearInterval(this.setPeerStatusInterval),this.pinnedMessage&&this.pinnedMessage.destroy(),this.chatAudio&&this.chatAudio.destroy(),delete this.chatAudio,delete this.pinnedMessage}setPeer(e){this.wasPeerId=this.peerId,this.peerId=e,this.container.style.display=e?"":"none"}finishPeerChange(e,t,s){var i,n;const a=this.peerId;this.avatarElement&&this.avatarElement.updateWithOptions({peerId:a});const o=this.appPeersManager.isBroadcast(a);if(this.btnMute&&this.btnMute.classList.toggle("hide",!o),this.btnJoin)if(this.appPeersManager.isAnyChat(a)){const e=a.toChatId();Object(k.a)(this.btnJoin,Object(T.d)(this.appChatsManager.isBroadcast(e)?"Chat.Subscribe":"ChannelJoin")),this.btnJoin.classList.toggle("hide",!(null===(n=null===(i=this.appChatsManager.getChat(e))||void 0===i?void 0:i.pFlags)||void 0===n?void 0:n.left))}else this.btnJoin.classList.add("hide");this.setUtilsWidth(),this.verifyButtons();const r=this.chat.bubbles.getMiddleware();if(this.pinnedMessage)if("chat"===this.chat.type){if(void 0!==this.wasPeerId){const e=new dr(this,this.chat,this.appMessagesManager,this.appPeersManager);this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.replaceWith(e.pinnedMessageContainer.divAndCaption.container),this.pinnedMessage.destroy(),this.pinnedMessage=e}M.c.getState().then(t=>{r()&&(this.pinnedMessage.hidden=!!t.hiddenPinnedMessages[a],e||this.pinnedMessage.setCorrectIndex(0))})}else"discussion"===this.chat.type&&(this.pinnedMessage.pinnedMid=this.chat.threadId,this.pinnedMessage.count=1,this.pinnedMessage.pinnedIndex=0,this.pinnedMessage._setPinnedMessage());Object(Le.b)(()=>{this.setTitle(),this.setPeerStatus(!0),this.setMutedState()})}setTitle(e){let t;"pinned"===this.chat.type?(t=void 0===e?Object(T.d)("Loading"):Object(T.d)("PinnedMessagesCount",[e]),void 0===e&&this.appMessagesManager.getSearchCounters(this.peerId,[{_:"inputMessagesFilterPinned"}],!1).then(e=>{const t=e[0].count;if(this.setTitle(t),!t){this.chat.appImManager.setPeer();const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)}})):"scheduled"===this.chat.type?(t=this.peerId===a.a.myId?Object(T.d)("Reminders"):Object(T.d)("ScheduledMessages"),void 0===e&&this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>{this.setTitle(e.length)})):"discussion"===this.chat.type?(t=void 0===e?Object(T.d)("Loading"):Object(T.d)("Chat.Title.Comments",[e]),void 0===e&&Promise.all([this.appMessagesManager.getHistory(this.peerId,0,1,0,this.chat.threadId),Promise.resolve()]).then(()=>{const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId).count;null===e?setTimeout(()=>{this.setTitle()},30):this.setTitle(e)})):"chat"===this.chat.type&&(t=new wt.a({peerId:this.peerId,dialog:!0}).element),Object(k.a)(this.title,t),"chat"===this.chat.type&&this.title.append(...Kt(this.peerId))}setMutedState(){if(!this.btnMute)return;const e=this.peerId;let t=this.appNotificationsManager.isPeerLocalMuted(e,!1);this.appPeersManager.isBroadcast(e)?(this.btnMute.classList.remove("tgico-mute","tgico-unmute"),this.btnMute.classList.add(t?"tgico-unmute":"tgico-mute"),this.btnMute.style.display=""):this.btnMute.style.display="none"}}class mr extends H{constructor(){super(...arguments),this.threadId=0,this.query=""}onOpenAfterTimeout(){this.appSearch.beginSearch(this.peerId,this.threadId,this.query)}init(){this.container.id="search-private-container",this.container.classList.add("chatlist-container"),this.inputSearch=new j("Search"),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=N("calendar sidebar-header-right"),this.header.append(this.btnPickDate);const e=document.createElement("div");e.classList.add("chatlist-container"),this.scrollable.container.replaceWith(e),this.appSearch=new A(e,this.inputSearch,{messages:new x("Chat.Search.PrivateSearch","messages")})}open(e,t,s,i){const n=super.open();return this.peerId?this.appSearch.beginSearch(this.peerId,this.threadId,i):(this.query=i,this.peerId=e,this.threadId=t,this.onDatePick=s,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&Object(l.b)(this.btnPickDate,()=>{new Xn(new Date,this.onDatePick).show()}),i&&this.appSearch.searchInput.inputField.setValueSilently(i),ts.toggleSidebar(!0)),n}}class br{constructor(e,t,s){this.topbar=e,this.chat=t,this.foundCount=0,this.selectedIndex=0,this.onDateClick=e=>{Object(c.a)(e),new Xn(new Date,this.chat.bubbles.onDatePick).show()},this.onResultsClick=e=>{const t=Object(bt.a)(e.target,"LI");t&&this.selectResult(t)},this.onFooterClick=e=>{this.foundCount&&(this.chat.bubbles.bubblesContainer.classList.toggle("search-results-active"),this.results.classList.toggle("active"))},this.onUpClick=e=>{Object(c.a)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex+1])},this.onDownClick=e=>{Object(c.a)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex-1])},this.element=document.createElement("div"),this.element.classList.add("sidebar-header","chat-search","chatlist-container"),this.backBtn=document.createElement("button"),this.backBtn.classList.add("btn-icon","tgico-left","sidebar-close-button"),Object(te.a)(this.backBtn);const i=this.listenerSetter=new R.a,n=(e,t)=>{Object(l.b)(e,t,{listenerSetter:i})};n(this.backBtn,()=>{this.destroy()}),this.inputSearch=new j("Search"),this.results=document.createElement("div"),this.results.classList.add("chat-search-results","chatlist-container"),this.searchGroup=new x(!1,"messages",void 0,"",!1),n(this.searchGroup.list,this.onResultsClick),this.appSearch=new A(this.results,this.inputSearch,{messages:this.searchGroup},e=>{this.foundCount=e,this.foundCount?this.selectResult(this.searchGroup.list.children[0]):(Object(k.a)(this.foundCountEl,this.inputSearch.value?Object(T.d)("NoResult"):""),this.results.classList.remove("active"),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active"),this.upBtn.setAttribute("disabled","true"),this.downBtn.setAttribute("disabled","true"))}),this.appSearch.beginSearch(this.chat.peerId,this.chat.threadId),this.chat.bubbles.bubblesContainer.append(this.results),this.footer=document.createElement("div"),this.footer.classList.add("chat-search-footer"),n(this.footer,this.onFooterClick),Object(te.a)(this.footer),this.foundCountEl=document.createElement("span"),this.foundCountEl.classList.add("chat-search-count"),this.dateBtn=document.createElement("button"),this.dateBtn.classList.add("btn-icon","tgico-calendar"),this.controls=document.createElement("div"),this.controls.classList.add("chat-search-controls"),this.upBtn=document.createElement("button"),this.upBtn.classList.add("btn-icon","tgico-up"),this.downBtn=document.createElement("button"),this.downBtn.classList.add("btn-icon","tgico-down"),this.upBtn.setAttribute("disabled","true"),this.downBtn.setAttribute("disabled","true"),n(this.dateBtn,this.onDateClick),n(this.upBtn,this.onUpClick),n(this.downBtn,this.onDownClick),this.controls.append(this.upBtn,this.downBtn),this.footer.append(this.foundCountEl,this.dateBtn,this.controls),this.topbar.container.parentElement.insertBefore(this.footer,t.input.chatInput),this.element.append(this.backBtn,this.inputSearch.container),this.topbar.container.classList.add("hide-pinned"),this.topbar.container.parentElement.append(this.element),this.inputSearch.input.focus(),s&&this.setQuery(s),ae.f||(this.navigationItem={type:"mobile-search",onPop:()=>{this.destroy()}},F.a.pushItem(this.navigationItem))}destroy(){this.topbar.container.classList.remove("hide-pinned"),this.element.remove(),this.inputSearch.remove(),this.results.remove(),this.footer.remove(),this.listenerSetter.removeAll(),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active"),this.chat.search=void 0,F.a.removeItem(this.navigationItem)}setQuery(e){this.inputSearch.inputField.value=e}selectResult(e){if(this.setPeerPromise)return this.setPeerPromise;const t=e.dataset.peerId.toPeerId(),s=+e.dataset.mid||void 0,i=Object(Bs.a)(e);i===this.foundCount-1?this.upBtn.setAttribute("disabled","true"):this.upBtn.removeAttribute("disabled"),i?this.downBtn.removeAttribute("disabled"):this.downBtn.setAttribute("disabled","true"),this.results.classList.remove("active"),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active");const n=this.chat.setPeer(t,s);this.setPeerPromise=(n instanceof Promise?n:Promise.resolve(n)).then(()=>{this.selectedIndex=i,Object(k.a)(this.foundCountEl,Object(T.d)("Of",[i+1,this.foundCount]));const e=this.searchGroup.list.childElementCount;this.selectedIndex>=e-6&&this.appSearch.searchMore()}).finally(()=>{this.setPeerPromise=null})}}class vr{constructor(){this.canvases=new Set}static getInstance(e){let t=this.INSTANCES.find(t=>Object(ge.a)(t.options,e));return t||(t=new vr,t.init(e),this.INSTANCES.push(t)),t}init(e){this.options=e}renderToCanvas(e){return this.renderImageFromUrl(this.options.url).then(()=>this.fillCanvas(e))}renderImageFromUrl(e){if(this.renderImageFromUrlPromise)return this.renderImageFromUrlPromise;const t=this.img=document.createElement("img");return t.crossOrigin="anonymous",this.renderImageFromUrlPromise=Object(ps.b)(t,e,!1).then(()=>t)}cleanup(e){this.canvases.delete(e),this.canvases.size||(Object(V.a)(vr.INSTANCES,this),this.objectUrl&&URL.revokeObjectURL(this.objectUrl))}fillCanvas(e){const t=e.getContext("2d");t.fillStyle instanceof CanvasPattern&&t.clearRect(0,0,e.width,e.height);const s=this.img;let i=s.width,n=s.height;i*=e.height/n,n=e.height,this.options.mask?(t.fillStyle="#000",t.fillRect(0,0,e.width,e.height),t.globalCompositeOperation="destination-out"):t.globalCompositeOperation="source-over";for(let a=0;a<e.width;a+=i)for(let o=0;o<e.height;o+=n)t.drawImage(s,a,o,i,n)}setCanvasDimensions(e){const t=Math.min(2,window.devicePixelRatio);e.width=this.options.width*t,e.height=this.options.height*t*(b.b.activeScreen===b.a.large?1.5:1)}createCanvas(){const e=document.createElement("canvas");return this.canvases.add(e),this.setCanvasDimensions(e),e}resize(e,t){this.init(Object.assign(Object.assign({},this.options),{width:e,height:t}));const s=[];for(const e of this.canvases)this.setCanvasDimensions(e),s.push(this.renderToCanvas(e));return Promise.all(s)}static resizeInstances(e,t){return Promise.all(this.INSTANCES.map(s=>s.resize(e,t)))}}vr.INSTANCES=[];class fr extends D.a{constructor(e,t,s,i,n,a,o,r,l,c,d,h,p,u,g,m,b,v,f,y,w){super(),this.appImManager=e,this.appChatsManager=t,this.appDocsManager=s,this.appInlineBotsManager=i,this.appMessagesManager=n,this.appPeersManager=a,this.appPhotosManager=o,this.appProfileManager=r,this.appStickersManager=l,this.appUsersManager=c,this.appWebPagesManager=d,this.appPollsManager=h,this.apiManager=p,this.appDraftsManager=u,this.serverTimeManager=g,this.storage=m,this.appNotificationsManager=b,this.appEmojiManager=v,this.appMessagesIdsManager=f,this.appGroupCallsManager=y,this.appReactionsManager=w,this.type="chat",this.container=document.createElement("div"),this.container.classList.add("chat","tabs-tab"),this.backgroundEl=document.createElement("div"),this.backgroundEl.classList.add("chat-background"),this.log=Object(Y.b)("CHAT",Y.a.Log|Y.a.Warn|Y.a.Debug|Y.a.Error),this.peerId=Me.c,this.container.append(this.backgroundEl),this.appImManager.chatsContainer.append(this.container),this.backgroundTempId=0}setBackground(e,t){const s=a.a.getTheme();let i;if(!!s.background.color&&!s.background.slug&&!s.background.intensity&&"grabbing"===document.documentElement.style.cursor&&this.gradientRenderer&&!this.patternRenderer)return this.gradientCanvas.dataset.colors=s.background.color,this.gradientRenderer.init(this.gradientCanvas),Promise.resolve();const n=++this.backgroundTempId,o=this.gradientRenderer,r=this.patternRenderer,l=(this.gradientCanvas,this.patternCanvas);this.gradientRenderer=this.patternRenderer=this.gradientCanvas=this.patternCanvas=void 0;const c=s.background.intensity&&s.background.intensity/100,d=!!c&&c<0;let h,p,u,g=null==i?void 0:i.firstElementChild;if(!i)if(i=document.createElement("div"),i.classList.add("chat-background-item"),e)if(c){i.classList.add("is-pattern");const t=this.appImManager.chatsContainer.getBoundingClientRect();h=this.patternRenderer=vr.getInstance({url:e,width:t.width,height:t.height,mask:d}),g=this.patternCanvas=h.createCanvas(),g.classList.add("chat-background-item-canvas","chat-background-item-pattern-canvas"),d&&i.classList.add("is-dark")}else s.background.slug&&i.classList.add("is-image");else s.background.color&&i.classList.add("is-color");const m=s.background.color;if(m){const{canvas:e,gradientRenderer:t}=en.create(m);u=this.gradientRenderer=t,p=this.gradientCanvas=e,p.classList.add("chat-background-item-canvas","chat-background-item-color-canvas"),a.a.settings.animationsEnabled&&u.scrollAnimate(!0)}if(h){(d?p:g).style.setProperty("--opacity-max",""+Math.abs(c))}const b=new Promise(s=>{const a=()=>{if(this.backgroundTempId!==n)return h&&h.cleanup(g),void(u&&u.cleanup());const e=this.backgroundEl.lastElementChild;if(e===i)return void s();const a=[p,g].filter(Boolean);a.length&&i.append(...a),this.backgroundEl.append(i),Object(is.a)(i,"is-visible",!0,t?0:200,e?()=>{r&&r.cleanup(l),o&&o.cleanup(),e.remove()}:null,2),s()};if(h){h.renderToCanvas(g).then(()=>{if(this.backgroundTempId!==n)return;let e;e=Promise.resolve(),e.then(a)})}else e?Object(ps.a)(i,e,a):a()});return this.setBackgroundPromise=Promise.race([Object(da.a)(500),b])}setType(e){this.type=e,"scheduled"===this.type&&(this.getMessagesStorage=()=>this.appMessagesManager.getScheduledMessagesStorage(this.peerId))}init(){this.topbar=new gr(this,ts,this.appMessagesManager,this.appPeersManager,this.appChatsManager,this.appNotificationsManager,this.appProfileManager,this.appUsersManager,this.appGroupCallsManager),this.bubbles=new ao(this,this.appMessagesManager,this.appStickersManager,this.appUsersManager,this.appInlineBotsManager,this.appPhotosManager,this.appPeersManager,this.appProfileManager,this.appDraftsManager,this.appMessagesIdsManager,this.appChatsManager,this.appReactionsManager,this.appWebPagesManager),this.input=new tr(this,this.appMessagesManager,this.appMessagesIdsManager,this.appDocsManager,this.appChatsManager,this.appPeersManager,this.appWebPagesManager,this.appImManager,this.appDraftsManager,this.serverTimeManager,this.appNotificationsManager,this.appEmojiManager,this.appUsersManager,this.appInlineBotsManager,this.appProfileManager),this.selection=new ri(this,this.bubbles,this.input,this.appMessagesManager),this.contextMenu=new fo(this.bubbles.bubblesContainer,this,this.appMessagesManager,this.appPeersManager,this.appPollsManager,this.appDocsManager,this.appMessagesIdsManager,this.appReactionsManager),"chat"===this.type?(this.topbar.constructUtils(),this.topbar.constructPeerHelpers()):"pinned"===this.type?this.topbar.constructPinnedHelpers():"discussion"===this.type&&(this.topbar.constructUtils(),this.topbar.constructDiscussionHelpers()),this.topbar.construct(),this.input.construct(),"chat"===this.type?(this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers()):"pinned"===this.type?(this.bubbles.constructPinnedHelpers(),this.input.constructPinnedHelpers()):"scheduled"===this.type?(this.bubbles.constructScheduledHelpers(),this.input.constructPeerHelpers()):"discussion"===this.type&&(this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers()),"scheduled"===this.type||he.a||this.bubbles.setReactionsHoverListeners(),this.container.classList.add("type-"+this.type),this.container.append(this.topbar.container,this.bubbles.bubblesContainer,this.input.chatInput),this.bubbles.listenerSetter.add(a.a)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{this.peerId===e&&this.setPeer(t)}),this.bubbles.listenerSetter.add(a.a)("dialog_drop",e=>{e.peerId===this.peerId&&this.appImManager.setPeer()})}beforeDestroy(){this.bubbles.cleanup()}cleanupBackground(){++this.backgroundTempId,this.patternRenderer&&(this.patternRenderer.cleanup(this.patternCanvas),this.patternRenderer=void 0),this.gradientRenderer&&(this.gradientRenderer.cleanup(),this.gradientRenderer=void 0)}destroy(){this.topbar.destroy(),this.bubbles.destroy(),this.input.destroy(),this.contextMenu&&this.contextMenu.destroy(),this.cleanupBackground(),delete this.topbar,delete this.bubbles,delete this.input,delete this.selection,delete this.contextMenu,this.container.remove()}cleanup(e=!0){this.input.cleanup(e),this.selection.cleanup()}setPeer(e,t,s){e?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=void 0;const i=this.peerId===e;if(i){if(this.setPeerPromise)return}else a.a.dispatchEvent("peer_changing",this),this.peerId=e||Me.c;if(!e)return ts.toggleSidebar(!1),this.cleanup(!0),this.topbar.setPeer(e),this.bubbles.setPeer(e),void a.a.dispatchEvent("peer_changed",e);if(!i){const t=ts.getTab(mr);t&&t.close(),this.noForwards=this.appPeersManager.noForwards(e),this.isRestricted=this.appPeersManager.isRestricted(e),this.container.classList.toggle("no-forwards",this.noForwards),ts.sharedMediaTab.setPeer(e,this.threadId),this.input.clearHelper(),this.selection.cleanup(),this.setAutoDownloadMedia()}this.peerChanged=i,void 0===s&&this.isStartButtonNeeded()&&(s=Me.a);const n=this.bubbles.setPeer(e,t,s);if(!n)return;const{promise:o}=n,r=this.setPeerPromise=o.finally(()=>{this.setPeerPromise===r&&(this.setPeerPromise=null)});return i||(ts.sharedMediaTab.setLoadMutex(this.setPeerPromise),ts.sharedMediaTab.loadSidebarMedia(!0)),n}setAutoDownloadMedia(){this.autoDownload=function(e){let t,s=0,i=0,n=0;const o=a.a.settings;return!o.autoDownloadNew.pFlags.disabled&&e&&(t=e.isUser()?e.isContact()?"contacts":"private":e.isBroadcast()?"channels":"groups",o.autoDownload.photo[t]&&(s=o.autoDownloadNew.photo_size_max),o.autoDownload.video[t]&&(i=o.autoDownloadNew.video_size_max),o.autoDownload.file[t]&&(n=o.autoDownloadNew.file_size_max)),{photo:s,video:i,file:n}}(this.peerId)}setMessageId(e){return this.setPeer(this.peerId,e)}finishPeerChange(e,t,s,i){if(this.peerChanged)return;let n=this.peerId;this.peerChanged=!0,this.cleanup(!1),this.topbar.setPeer(n),this.topbar.finishPeerChange(e,t,s),this.bubbles.finishPeerChange(),this.input.finishPeerChange(i),ts.sharedMediaTab.fillProfileElements(),this.log.setPrefix("CHAT-"+n+"-"+this.type),a.a.dispatchEvent("peer_changed",n),this.wasAlreadyUsed=!0}getMessagesStorage(){return this.appMessagesManager.getMessagesStorage(this.peerId)}getMessage(e){return this.appMessagesManager.getMessageFromStorage(this.getMessagesStorage(),e)}getMidsByMid(e){return this.appMessagesManager.getMidsByMessage(this.getMessage(e))}isAnyGroup(){return this.peerId===a.a.myId||this.peerId===Me.e||this.appPeersManager.isAnyGroup(this.peerId)}initSearch(e){if(this.peerId)if(b.b.isMobile)this.search?this.search.setQuery(e):this.search=new br(this.topbar,this,e);else{let t=ts.getTab(mr);t||(t=new mr(ts)),t.open(this.peerId,this.threadId,this.bubbles.onDatePick,e)}}canSend(e){return this.appMessagesManager.canSendToPeer(this.peerId,this.threadId,e)}isStartButtonNeeded(){return this.appPeersManager.isBot(this.peerId)&&!this.appMessagesManager.getDialogOnly(this.peerId)&&!this.appMessagesManager.getHistoryStorage(this.peerId).history.length}getMessageSendingParams(){return{threadId:this.threadId,replyToMsgId:this.input.replyToMsgId,scheduleDate:this.input.scheduleDate,sendSilent:this.input.sendSilent,sendAsPeerId:this.input.sendAsPeerId}}}class yr{constructor(e){this.appImManager=e,this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,he.a){if(e&&Object(c.a)(e),0!=this.mouseUpCounter++)return void this.hide();this.resetSelection(this.savedRange)}this.show()}}init(){this.container=document.createElement("div"),this.container.classList.add("markup-tooltip","z-depth-1","hide"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("markup-tooltip-wrapper");const e=document.createElement("div"),t=document.createElement("div");e.classList.add("markup-tooltip-tools"),t.classList.add("markup-tooltip-tools");["bold","italic","underline","strikethrough","monospace","spoiler","link"].forEach(t=>{const s=N(t,{noRipple:!0});e.append(this.buttons[t]=s),"link"!==t?s.addEventListener("mousedown",e=>{Object(c.a)(e),this.appImManager.chat.input.applyMarkdown(t),this.cancelClosening()}):Object(l.b)(s,e=>{Object(c.a)(e),this.showLinkEditor(),this.cancelClosening()})}),this.linkBackButton=N("left",{noRipple:!0}),this.linkInput=document.createElement("input"),Object(T.b)(this.linkInput,"MarkupTooltip.LinkPlaceholder",void 0,"placeholder"),this.linkInput.classList.add("input-clear"),this.linkInput.addEventListener("keydown",e=>{const t=!this.linkInput.value.length||!!X.b.matchUrl(this.linkInput.value);"Enter"===e.key&&(t?this.applyLink(e):(this.linkInput.classList.contains("error")&&(this.linkInput.classList.remove("error"),this.linkInput.offsetLeft),this.linkInput.classList.add("error")))}),this.linkInput.addEventListener("input",e=>{const t=this.isLinkValid();this.linkInput.classList.toggle("is-valid",t),this.linkInput.classList.remove("error")}),this.linkBackButton.addEventListener("mousedown",e=>{Object(c.a)(e),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()}),this.linkApplyButton=N("check markup-tooltip-link-apply",{noRipple:!0}),this.linkApplyButton.addEventListener("mousedown",e=>{this.applyLink(e)});const s=document.createElement("div");s.classList.add("markup-tooltip-link-apply-container");const i=document.createElement("span"),n=document.createElement("span"),a=document.createElement("span");i.classList.add("markup-tooltip-delimiter"),n.classList.add("markup-tooltip-delimiter"),a.classList.add("markup-tooltip-delimiter"),e.insertBefore(i,this.buttons.link),s.append(a,this.linkApplyButton),t.append(this.linkBackButton,n,this.linkInput,s),this.wrapper.append(e,t),this.container.append(this.wrapper),document.body.append(this.container),window.addEventListener("resize",()=>{this.hide()})}showLinkEditor(){this.container&&this.container.classList.contains("is-visible")||this.show();const e=this.buttons.link;this.container.classList.add("is-link");const t=document.getSelection();if(this.savedRange=t.getRangeAt(0),e.classList.contains("active")){const e=this.savedRange.startContainer.parentElement;this.linkInput.value=e.href}else this.linkInput.value="";this.setTooltipPosition(!0),setTimeout(()=>{this.linkInput.focus()},200),this.linkInput.classList.toggle("is-valid",this.isLinkValid())}applyLink(e){Object(c.a)(e),this.resetSelection();let t=this.linkInput.value;t&&!X.b.matchUrlProtocol(t)&&(t="https://"+t),this.appImManager.chat.input.applyMarkdown("link",t),setTimeout(()=>{this.hide()},0)}isLinkValid(){return!this.linkInput.value.length||!!X.b.matchUrl(this.linkInput.value)}resetSelection(e=this.savedRange){const t=window.getSelection();t.removeAllRanges(),t.addRange(e),this.appImManager.chat.input.messageInput.focus()}hide(){this.init||(this.container.classList.remove("is-visible"),document.removeEventListener("mouseup",this.onMouseUpSingle),this.waitingForMouseUp=!1,F.a.removeByType("markup"),this.hideTimeout&&clearTimeout(this.hideTimeout),this.hideTimeout=window.setTimeout(()=>{this.hideTimeout=void 0,this.container.classList.add("hide"),this.container.classList.remove("is-link")},200))}getActiveMarkupButton(){const e=function(){const e=[],t=window.getSelection();for(let s=0;s<t.rangeCount;++s){const i=t.getRangeAt(s);let{startContainer:n,endContainer:a}=i;for(3!==a.nodeType&&(a=a.firstChild);n&&n!==a;)e.push(3===n.nodeType?n:n.firstChild),n=n.nextSibling;e[e.length-1]!==a&&e.push(a)}return e.filter(e=>!!e)}(),t=[...new Set(e.map(e=>e.parentNode))],s=new Set;return t.forEach(e=>{for(const t in Uo.b){const i=Uo.b[t];e.closest(i.match+", [contenteditable]")!==this.appImManager.chat.input.messageInput&&s.add(this.buttons[t])}}),[...s]}setActiveMarkupButton(){const e=this.getActiveMarkupButton();for(const t in this.buttons){const s=this.buttons[t];s.classList.toggle("active",e.includes(s))}}setTooltipPosition(e=!1){const t=document.getSelection().getRangeAt(0),s=document.body.getBoundingClientRect(),i=t.getBoundingClientRect(),n=this.appImManager.chat.input.rowsWrapper.getBoundingClientRect();this.container.style.maxWidth=n.width+"px";const a=Qa(void 0,this.appImManager.chat.input.messageInput,!1,i).rect.top+-1*s.top,o=(this.container.classList.contains("is-link")?this.wrapper.lastElementChild:this.wrapper.firstElementChild).getBoundingClientRect(),r=a-o.height-8,l=n.left,c=n.left+n.width-Math.min(n.width,o.width);let d;if(e){const e=this.container.getBoundingClientRect();d=Object(ke.a)(e.left,l,c)}else{const e=i.left+(i.width-o.width)/2;d=Object(ke.a)(e,l,c)}this.container.style.transform=`translate3d(${d}px, ${r}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),lo())return void this.hide();if(void 0!==this.hideTimeout&&clearTimeout(this.hideTimeout),this.container.classList.contains("is-visible"))return;this.setActiveMarkupButton(),this.container.classList.remove("is-link");const e=this.container.classList.contains("hide");e&&(this.container.classList.remove("hide"),this.container.classList.add("no-transition")),this.setTooltipPosition(),e&&(this.container.offsetLeft,this.container.classList.remove("no-transition")),this.container.classList.add("is-visible"),ae.e||F.a.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){he.a&&!ae.b&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",e=>{Object(c.a)(e),this.mouseUpCounter=1,this.waitingForMouseUp=!1,this.setMouseUpEvent()},{once:!0}))}handleSelection(){this.addedListener||(this.addedListener=!0,document.addEventListener("selectionchange",e=>{if(document.activeElement===this.linkInput)return;const t=this.appImManager.chat.input.messageInput;if(document.activeElement!==t)return void this.hide();const s=document.getSelection();if(lo(s))this.hide();else if(he.a)if(ae.b)this.show(),this.setTooltipPosition();else{if(2===this.mouseUpCounter)return void(this.mouseUpCounter=0);this.savedRange=s.getRangeAt(0),this.setMouseUpEvent()}else this.container&&this.container.classList.contains("is-visible")?this.setTooltipPosition():t.matches(":active")?this.setMouseUpEvent():this.show()}))}}function wr(e,t,s,i,n,a,o){return[e,",",t," ",s," ",i,",",n," ",a,",",o].join("")}function Sr(e,t,s,i,n,a,o,r){const l=[];return l.push("M"+(e+s/2)+","+t),l.push("H"+(e+s-a)),a>0&&l.push("A"+wr(a,a,0,0,1,e+s,t+a)),l.push("V"+(t+i-o)),o>0&&l.push("A"+wr(o,o,0,0,1,e+s-o,t+i)),l.push("H"+(e+r)),r>0&&l.push("A"+wr(r,r,0,0,1,e+0,t+i-r)),l.push("V"+(t+n)),n>0&&l.push("A"+wr(n,n,0,0,1,e+n,t+0)),l.push("Z"),l.join(" ")}le.a.generatePathData=Sr;class Cr{constructor(e,t){let s;this.options=t,this.onDragOver=e=>{this.container.classList.add("is-dragover")},this.onDragLeave=e=>{this.container.classList.remove("is-dragover")},this.onDrop=e=>{this.options.onDrop(e)},this.container=document.createElement("div"),this.container.classList.add("drop","z-depth-1"),this.outlineWrapper=document.createElement("div"),this.outlineWrapper.classList.add("drop-outline-wrapper"),this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.classList.add("drop-outline"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.classList.add("drop-outline-path"),t.icon&&(s=document.createElement("div"),s.classList.add("drop-icon","tgico-"+t.icon));const i=document.createElement("div");let n;i.classList.add("drop-header"),i.append(Object(T.d)(t.header,t.headerArgs)),t.subtitle&&(n=document.createElement("div"),n.classList.add("drop-subtitle"),n.append(Object(T.d)(t.subtitle))),this.svg.append(this.path),this.outlineWrapper.append(this.svg),this.container.append(...[this.outlineWrapper,s,i,n].filter(Boolean)),e.append(this.container),this.container.addEventListener("dragover",this.onDragOver),this.container.addEventListener("dragleave",this.onDragLeave),this.container.addEventListener("drop",this.onDrop)}destroy(){delete this.options,this.container.remove(),this.container.removeEventListener("dragover",this.onDragOver),this.container.removeEventListener("dragleave",this.onDragLeave),this.container.removeEventListener("drop",this.onDrop)}setPath(){const e=this.outlineWrapper.getBoundingClientRect();this.svg.setAttributeNS(null,"preserveAspectRatio","none"),this.svg.setAttributeNS(null,"viewBox",`0 0 ${e.width} ${e.height}`),this.svg.setAttributeNS(null,"width",""+e.width),this.svg.setAttributeNS(null,"height",""+e.height);const t=Sr(5,5,e.width-10,e.height-10,10,10,10,10);this.path.setAttributeNS(null,"d",t)}}function Lr(e){e.forEach(e=>e.classList.add("no-transition")),Object(Le.a)().then(()=>{e.forEach(e=>e.classList.remove("no-transition"))})}var Ir=s(50),Mr=s(48),Er=s(138),Pr=s(128);class kr{constructor(e){this.maxRadius=10,this.minRadius=0,this.N=e,this.radius=new Array(e+1),this.radiusNext=new Array(e+1),this.progress=new Array(e+1),this.speed=new Array(e+1);for(let t=0;t<=e;t++)this.generateBlob(this.radius,t),this.generateBlob(this.radiusNext,t),this.progress[t]=0}generateBlob(e,t){const{maxRadius:s,minRadius:i,speed:n}=this,a=s-i;e[t]=i+Math.random()*a,n[t]=.017+.003*Math.random()}generateNextBlob(){const{radius:e,radiusNext:t,progress:s,N:i}=this;for(let n=0;n<i;n++)this.generateBlob(e,n),this.generateBlob(t,n),s[n]=0}update(e,t){const{N:s,progress:i,speed:n,radius:a,radiusNext:o}=this;for(let r=0;r<=s;r++)i[r]+=.8*n[r]+e*n[r]*8.2*t,i[r]>=1&&(i[r]=0,a[r]=o[r],this.generateBlob(o,r))}draw(e,t,s,i,n,a,o,r){if(n.getContext){const l=n.getContext("2d");l.beginPath(),l.moveTo(s,i),l.lineTo(e,i);const{radius:c,radiusNext:d,N:h}=this;for(let n=0;n<=h;n++)if(0===n){const s=this.progress[n],i=(t-(c[n]*(1-s)+d[n]*s))*r+o*(1-r);l.lineTo(e,i)}else{const a=this.progress[n-1],p=c[n-1]*(1-a)+d[n-1]*a,u=this.progress[n],g=(s-e)/h*(n-1),m=(s-e)/h*n,b=g+(m-g)/2,v=(t-p)*r+o*(1-r),f=(t-(c[n]*(1-u)+d[n]*u))*r+o*(1-r);l.bezierCurveTo(b,v,b,f,m,f),n===h&&l.lineTo(s,i)}a(l),l.fill(),l.closePath()}}}class Tr{constructor(e){this.stateId=e,this.createGradient(e)}createGradient(e){this.shader=(t,s,i,n,a)=>{t.fillStyle=Tr.getGradientFromType(t,e,s,i,n,a)}}static getGradientFromType(e,t,s,i,n,a){const o=e.createLinearGradient(s,i,n,a);return t===Pr.a.MUTED_BY_ADMIN?(o.addColorStop(0,"#F05459"),o.addColorStop(.4,"#766EE9"),o.addColorStop(1,"#57A4FE")):t===Pr.a.UNMUTED?(o.addColorStop(0,"#52CE5D"),o.addColorStop(1,"#00B1C0")):t===Pr.a.MUTED?(o.addColorStop(0,"#0976E3"),o.addColorStop(1,"#2BCEFF")):t===Pr.a.CONNECTING&&(o.addColorStop(0,"#8599aa"),o.addColorStop(1,"#8599aa")),o}update(e,t,s,i){}}class xr{constructor(){this.handleDevicePixelRatioChanged=e=>{this.setSize(),this.forceUpdate()},this.handleResize=()=>{this.resizeHandler&&(clearTimeout(this.resizeHandler),this.resizeHandler=null),this.resizing=!0,this.resizeCanvas(),this.resizeHandler=window.setTimeout(()=>{this.resizing=!1,this.invokeDraw()},250)},this.handleFocus=()=>{this.focused=!0,this.invokeDraw()},this.handleBlur=()=>{this.focused=!1},this.invokeDraw=()=>{this.raf||this.draw()},this.draw=(e=!1)=>{if(this.raf=null,!this.mounted)return;const{lbd:t,lbd1:s,lbd2:i,scale:n,left:a,top:o,right:r,bottom:l,currentState:c,previousState:d,focused:h,resizing:p,canvas:u}=this;if(!h&&!p&&this.progressToState>=1)return;let g=Date.now()-this.lastUpdateTime;g>20&&(g=17),this.animateToAmplitude!==this.amplitude&&(this.amplitude+=this.animateAmplitudeDiff*g,this.animateAmplitudeDiff>0?this.amplitude>this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude):this.amplitude<this.animateToAmplitude&&(this.amplitude=this.animateToAmplitude)),this.animateToAmplitude!==this.amplitude2&&(this.amplitude2+=this.animateAmplitudeDiff2*g,this.animateAmplitudeDiff2>0?this.amplitude2>this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude):this.amplitude2<this.animateToAmplitude&&(this.amplitude2=this.animateToAmplitude)),d&&(this.progressToState+=g/250,this.progressToState>1&&(this.progressToState=1,this.previousState=null));const{amplitude:m,amplitude2:b,progressToState:v}=this,f=6*b*n,y=6*b*n;u.getContext("2d").clearRect(0,0,u.width,u.height),t.minRadius=0,t.maxRadius=(2+2*m)*n,s.minRadius=0,s.maxRadius=(3+9*m)*n,i.minRadius=0,i.maxRadius=(3+9*m)*n,t.update(m,.3),s.update(m,.7),i.update(m,.7);for(let e=0;e<2;e++){if(0===e&&!d)continue;let n=1,h=null;0===e?(n=1-v,h=d):(n=d?v:1,c.update(l-o,r-a,g,m),h=c);const p=e=>{e.globalAlpha=.3*n,h.shader(e,a,o,r,l)},b=t=>{t.globalAlpha=0===e?1:n,h.shader(t,a,o,r,l)};s.draw(a,o-f,r,l,u,p,o,1),i.draw(a,o-y,r,l,u,p,o,1),t.draw(a,o,r,l,u,b,o,1)}e||(this.raf=requestAnimationFrame(()=>this.draw()))},this.setCurrentState=(e,t)=>{const{currentState:s,states:i}=this;(null==s?void 0:s.stateId)!==e&&(this.previousState=t?s:null,this.currentState=i.get(e),this.progressToState=this.previousState?0:1)},this.focused=!0,this.resizing=!1,this.lastUpdateTime=Date.now(),this.amplitude=0,this.amplitude2=0,this.states=new Map([[Pr.a.UNMUTED,new Tr(Pr.a.UNMUTED)],[Pr.a.MUTED,new Tr(Pr.a.MUTED)],[Pr.a.MUTED_BY_ADMIN,new Tr(Pr.a.MUTED_BY_ADMIN)],[Pr.a.CONNECTING,new Tr(Pr.a.CONNECTING)]]),this.previousState=null,this.currentState=this.states.get(Pr.a.CONNECTING),this.progressToState=1}componentDidMount(){this.mounted||(this.mounted=!0,window.addEventListener("resize",this.handleResize),this.media=window.matchMedia("screen and (min-resolution: 2dppx)"),this.media.addEventListener("change",this.handleDevicePixelRatioChanged),this.setSize(),this.forceUpdate(),this.lbd=new kr(3),this.lbd1=new kr(7),this.lbd2=new kr(8),this.setAmplitude(this.amplitude),this.draw())}componentWillUnmount(){this.mounted=!1,window.removeEventListener("resize",this.handleResize),this.media.addEventListener("change",this.handleDevicePixelRatioChanged);const{canvas:e}=this;e.getContext("2d").clearRect(0,0,e.width,e.height)}setSize(){this.scale=window.devicePixelRatio,this.top=20*this.scale,this.right=(this.mounted?this.container.offsetWidth:1261)*this.scale,this.bottom=(this.mounted?this.container.offsetHeight:68)*this.scale,this.left=0*this.scale,this.setCanvasSize()}setCanvasSize(){this.canvas.width=this.right,this.canvas.height=this.bottom}resizeCanvas(){this.scale=window.devicePixelRatio,this.right=this.container.offsetWidth*this.scale,this.forceUpdate(),this.invokeDraw()}setAmplitude(e){const{amplitude:t}=this;this.animateToAmplitude=e,this.animateAmplitudeDiff=(e-t)/250,this.animateAmplitudeDiff2=(e-t)/120}forceUpdate(){this.setCanvasSize()}render(e){const t=this.container=document.createElement("div");t.classList.add(e);const s=this.canvas=document.createElement("canvas");return s.classList.add(e+"-canvas"),t.append(s),t}}var Ar=new class{constructor(){this.cache={},a.a.addEventListener("theme_change",()=>{this.computedStyle=void 0;const e=this.cache;this.cache={};for(let t in e)this.getProperty(t)})}getProperty(e){let t=this.cache[e];return t||(this.computedStyle||(this.computedStyle=window.getComputedStyle(document.documentElement)),t=this.computedStyle.getPropertyValue("--"+e).trim(),this.cache[e]=t)}};class Or{constructor(e,t){this.item=e,Object(w.a)(this,t)}play(e){return this.item.playPart(this,e)}}class jr{constructor(e,t){this.icon=e,this.autoplay=!1,Object(w.a)(this,t),this.parts=this.parts.map(e=>this.createPart(e))}load(){var e;let t=this.loadPromise;if(t)return t;const{container:s,canvas:i,width:n,height:a}=this.icon;return t=oe.a.loadAnimationAsAsset({container:s,canvas:i,width:n,height:a,group:"none",loop:!1,autoplay:null!==(e=this.autoplay)&&void 0!==e&&e,initFrame:this.initFrame,skipFirstFrameRendering:void 0===this.initFrame,color:this.color,inverseColor:this.inverseColor},this.name).then(e=>oe.a.waitForFirstFrame(e)).then(e=>{this.player=e,this.onLoadForColor&&(this.onLoadForColor(),this.onLoadForColor=void 0),this.onLoadForPart&&(this.onLoadForPart(),this.onLoadForPart=void 0)}),this.loadPromise=t,this.icon.loadPromises.set(this.name,t),t}createPart(e){return new Or(this,e)}getPart(e){return e instanceof Or?e:"string"==typeof e?this.parts.find(t=>t.name===e):this.parts[e]}playPart(e,t){return this.icon.playPart(this,e,t)}}class _r{constructor(e){Object(w.a)(this,e),this.container||(this.container=document.createElement("div")),this.container.classList.add("rlottie-icon");const{width:t,height:s}=this;this.container.style.width=t+"px",this.container.style.height=s+"px";const i=this.canvas=document.createElement("canvas");i.classList.add("rlottie"),i.width=t,i.height=s,this.items=new Map,this.loadPromises=new Map}get loadPromise(){return Promise.all([...this.loadPromises.values()]).then(Se.a)}getItem(e){return e||1!==this.items.size?this.items.get(e):this.items.values().next().value}add(e){const t=new jr(this,e);return this.items.set(e.name,t),t}playPart(e,t,s){if(!e.player)return void(e.onLoadForPart=()=>{this.playPart(e,t,s)});const i=e.getPart(t);e.player.playPart({from:a.a.settings.animationsEnabled&&!this.skipAnimation?i.startFrame:i.endFrame,to:i.endFrame,callback:s})}static generateEqualParts(e,t){return new Array(e).fill(0).map((e,s)=>{const i=s*t;return{startFrame:i,endFrame:i+t-1}})}}class Fr extends _r{constructor(e){super({width:e.width,height:e.height}),Object(w.a)(this,e)}load(e,t){if(this.loaded)return this.loadPromise;this.loaded=!0,this.partState=e,this.colorState=t;const s=this.getPart(e),i=void 0!==t&&this.getColor&&this.getColor(t),n=s.item;n.initFrame=s.endFrame,n.color=i;const a=[...this.items.values()].map(e=>e.load());return Promise.all(a).then(Se.a)}setState(e,t,s){this.loaded||this.load(e,t);let i=!1,n=!1;return void 0!==e?i=this.setPartState(e,t,s):void 0!==t&&(n=this.setColorState(t)),i||n}setPartState(e,t,s){const{partState:i}=this;if(i===e)return void 0!==t&&this.setColorState(t);void 0!==t&&this.setColorState(t,!1),this.partState=e;return this.getPart(e,i).play(s),!0}setColorState(e,t=!0){const{colorState:s}=this;if(s===e||!this.getColor)return!1;this.colorState=e;const i=this.getItem(),n=this.getColor(e,s),a=()=>{i.player.setColor(n,t)};return i.player?a():i.onLoadForColor=a,!0}destroy(){this.items.forEach(e=>{e.loadPromise.then(()=>{e.player.remove()})})}}class Dr extends Fr{constructor(){super({width:36,height:36,getPart:(e,t)=>{const s=el;let i;switch(e){case s.HAND:i=t===s.MUTED?"muted-to-hand":"unmuted-to-hand";break;case s.MUTED:i=t===s.HAND?"hand-to-muted":"mute";break;case s.UNMUTED:i="unmute"}return this.getItem().getPart(i)}});this.container.classList.add("group-call-microphone-icon-container");this.add({name:"voip_filled",parts:[{startFrame:0,endFrame:35,name:"hand-to-muted"},{startFrame:36,endFrame:68,name:"unmute"},{startFrame:69,endFrame:98,name:"mute"},{startFrame:99,endFrame:135,name:"muted-to-hand"},{startFrame:136,endFrame:172,name:"unmuted-to-hand"},{startFrame:173,endFrame:201,name:"scheduled-crossing"},{startFrame:202,endFrame:236,name:"scheduled-to-muted"},{startFrame:237,endFrame:273,name:"scheduled-to-hand"},{startFrame:274,endFrame:310,name:"scheduled-crossed-to-hand"},{startFrame:311,endFrame:343,name:"scheduled-uncrossing"},{startFrame:344,endFrame:375,name:"scheduled-to-muted"},{startFrame:376,endFrame:403,name:"play-to-muted"}]})}}var Rr=s(126);class Br extends Fr{constructor(e){super({width:32,height:32,getPart:(e,t)=>{const s=Zr;let i;switch(e){case s.HAND:i=3;break;case s.MUTED:i=t===s.HAND?0:2;break;case s.UNMUTED:i=1}return this.getItem().getPart(i)},getColor:e?(e,t)=>function(e){const t=Zr;let s,i;switch(e){case t.HAND:i="blue";break;case t.MUTED:case t.MUTED_FOR_ME:case t.MUTED_BY_ADMIN:i=e===t.MUTED?"secondary":"red";break;case t.UNMUTED:i="green"}const n=Ar.getProperty("gc-"+i+"-text-color");return s=Yi(n),s}(e):void 0}),this.colored=e;this.container.classList.add("group-call-participant-muted-icon-container");const t=_r.generateEqualParts(4,21);this.add({name:"voice_outlined2",parts:t})}setState(e){return super.setState(function(e){const t=Zr;switch(e){case t.MUTED_BY_ADMIN:case t.MUTED_FOR_ME:return t.MUTED;default:return e}}(e),e)}}class Nr{constructor(e){this.withIcons=e,this.container=document.createElement("div"),this.container.classList.add("group-call-participant-status-container")}setState(e,t){const s=Zr,i=this.withIcons.filter(e=>!!t[e]).map(e=>{const t="tgico-"+("presentation"===e?"listscreenshare":"videocamera_filled"),s=document.createElement("i");return s.classList.add("group-call-participant-status-icon","group-call-participant-status-icon-"+e,t),s});let n,a;if(e===s.MUTED_FOR_ME)n=Object(T.d)("VoiceChat.Status.MutedForYou"),a="is-muted";else if(e===s.UNMUTED)n=Object(T.d)("VoiceChat.Status.Speaking"),a="is-speaking";else if(e===s.HAND)n=Object(T.d)("VoiceChat.Status.WantsSpeak"),a="is-waiting";else{if(t.about&&!i.length)return void Object(m.a)(this.container,X.b.wrapEmojiText(t.about));n=Object(T.d)("VoiceChat.Status.Listening"),a="is-listening"}const o=document.createElement("span");o.classList.add("group-call-participant-status",a),o.append(...i,n),Object(k.a)(this.container,o)}}class Ur extends Hs{constructor(e){super({getIndex:e=>e.participant.date,onDelete:e=>{e.dom.listEl.remove(),this.onElementDestroy(e)},onUpdate:e=>{const{participant:t}=e,s=al(t);e.mutedIcon.setState(s),e.status.setState(s,t)},onSort:(e,t)=>{Ns(e.dom.listEl,this.list,t)},onElementCreate:t=>{const{dom:s}=_c.addDialogNew({dialog:t.id,container:!1,drawStatus:!1,avatarSize:this.avatarSize,autonomous:this.autonomous,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});s.listEl.classList.add("group-call-participant");const i=e.participants.get(t.id),n=al(i),a=new Br(!0),o=new Nr(["presentation","video"]);return a.setState(n),o.setState(n,i),Object(k.a)(s.lastMessageSpan,o.container),s.listEl.append(a.container),t.dom=s,t.participant=i,t.mutedIcon=a,t.status=o,t},updateElementWith:Le.b}),this.instance=e,this.avatarSize=54,this.rippleEnabled=!0,this.autonomous=!0,this.createChatListOptions={dialogSize:72},this.list=_c.createChatList(this.createChatListOptions)}destroy(){this.elements.forEach(e=>{this.onElementDestroy(e)})}onElementDestroy(e){e.mutedIcon.destroy()}}class Hr extends D.a{constructor(){super(!1),this.hideControls=(e=!1)=>{if(e)return void(this.hideControlsTimeout||(this.hideControlsTimeout=window.setTimeout(this.hideControls,3e3)));clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=0;const t=this.element.classList.contains("show-controls");if(!1!==this.controlsLocked){if(this.canHideControls&&!this.canHideControls()||!t||this.controlsLocked)return}else if(!t)return;this.dispatchEvent("toggleControls",!1),this.element.classList.remove("show-controls")},this.showControls=(e=!0)=>{this.hideControlsTimeout?(clearTimeout(this.hideControlsTimeout),this.hideControlsTimeout=0):this.element.classList.contains("show-controls")||!1===this.controlsLocked||(this.dispatchEvent("toggleControls",!0),this.element.classList.add("show-controls")),e&&!this.controlsLocked&&(this.hideControlsTimeout=window.setTimeout(this.hideControls,3e3))},this.toggleControls=e=>{const t=this.element.classList.contains("show-controls");if(void 0===e)t?this.hideControls():this.showControls();else{if(e===t)return;!1===e?this.hideControls():this.showControls()}},this.hideControlsTimeout=0}setup(e){Object(w.a)(this,e);const{listenerSetter:t,element:s}=this;he.a?t.add(s)("click",e=>{this.ignoreClickClassName&&Object(Ce.a)(e.target,this.ignoreClickClassName)||this.toggleControls()}):(t.add(s)("mousemove",()=>{this.showControls()}),t.add(s)("mouseenter",()=>{this.showControls(!1)}),t.add(s)("mouseleave",e=>{e.relatedTarget&&this.showOnLeaveToClassName&&Object(Ce.a)(e.relatedTarget,this.showOnLeaveToClassName)?this.showControls(!1):this.hideControls()}))}lockControls(e){this.controlsLocked=e,this.element.classList.toggle("disable-hover",!1===e),this.toggleControls(e)}}function zr(e){const t=document.createElement("canvas");t.classList.add("call-video-blur");t.width=16,t.height=16;const s=t.getContext("2d");s.filter="blur(2px)";const i=()=>{s.drawImage(e,0,0,e.videoWidth,e.videoHeight,0,0,t.width,t.height)};return Object(Pe.a)(()=>(i(),t.isConnected)),i(),t}class Vr{constructor(e,t,s){this.appPeersManager=e,this.instance=t,this.source=s,this.container=document.createElement("div"),this.container.classList.add("group-call-participant-video-container"),this.info=document.createElement("div"),this.info.classList.add("group-call-participant-video-info"),this.left=document.createElement("div"),this.left.classList.add("group-call-participant-video-info-left"),this.right=document.createElement("div"),this.right.classList.add("group-call-participant-video-info-right"),this.info.append(this.left,this.right),this.container.append(this.info)}setPinned(e){if(!e)return void(this.header&&(this.header.remove(),this.header=void 0));if(this.header)return;this.header=document.createElement("div"),this.header.classList.add("group-call-participant-video-header");const t=document.createElement("i");t.classList.add("group-call-pin-icon","tgico-pin"),this.header.append(t),this.container.append(this.header)}setParticipant(e,t,s){let i;e.pFlags.self?(i=Object(T.d)("VoiceChat.Status.You"),i.classList.add("peer-title")):(this.peerTitle=new wt.a({peerId:this.appPeersManager.getPeerId(e.peer)}),i=this.peerTitle.element),this.groupCallParticipantMutedIcon=new Br(!1),this.groupCallParticipantStatus=new Nr([t]),this.left.append(i,this.groupCallParticipantStatus.container),this.right.append(this.groupCallParticipantMutedIcon.container),s.classList.add("group-call-participant-video","call-video"),s.paused&&s.play();const n=zr(s);n.classList.add("group-call-participant-video-blur"),this.container.prepend(n,s),this.updateParticipant(e)}updateParticipant(e){const t=al(e);this.groupCallParticipantMutedIcon.setState(t),this.groupCallParticipantStatus.setState(t,e)}destroy(){this.groupCallParticipantMutedIcon.destroy()}}class Kr extends Hr{constructor(e){super(),Object(w.a)(this,e);const t=this.container=document.createElement("div");this.container.classList.add("group-call-participants-video-container"),e.appendTo.append(t),this.participantsElements=new Map,this.containers=new Map;const{listenerSetter:s}=this;s.add(a.a)("group_call_participant",({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)}),s.add(this.instance)("pinned",e=>{this.participantsElements.forEach(t=>{t.forEach(t=>{this.setElementDisplay(t,e)})})}),Object(l.b)(this.container,e=>{const t=Object(Ce.a)(e.target,"group-call-participant-video-container");if(!t)return;const s=this.containers.get(t);this.instance.pinnedSource!==s.source?this.instance.pinSource(s.source):this.instance.unpinAll()},{listenerSetter:s}),this.setInstance(this.instance),this.setup({element:t,listenerSetter:s,showOnLeaveToClassName:"group-call-buttons"})}shouldDisplayElement(e,t){return this.displayPinned?!t||e.source===t:t&&e.source!==t}setElementDisplay(e,t){const s=this.shouldDisplayElement(e,t);e.container.classList.toggle("video-hidden",!s);const i=e.source===t;e.setPinned(i)}updateParticipant(e){const t=this.appPeersManager.getPeerId(e.peer),s=["video","presentation"],i=s.some(t=>!!e[t]);let n=this.participantsElements.get(t);(i||n)&&(n||this.participantsElements.set(t,n=new Map),s.forEach(s=>{let i=n.get(s);const a=e[s];if(!!a!=!!i){if(a){const t=this.instance.getVideoElementFromParticipantByType(e,s);if(!t)return;const{video:a,source:o}=t;i=new Vr(this.appPeersManager,this.instance,o),this.containers.set(i.container,i),this.setElementDisplay(i,this.instance.pinnedSource),n.set(s,i),i.setParticipant(e,s,a),this.container.prepend(i.container)}else n.delete(s),i.container.remove(),n.size||(this.participantsElements.delete(t),this.containers.delete(i.container),i.destroy());this._onLengthChange()}else i&&i.updateParticipant(e)}))}_onLengthChange(){const e=this.container.childElementCount;this.container.dataset.length=""+e,this.container.dataset.layout=e<=2?"1":3===e?"3":"4",this.onLengthChange&&this.onLengthChange(e)}setInstance(e){e.participants.forEach(e=>{this.updateParticipant(e)})}destroy(){this.containers.forEach(e=>{e.destroy()})}}class Gr{constructor(e){this.onOpenProfileClick=()=>{const e=ht.b.getPopups(rl)[0];e&&e.hide(),a.a.dispatchEvent("history_focus",{peerId:this.targetPeerId})},this.toggleParticipantMuted=e=>{this.appGroupCallsManager.editParticipant(this.instance.id,this.participant,{muted:e})},this.buttons=[{icon:"gc_microphoneoff",text:"VoiceChat.MutePeer",verify:()=>this.canManageCall&&this.participant.pFlags.can_self_unmute,onClick:()=>this.toggleParticipantMuted(!0)},{icon:"gc_microphone",text:"VoiceChat.UnmutePeer",verify:()=>this.canManageCall&&!this.participant.pFlags.can_self_unmute,onClick:()=>this.toggleParticipantMuted(!1)},{icon:"gc_microphoneoff",text:"VoiceChat.MuteForMe",verify:()=>!this.canManageCall&&!this.participant.pFlags.muted_by_you,onClick:()=>this.toggleParticipantMuted(!0)},{icon:"gc_microphone",text:"VoiceChat.UnmuteForMe",verify:()=>!this.canManageCall&&this.participant.pFlags.muted_by_you,onClick:()=>this.toggleParticipantMuted(!1)},{icon:"newprivate",text:"VoiceChat.OpenProfile",verify:()=>!0,onClick:this.onOpenProfileClick},{icon:"deleteuser danger",text:"VoiceChat.RemovePeer",verify:()=>this.appChatsManager.hasRights(this.chatId,"ban_users"),onClick:()=>{Mn({peerId:this.targetPeerId,title:new wt.a({peerId:this.targetPeerId}).element,descriptionLangKey:this.appChatsManager.isBroadcast(this.chatId)?"VoiceChat.RemovePeer.Confirm.Channel":"VoiceChat.RemovePeer.Confirm",descriptionLangArgs:[new wt.a({peerId:this.targetPeerId}).element],button:{langKey:"VoiceChat.RemovePeer.Confirm.OK",isDanger:!0}}).then(()=>{this.appChatsManager.kickFromChat(this.chatId,this.targetPeerId)},Se.a)}}];const{listenerSetter:t}=e;this.appChatsManager=e.appChatsManager,this.appPeersManager=e.appPeersManager,this.appGroupCallsManager=e.appGroupCallsManager,this.instance=e.instance,this.chatId=this.instance.chatId,this.element=$s(this.buttons,t),this.element.classList.add("group-call-participant-menu","night"),Object(ee.a)(e.onContextElement,e=>{const t=Object(Ce.a)(e.target,"group-call-participant");if(!t)return;this.element.parentElement!==s&&s.append(this.element);const i=this.targetPeerId=t.dataset.peerId.toPeerId();this.participant=this.instance.getParticipantByPeerId(i),this.participant.pFlags.self||(this.canManageCall=this.appChatsManager.hasRights(this.chatId,"manage_call"),this.buttons.forEach(e=>{e.element.classList.toggle("hide",!e.verify(i))}),Object(c.a)(e),Object(ee.e)(e.touches?e.touches[0]:e,this.element,"right"),Object(ee.d)(this.element))},t),t.add(a.a)("group_call_participant",({groupCallId:e,participant:t})=>{if(this.instance.id===e){const e=this.appPeersManager.getPeerId(t.peer);this.targetPeerId===e&&Object(ee.c)()}});let s=document.body;Object(Rr.a)(document.body,()=>{const e=Object(Rr.d)();s=e?ht.b.getPopups(rl)[0].getContainer():document.body,e||Object(ee.c)()},t)}}class Wr{constructor(e){Object(w.a)(this,e);const t=new P.b(void 0);t.container.classList.add("group-call-participants-scrollable");const s=this.container=document.createElement("div");s.classList.add("group-call-participants");const i=this.sortedList=new Ur(this.instance),{instance:n,listenerSetter:o}=this;this.contextMenu=new Gr(Object.assign(Object.assign({},e),{onContextElement:i.list,listenerSetter:o,instance:n})),this.groupCallParticipantsVideo=new Kr(Object.assign(Object.assign({},e),{appendTo:t.container,displayPinned:!1})),t.append(i.list),s.append(t.container),e.appendTo.append(s),o.add(a.a)("group_call_participant",({groupCallId:e,participant:t})=>{this.instance.id===e&&this.updateParticipant(t)});new vt({scrollable:t,getPromise:()=>this.appGroupCallsManager.getGroupCallParticipants(this.instance.id).then(({participants:e,isEnd:t})=>(e.forEach(e=>{this.updateParticipant(e)}),t))});this.setInstance(n)}updateParticipant(e){const t=this.appPeersManager.getPeerId(e.peer),s=this.sortedList.has(t);e.pFlags.left?s&&this.sortedList.delete(t):s?this.sortedList.update(t):this.sortedList.add(t)}setInstance(e){e.participants.forEach(e=>{this.updateParticipant(e)})}destroy(){this.sortedList.destroy(),this.groupCallParticipantsVideo.destroy()}}class qr{constructor(e){this.appendTo=e,this.descriptionIntl=new T.c.IntlElement({key:"VoiceChat.Status.Connecting"}),this.descriptionIntl.element.classList.add("group-call-description")}detach(){this.descriptionIntl.element.remove()}update(e){const{state:t}=e;let s,i;t===Pr.a.CONNECTING?s="VoiceChat.Status.Connecting":(s="VoiceChat.Status.Members",i=[e.groupCall.participants_count]);const{descriptionIntl:n}=this;n.compareAndUpdate({key:s,args:i}),this.descriptionIntl.element.parentElement||this.appendTo.append(this.descriptionIntl.element)}}class Qr{constructor(e){this.appendTo=e,this.peerTitle=new wt.a({peerId:0})}update(e){const{peerTitle:t,appendTo:s}=this,i=e.groupCall,n=e.chatId.toPeerId(!0);i.title?Object(m.a)(s,X.b.wrapEmojiText(i.title)):(t.peerId!==n&&(t.peerId=n,t.update()),t.element.parentElement!==s&&s.append(t.element))}}var $r=!!("getDisplayMedia"in((null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||{}));function Yr(e,t,s){const i=e+"-button",n=document.createElement("div");n.classList.add(i,"call-button","rp-overflow"),s.icon&&n.classList.add("tgico-"+s.icon),s.noRipple||Object(te.a)(n),s.isDanger&&n.classList.add(i+"-red"),s.isConfirm&&n.classList.add(i+"-green"),s.callback&&Object(l.b)(n,s.callback,{listenerSetter:t});let a=n;if(s.text){const e=document.createElement("div");e.classList.add(i+"-container","call-button-container");const t="string"==typeof s.text?Object(T.d)(s.text):s.text;t.classList.add(i+"-text","call-button-text"),e.append(n,t),a=e}return a}class Xr extends D.a{constructor(e){super(!0),this.onResize=()=>{this.fixDimensions(),this.fixPosition(),this.setPosition()},Object(w.a)(this,e),this.top=this.left=this.width=this.height=0,this.element.classList.add("movable-element"),this.addResizeHandlers(),this.setSwipeHandler(),b.b.addEventListener("resize",this.onResize)}destroyElements(){this.element.classList.remove("movable-element"),this.handlers&&this.handlers.forEach(e=>{e.remove()})}destroy(){b.b.removeEventListener("resize",this.onResize),this.swipeHandler.removeListeners()}addResizeHandlers(){this.handlers=["n","e","s","w","ne","se","sw","nw"].map(e=>{const t=document.createElement("div");return t.dataset.side=e,t.classList.add("movable-element-resize-handler","movable-element-resize-handler-side-"+e),this.element.append(t),t})}setSwipeHandler(){let e,t,s,i,n;const a=this.swipeHandler=new Qt({element:this.element,onSwipe:(a,o,r)=>{if(a*=-1,o*=-1,n){if(n.includes("e")||n.includes("w")){const e=n.includes("e")&&a>0||n.includes("w")&&a<0,i=Math.abs(a)*(e?1:-1),o=n.includes("e")?St.a.width-t:s+t;this.width=Math.min(o,s+i)}if(n.includes("n")||n.includes("s")){const t=n.includes("s")&&o>0||n.includes("n")&&o<0,s=Math.abs(o)*(t?1:-1),a=n.includes("s")?St.a.height-e:i+e;this.height=Math.min(a,i+s)}this.fixDimensions(),n.includes("w")&&(this.left=Math.min(t+s-this.minWidth,t+a)),n.includes("n")&&(this.top=Math.min(e+i-this.minHeight,e+o))}else this.top=e+o,this.left=t+a;this.fixPosition(),this.setPosition()},verifyTouchTarget:e=>{const t=e.target;if(this.verifyTouchTarget&&!this.verifyTouchTarget(e))return!1;const s=Object(Ce.a)(t,"movable-element-resize-handler");return s?(n=s.dataset.side,a.setCursor("")):(n=void 0,a.setCursor("grabbing")),!0},onFirstSwipe:()=>{e=this.top,t=this.left,s=this.width,i=this.height}})}setPositionToCenter(){this.top=St.a.height/2-this.height/2,this.left=St.a.width/2-this.width/2,this.setPosition()}fixDimensions(){this.width=Object(ke.a)(this.width,this.minWidth,St.a.width),this.height=Object(ke.a)(this.height,this.minHeight,St.a.height)}fixPosition(){this.top=Object(ke.a)(this.top,0,St.a.height-this.height),this.left=Object(ke.a)(this.left,0,St.a.width-this.width)}setPosition(){this.element.style.top=this.top+"px",this.element.style.left=this.left+"px",this.element.style.right="auto",this.element.style.bottom="auto",this.element.style.width=this.width+"px",this.element.style.height=this.height+"px",this.dispatchEvent("resize")}get width(){return this._width}get height(){return this._height}set width(e){this._width=e}set height(e){this._height=e}get state(){const{top:e,left:t,width:s,height:i}=this;return{top:e,left:t,width:s,height:i}}set state(e){const{top:t,left:s,width:i,height:n}=e;this.top=t,this.left=s,this.width=i,this.height=n,this.onResize()}}var Jr,Zr,el,tl=function(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)},sl=function(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,s):n?n.value=s:t.set(e,s),s};class il{constructor(e){Jr.set(this,void 0),Object(w.a)(this,e),this.toggleMovable(!he.a),this.listenerSetter.add(b.b)("changeScreen",(e,t)=>{t!==b.a.mobile&&e!==b.a.mobile||this.toggleMovable(!he.a)})}destroy(){const e=this.movable;e&&e.destroy()}get movable(){return tl(this,Jr,"f")}get state(){return this.movable?this.movable.state:this.previousState}set state(e){this.previousState=e}toggleMovable(e){let{movable:t}=this;if(e){if(t)return;t=sl(this,Jr,new Xr(this.movableOptions),"f"),t.state=this.previousState,void 0===this.previousState.top&&t.setPositionToCenter(),this.onResize&&this.listenerSetter.add(t)("resize",this.onResize)}else{if(!t)return;this.previousState=t.state,t.destroyElements(),t.destroy(),sl(this,Jr,void 0,"f")}}}function nl(e,t,s){return t.forEach(t=>{t.classList.toggle(e,s)}),()=>nl(e,t,!s)}function al(e){const t=Zr;return e.pFlags.muted_by_you?t.MUTED_FOR_ME:void 0!==e.raise_hand_rating?t.HAND:e.pFlags.muted?e.pFlags.can_self_unmute?t.MUTED:t.MUTED_BY_ADMIN:t.UNMUTED}Jr=new WeakMap,function(e){e[e.UNMUTED=0]="UNMUTED",e[e.MUTED=1]="MUTED",e[e.MUTED_FOR_ME=2]="MUTED_FOR_ME",e[e.MUTED_BY_ADMIN=3]="MUTED_BY_ADMIN",e[e.HAND=4]="HAND"}(Zr||(Zr={})),function(e){e[e.HAND=0]="HAND",e[e.MUTED=1]="MUTED",e[e.UNMUTED=2]="UNMUTED"}(el||(el={}));let ol={width:420,height:640};class rl extends ht.b{constructor(e){super("popup-group-call",void 0,{body:!0,withoutOverlay:!0,closable:!0}),this.onFullScreenClick=()=>{Object(Rr.e)(this.container)},this.onToggleControls=e=>{this.container.classList.toggle("show-controls",e),this.buttonsContainer.classList.toggle("show-controls",e)},this.toggleDisability=nl.bind(null,"btn-disabled"),this.onVideoClick=()=>{const e=this.toggleDisability([this.btnVideo],!0);this.instance.toggleVideoSharing().finally(()=>{e()})},this.onScreenClick=()=>{const e=this.toggleDisability([this.btnScreen],!0);this.instance.toggleScreenSharing().finally(()=>{e()})},this.onMuteClick=()=>{const e=this.instance.participant;e.pFlags.can_self_unmute?this.instance.toggleMuted():void 0===e.raise_hand_rating&&this.instance.changeRaiseHand(!0)},this.onLeaveClick=()=>{const e=e=>{this.instance.hangUp(e)};this.appChatsManager.hasRights(this.instance.chatId,"manage_call")?new ut("popup-end-video-chat",{titleLangKey:"VoiceChat.End.Title",descriptionLangKey:"VoiceChat.End.Text",checkboxes:[{text:"VoiceChat.End.Third"}],buttons:[{langKey:"VoiceChat.End.OK",callback:t=>{e(!!t.size)},isDanger:!0}]}).show():e(!1)},this.onFullScreenChange=()=>{this.toggleBigLayout();const e=Object(Rr.d)(),{btnFullScreen:t,btnExitFullScreen:s}=this,i=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",e),t&&t.classList.toggle("hide",e),s&&s.classList.toggle("hide",!e),this.btnClose.classList.toggle("hide",e),e!==i&&(I.a.checkAnimations(e),a.a.setThemeColor(e?"#000000":void 0))},this.toggleBigLayout=()=>{var e;const t=Object(Rr.d)(),s=null===(e=this.movablePanel)||void 0===e?void 0:e.movable,i=(t||!!(s&&s.width>=680))&&!!this.videosCount,n=this.container.classList.contains("is-big-layout");let a;i&&!n&&(a=Array.from(this.buttonsContainer.children),a.forEach(e=>{e.style.opacity="0"}),this.buttonsContainer.offsetLeft),this.container.classList.toggle("is-big-layout",i),this.btnInvite.classList.toggle("hide",i),this.btnShowColumn.classList.toggle("hide",!i),a&&a.forEach(e=>{e.style.opacity=""})},this.toggleRightColumn=()=>{this.container.classList.toggle("is-right-column-shown")},Object(w.a)(this,e),this.videosCount=0,this.container.classList.add("group-call","night");const t=this.instance=this.appGroupCallsManager.groupCall,{listenerSetter:s}=this;if(!ae.c){const e=this.btnFullScreen=N("fullscreen"),t=this.btnFullScreen2=N("fullscreen group-call-cfs"),i=this.btnExitFullScreen=N("smallscreen");Object(l.b)(e,this.onFullScreenClick,{listenerSetter:s}),Object(l.b)(t,this.onFullScreenClick,{listenerSetter:s}),Object(l.b)(i,()=>{Object(Rr.b)()},{listenerSetter:s}),Object(Rr.a)(this.container,this.onFullScreenChange,s)}this.btnInvite=N("adduser");const i=this.btnShowColumn=N("rightpanel group-call-only-big");Object(l.b)(i,this.toggleRightColumn,{listenerSetter:s});const n=document.createElement("div");n.classList.add("group-call-header-info"),this.title.classList.add("group-call-header-title");const o=document.createElement("div");o.classList.add("group-call-header-subtitle"),n.append(this.title,o),this.header.classList.add("group-call-header"),this.header.append(...[this.btnExitFullScreen,n,this.btnFullScreen,i].filter(Boolean));const r=this.header.cloneNode(!1),c=n.cloneNode(!1),d=this.title.cloneNode(!1);c.append(d);const h=N("rightpanel");r.append(...[h,c,this.btnFullScreen2].filter(Boolean)),Object(l.b)(h,this.toggleRightColumn,{listenerSetter:s}),this.body.prepend(r);const p=new P.b(void 0);p.container.classList.add("group-call-big-video-container"),this.container.append(p.container),this.groupCallTitle=new Qr(this.title),this.groupCallDescription=new qr(o),this.groupCallBodyHeaderDescription=new qr(d),this.constructButtons(),this.groupCallParticipantsVideo=new Kr(Object.assign({appendTo:p.container,instance:t,listenerSetter:s,displayPinned:!0,onLengthChange:e=>{this.videosCount=e,this.toggleBigLayout()}},e)),this.groupCallParticipants=new Wr(Object.assign({appendTo:this.body,instance:t,listenerSetter:s},e)),this.movablePanel=new il({listenerSetter:s,movableOptions:{minWidth:400,minHeight:480,element:this.element,verifyTouchTarget:e=>{const t=e.target;return!(Object(Ce.a)(t,"chatlist")||Object(Ce.a)(t,"group-call-button")||Object(Ce.a)(t,"btn-icon")||Object(Ce.a)(t,"group-call-participants-video-container")||Object(Rr.d)())}},onResize:()=>this.toggleBigLayout(),previousState:ol}),s.add(t)("state",()=>{this.updateInstance()}),s.add(a.a)("group_call_update",e=>{var t;(null===(t=this.instance)||void 0===t?void 0:t.id)===e.id&&this.updateInstance()}),s.add(t)("pinned",()=>{this.setHasPinned()}),s.add(this.groupCallParticipantsVideo)("toggleControls",this.onToggleControls),this.addEventListener("close",()=>{const{movablePanel:e}=this;ol=e.state,this.groupCallParticipantsVideo.destroy(),this.groupCallParticipants.destroy(),this.groupCallMicrophoneIcon.destroy(),e.destroy()}),this.toggleRightColumn(),this.onFullScreenChange(),this.updateInstance()}constructButtons(){const e=this.buttonsContainer=document.createElement("div");e.classList.add("group-call-buttons");const t=Yr.bind(null,"group-call",this.listenerSetter),s=this.btnVideo=t({callback:this.onVideoClick,icon:"videocamera_filled"}),i=this.btnScreen=t({callback:this.onScreenClick,icon:"sharescreen_filled"});i.classList.toggle("hide",!$r);const n=t({noRipple:!0,callback:Object(ws.a)(this.onMuteClick,600,!0)});n.classList.add("group-call-microphone-button");const a=this.groupCallMicrophoneIcon=new Dr;n.append(a.container);const o=t({icon:"settings_filled"});o.classList.add("btn-disabled"),o.classList.toggle("hide",!$r);const r=t({isDanger:!0,callback:this.onLeaveClick,icon:"close"});e.append(s,i,n,o,r),this.container.append(e)}getContainer(){return this.container}setHasPinned(){this.container.classList.toggle("has-pinned",!!this.instance.pinnedSource)}updateInstance(){if(this.instance.state===Pr.a.CLOSED)return this.container.classList.contains("is-full-screen")&&Object(Rr.b)(),void this.hide();const{participant:e,groupCall:t}=this.instance;if(!e)return;this.setTitle(),this.setDescription(),this.setHasPinned();const s=function(e,t){const s=el;return t.pFlags.can_self_unmute?t.pFlags.muted?s.MUTED:s.UNMUTED:s.HAND}(0,e);this.container.dataset.micState=s===el.HAND?"hand":s===el.MUTED?"muted":"unmuted",this.groupCallMicrophoneIcon.setState(s)}setTitle(){this.groupCallTitle.update(this.instance)}setDescription(){this.groupCallDescription.update(this.instance),this.groupCallBodyHeaderDescription.update(this.instance)}}var ll,cl=s(185);!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.EXCHANGING_KEYS=2]="EXCHANGING_KEYS",e[e.PENDING=3]="PENDING",e[e.REQUESTING=4]="REQUESTING",e[e.CLOSING=5]="CLOSING",e[e.CLOSED=6]="CLOSED"}(ll||(ll={}));var dl=ll;class hl{constructor(e){this.appendTo=e,this.container=document.createElement("div"),this.container.classList.add("call-description")}detach(){void 0!==this.interval&&(clearInterval(this.interval),this.interval=void 0),this.container.remove(),this.state=void 0}update(e){const{connectionState:t}=e;if(this.state===t)return;let s;if(this.state=t,t===dl.CONNECTED){s=document.createElement("span"),s.classList.add("call-description-duration");const t=()=>{s.innerText=Te(e.duration,!0)};this.interval=window.setInterval(t,1e3),t()}else{let i;switch(t){case dl.PENDING:i=e.isOutgoing?"Call.StatusRinging":"Call.StatusCalling";break;case dl.REQUESTING:i="Call.StatusRequesting";break;case dl.EXCHANGING_KEYS:i="VoipExchangingKeys";break;case dl.CLOSED:i=void 0!==e.connectedAt?"Call.StatusEnded":"Call.StatusFailed";break;default:i="Call.StatusConnecting"}s=Object(T.d)(i),void 0!==this.interval&&(clearInterval(this.interval),this.interval=void 0)}this.container.classList.toggle("has-duration",t===dl.CONNECTED),Object(k.a)(this.container,s),this.container.parentElement||this.appendTo.append(this.container)}}class pl extends Fr{constructor(e,t){super({width:36,height:36,getPart:e=>this.getItem().getPart(e?"unmute":"mute"),getColor:e?e=>e?[255,255,255]:[158,158,158]:void 0,skipAnimation:t}),this.add({name:"voice_mini",parts:[{startFrame:0,endFrame:35,name:"hand-to-muted"},{startFrame:36,endFrame:68,name:"unmute"},{startFrame:69,endFrame:98,name:"mute"},{startFrame:99,endFrame:135,name:"muted-to-hand"},{startFrame:136,endFrame:171,name:"unmuted-to-hand"}]})}}const ul={width:400,height:580};let gl=Object.assign({},ul);class ml extends ht.b{constructor(e){super("popup-call",void 0,{withoutOverlay:!0,closable:!0}),this.onFullScreenClick=()=>{Object(Rr.e)(this.container)},this.onFullScreenChange=()=>{const e=Object(Rr.d)(),{btnFullScreen:t,btnExitFullScreen:s}=this,i=this.container.classList.contains("is-full-screen");this.container.classList.toggle("is-full-screen",e),t&&t.classList.toggle("hide",e),s&&s.classList.toggle("hide",!e),this.btnClose.classList.toggle("hide",e),e!==i&&(I.a.checkAnimations(e),a.a.setThemeColor(e?"#000000":void 0),this.resizeVideoContainers())},Object(w.a)(this,e),this.videoContainers={};const{container:t,listenerSetter:s,instance:i}=this;t.classList.add("call","night");const n=document.createElement("div");n.classList.add("call-avatar");const o=this.peerId=this.instance.interlocutorUserId.toPeerId(),r=new fc;r.classList.add("avatar-full"),r.updateWithOptions({isBig:!0,peerId:o}),n.append(r);const c=new wt.a({peerId:o}).element;c.classList.add("call-title");const d=document.createElement("div");d.classList.add("call-subtitle");this.description=new hl(d);const h=this.emojisSubtitle=document.createElement("div");h.classList.add("call-emojis"),t.append(n,c,d),ae.e?this.header.append(h):(this.btnFullScreen=N("fullscreen"),this.btnExitFullScreen=N("smallscreen hide"),Object(l.b)(this.btnFullScreen,this.onFullScreenClick,{listenerSetter:s}),Object(l.b)(this.btnExitFullScreen,()=>Object(Rr.b)(),{listenerSetter:s}),Object(Rr.a)(this.container,this.onFullScreenChange,s),this.header.prepend(this.btnExitFullScreen),this.header.append(this.btnFullScreen),t.append(h)),this.partyStates=document.createElement("div"),this.partyStates.classList.add("call-party-states"),this.partyMutedState=document.createElement("div"),this.partyMutedState.classList.add("call-party-state");const p=Object(T.d)("VoipUserMicrophoneIsOff",[new wt.a({peerId:o,onlyFirstName:!0,limitSymbols:18}).element]);p.classList.add("call-party-state-text");const u=new pl(!1,!0);u.setState(!1,!1),this.partyMutedState.append(u.container,p),this.partyStates.append(this.partyMutedState),this.container.append(this.partyStates),this.makeButton=Yr.bind(null,"call",this.listenerSetter),this.constructFirstButtons(),this.constructSecondButtons(),s.add(i)("state",()=>{this.updateInstance()}),s.add(i)("mediaState",()=>{this.updateInstance()}),this.movablePanel=new il({listenerSetter:s,movableOptions:{minWidth:400,minHeight:580,element:this.element,verifyTouchTarget:e=>{const t=e.target;return!(Object(Ce.a)(t,"call-button")||Object(Ce.a)(t,"btn-icon")||Object(Rr.d)())}},previousState:this.instance.wasTryingToJoin||this.instance.isOutgoing?gl:Object.assign({},ul)});const g=this.movablePanel.movable;g&&this.listenerSetter.add(g)("resize",()=>{this.resizeVideoContainers()});const m=this.controlsHover=new Hr;m.setup({element:this.container,listenerSetter:this.listenerSetter,showOnLeaveToClassName:"call-buttons"}),m.showControls(!1),this.addEventListener("close",()=>{const{movablePanel:e}=this;gl=e.state,this.microphoneIcon.destroy(),e.destroy()}),this.updateInstance()}getCallInstance(){return this.instance}constructFirstButtons(){const e=this.firstButtonsRow=document.createElement("div");e.classList.add("call-buttons","is-first");const t=nl.bind(null,"btn-disabled"),s=this.btnVideo=this.makeButton({text:"Call.Camera",icon:"videocamera_filled",callback:()=>{const e=t([s,i],!0);this.instance.toggleVideoSharing().finally(e)}}),i=this.btnScreen=this.makeButton({text:"Call.Screen",icon:"sharescreen_filled",callback:()=>{const e=t([s,i],!0);this.instance.toggleScreenSharing().finally(e)}});$r||(i.classList.add("hide"),this.container.classList.add("no-screen")),this.muteI18nElement=new T.c.IntlElement({key:"Call.Mute"});const n=this.btnMute=this.makeButton({text:this.muteI18nElement.element,callback:()=>{this.instance.toggleMuted()}}),a=this.microphoneIcon=new pl(!0,!0);n.firstElementChild.append(a.container),e.append(s,i,n),this.container.append(e)}constructSecondButtons(){const e=this.secondButtonsRow=document.createElement("div");e.classList.add("call-buttons","is-second"),this.declineI18nElement=new T.c.IntlElement({key:"Call.Decline"});const t=this.btnDecline=this.makeButton({text:this.declineI18nElement.element,icon:"endcall_filled",callback:()=>{this.instance.hangUp("phoneCallDiscardReasonHangup")},isDanger:!0}),s=this.btnAccept=this.makeButton({text:"Call.Accept",icon:"phone_filled",callback:()=>{this.instance.acceptCall()},isConfirm:!0});e.append(t,s),this.container.append(e)}createVideoContainer(e){const t=document.createElement("div");t.classList.add("call-video-container"),e.classList.add("call-video"),e.paused&&e.play(),Object(l.b)(t,()=>{if(!t.classList.contains("small"))return;const e=Object.values(this.videoContainers).find(e=>!e.classList.contains("small"));e.classList.add("small"),e.style.cssText=t.style.cssText,t.classList.remove("small"),t.style.cssText="",this.resizeVideoContainers()});const s=zr(e);return s.classList.add("call-video-blur"),t.append(s,e),t}updateInstance(){const{instance:e}=this,{connectionState:t}=e;if(t===dl.CLOSED)return this.container.classList.contains("is-full-screen")&&Object(Rr.b)(),this.btnVideo.classList.add("disabled"),void this.hide();const s=!e.isOutgoing&&t===dl.PENDING;this.declineI18nElement.compareAndUpdate({key:t===dl.PENDING?"Call.Decline":"Call.End"}),this.btnAccept.classList.toggle("disable",!s),this.btnAccept.classList.toggle("hide-me",!s),this.container.classList.toggle("two-button-rows",s);const i=e.isMuted,n=()=>{this.btnMute.firstElementChild.classList.toggle("active",i)},a=this.microphoneIcon.getItem().player;this.microphoneIcon.setState(!i,!i,n),a||n(),this.muteI18nElement.compareAndUpdate({key:i?"VoipUnmute":"Call.Mute"});const o=e.isSharingVideo;this.btnVideo.firstElementChild.classList.toggle("active",o);const r=e.isSharingScreen;this.btnScreen.firstElementChild.classList.toggle("active",r);const l=e.getMediaState("output");Object(is.a)(this.partyMutedState,"is-visible",!!(null==l?void 0:l.muted),300);const c=this.videoContainers,d=Object.assign({},c);["input","output"].forEach(t=>{const s=e.getMediaState(t),i=e.getVideoElement(t),n=!!(i&&i.videoWidth&&i.videoHeight);!i||n||i.dataset.hasPromise||(i.dataset.hasPromise="1",Object(pe.e)(i).then(()=>{delete i.dataset.hasPromise,this.updateInstance()}));const a=!!i&&n&&!(!s||"active"!==s.videoState&&"active"!==s.screencastState);let o=c[t];a&&i&&!o&&(o=c[t]=this.createVideoContainer(i),this.container.append(o)),!a&&o&&(o.remove(),delete c[t])});{const e=c.input,t=c.output;Object.keys(d).length!==Object.keys(c).length&&e&&e.classList.toggle("small",!!t),t&&!e&&t.classList.remove("small")}this.resizeVideoContainers(),this.container.classList.toggle("no-video",!Object.keys(c).length),!this.emojisSubtitle.textContent&&t<dl.EXCHANGING_KEYS&&Promise.resolve(e.getEmojisFingerprint()).then(e=>{this.emojisSubtitle.append(X.b.wrapEmojiText(e.join("")))}),this.setDescription()}resizeVideoContainers(){Object.values(this.videoContainers).forEach(e=>{if(e.classList.contains("small")){const t=e.querySelector("video"),s=this.movablePanel.state,i=240,n=240,a=t.videoHeight>t.videoWidth,o=a?n:i,r=1/3*(Object(Rr.d)()?65535:a?s.height:s.width),l=a?t.videoWidth/t.videoHeight:1,c=a?1:t.videoHeight/t.videoWidth;e.style.width=r*l+"px",e.style.height=r*c+"px",e.style.maxWidth=o*l+"px",e.style.maxHeight=o*c+"px"}else e.style.cssText=""})}setDescription(){this.description.update(this.instance)}}var bl=s(186),vl=s(167);function fl(e){const t=Object(vl.a)(e,e.media[0]),s={"@type":"InitialSetup",fingerprints:[t.fingerprint],ufrag:t.ufrag,pwd:t.pwd,audio:void 0,video:void 0,screencast:void 0},i=e=>""+e;for(const t of e.media){const n=t.mediaType;if("application"===n||!t.isSending)continue;const a=s["video"===n&&s.video?"screencast":n]={},o=Object(vl.a)(e,t);a.ssrc=i(o.source),o.sourceGroups&&(a.ssrcGroups=o.sourceGroups.map(e=>({semantics:e.semantics,ssrcs:e.sources.map(i)})));const r=a.rtpExtensions=[];t.attributes.get("extmap").forEach(e=>{r.push({id:+e.key,uri:e.value})});const l=new Map,c=e=>{let t=l.get(e);return t||l.set(e,t={id:e}),t};t.attributes.get("rtpmap").forEach(e=>{const t=+e.key,s=c(t),i=e.value.split("/"),[n,a,o]=i;s.name=n,s.clockrate=+a,s.channels=o?+o:0}),t.attributes.get("rtcp-fb").forEach(e=>{const t=+e.key;c(t).feedbackTypes=e.lines.map(e=>{const t=e.split(" "),[s,i]=t;return{type:s,subtype:i||""}})}),t.attributes.get("fmtp").forEach(e=>{const t=+e.key,s=c(t).parameters={},i=e.value.split(";");for(const e of i){const[t,i]=e.split("=");s[t]=i}}),a.payloadTypes=Array.from(l.values())}return s}var yl=s(164),wl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Sl extends bl.a{constructor(e){super(e)}negotiateInternal(){return wl(this,void 0,void 0,(function*(){const{connection:e,call:t}=this;if(!e.localDescription&&!e.remoteDescription&&!t.isOutgoing)return;let s;if(t.offerReceived){t.offerReceived=!1;const i=s=yield e.createAnswer();this.log("[sdp] local",i.type,i.sdp),yield e.setLocalDescription(i),this.log("[InitialSetup] send 2")}else{const i=s=yield e.createOffer();this.log("[sdp] local",i.sdp),yield e.setLocalDescription(i),t.offerSent=!0,this.log("[InitialSetup] send 0")}const i=fl(Object(yl.b)(s.sdp));t.sendCallSignalingData(i)}))}}var Cl=s(192),Ll=s(162),Il=s(146),Ml=s(135);var El=s(52);var Pl="undefined"!=typeof window&&"crypto"in window?window.crypto.subtle:self.crypto.subtle;function kl(e){return Pl.digest("SHA-256",function(e){return e instanceof Uint8Array?e:"string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e)}(e)).then(e=>new Uint8Array(e))}var Tl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class xl{constructor(e,t){this.isOutgoing=e,this.p2pKey=t,this.type="Signaling",this.counter=0,this.seqMap=new Map}concatSHA256(e){return kl(Object(El.a)(...e))}encryptPrepared(e){return Tl(this,void 0,void 0,(function*(){const t={counter:0,bytes:new Uint8Array(16+e.length)},s=(this.isOutgoing?0:8)+("Signaling"===this.type?128:0),i=this.p2pKey,n=yield this.concatSHA256([i.subarray(s+88,s+88+32),e]),a=t.bytes;for(let e=0;e<16;++e)a[e]=n[e+8];const o=yield this.prepareAesKeyIv(i,a,s),r=yield this.aesProcessCtr(e,e.length,o,!0);return t.bytes=new Uint8Array([...t.bytes.subarray(0,16),...r]),t}))}encryptRawPacket(e){const t=++this.counter,s=new ArrayBuffer(4);new DataView(s).setUint32(0,t>>>0,!1);const i=new Uint8Array([...new Uint8Array(s),...e]);return this.encryptPrepared(i)}prepareAesKeyIv(e,t,s){return Tl(this,void 0,void 0,(function*(){const[i,n]=yield Promise.all([this.concatSHA256([t.subarray(0,16),e.subarray(s,s+36)]),this.concatSHA256([e.subarray(40+s,40+s+36),t.subarray(0,16)])]);return{key:new Uint8Array([...i.subarray(0,8),...n.subarray(8,24),...i.subarray(24,32)]),iv:new Uint8Array([...n.subarray(0,4),...i.subarray(8,16),...n.subarray(24,28)])}}))}aesProcessCtr(e,t,s,i=!0){return Tl(this,void 0,void 0,(function*(){const t=yield Pl.importKey("raw",s.key,{name:"AES-CTR"},!1,[i?"encrypt":"decrypt"]),n=yield Pl[i?"encrypt":"decrypt"]({name:"AES-CTR",counter:s.iv,length:8*s.iv.length},t,e);return new Uint8Array(n)}))}constTimeIsDifferent(e,t,s){let i=!0;for(let n=0;n<s;++n)e[n]!==t[n]&&(i=!1);return!i}decryptRawPacket(e){return Tl(this,void 0,void 0,(function*(){if(e.length<21||e.length>134217728)return;const{isOutgoing:t,type:s}=this,i=(t?8:0)+("Signaling"===s?128:0),n=this.p2pKey,a=e.subarray(0,16),o=e.subarray(16),r=e.length-16,l=yield this.prepareAesKeyIv(n,a,i),c=yield this.aesProcessCtr(o,r,l,!1),d=yield this.concatSHA256([n.subarray(88+i,88+i+32),c]);if(this.constTimeIsDifferent(d.subarray(8),a,16))return;const h=new DataView(c.buffer).getUint32(0);return this.seqMap.has(h)?void 0:(this.seqMap.set(h,h),c.slice(4))}))}}var Al=s(182);class Ol{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a],r=new Al.a;r.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach(e=>{const{hash:t,fingerprint:s,setup:i}=e;r.add(`a=fingerprint:${t} ${s}`,"a=setup:"+i)}),s&&i&&r.add("a=ice-ufrag:"+s,"a=ice-pwd:"+i),r.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const l="stream"+o.map(e=>e.ssrc).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(s){case"audio":r.add("m=audio 56930 UDP/TLS/RTP/SAVPF "+a.map(e=>e.id).join(" "),"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle","a=mid:"+e,"a=sendrecv",Rl(c)),i&&r.add(`a=msid:${l} audio${i}`),r.add("a=rtcp-mux",Bl(a),Nl(s,i,n,l));break;case"video":r.add("m=video 61986 UDP/TLS/RTP/SAVPF "+a.map(e=>e.id).join(" "),"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle","a=mid:"+e,"a=sendrecv",Rl(c)),i&&r.add(`a=msid:${l} video${i}`),r.add("a=rtcp-mux","a=rtcp-rsize",Bl(a),Nl(s,i,n,l))}}return r.add(Ul(2)),r.finalize()}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a],r=new Al.a;r.add("v=0","o=- 1 2 IN IP4 127.0.0.1","s=-","t=0 0"),t&&t.forEach(e=>{const{hash:t,fingerprint:s,setup:i}=e;r.add(`a=fingerprint:${t} ${s}`,"a=setup:"+i)}),s&&i&&r.add("a=ice-ufrag:"+s,"a=ice-pwd:"+i),r.add("a=group:BUNDLE 0 1 2","a=extmap-allow-mixed","a=msid-semantic: WMS *");const l="stream"+o.map(e=>e.ssrc).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(s){case"audio":r.add("m=audio 56930 UDP/TLS/RTP/SAVPF "+a.map(e=>e.id).join(" "),"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle","a=mid:"+e,"a=sendrecv",Rl(c)),i&&r.add(`a=msid:${l} audio${i}`),r.add("a=rtcp-mux",Bl(a),Nl(s,i,n,l));break;case"video":r.add("m=video 61986 UDP/TLS/RTP/SAVPF "+a.map(e=>e.id).join(" "),"c=IN IP4 0.0.0.0","a=rtcp:9 IN IP4 0.0.0.0","a=ice-options:trickle","a=mid:"+e,"a=sendrecv",Rl(c)),i&&r.add(`a=msid:${l} video${i}`),r.add("a=rtcp-mux","a=rtcp-rsize",Bl(a),Nl(s,i,n,l))}}return r.add(Ul(2)),r.finalize()}}class jl{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];let r="v=0\no=- 1 0 IN IP4 0.0.0.0\ns=-\nt=0 0";t&&t.forEach(e=>{const{hash:t,fingerprint:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`}),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),r+="\na=group:BUNDLE 0 1 2\na=ice-options:trickle\na=msid-semantic:WMS *";const l="stream"+o.map(e=>e.ssrc).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(s){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${a.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=Rl(c),r+="\na=rtcp-mux",r+=Bl(a),r+=Nl(s,i,n,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${a.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=Rl(c),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Bl(a),r+=Nl(s,i,n,l)}}return r+=Ul(2),r+="\n",r}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];let r="v=0\no=- 1 0 IN IP4 0.0.0.0\ns=-\nt=0 0";t&&t.forEach(e=>{const{hash:t,fingerprint:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`}),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),r+="\na=group:BUNDLE 0 1 2\na=ice-options:trickle\na=msid-semantic:WMS *";const l="stream"+o.map(e=>e.ssrc).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:s,mid:i,ssrc:n,ssrcGroups:a,payloadTypes:c,dir:d,rtpExtensions:h}=t;switch(s){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${c.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=Rl(h),r+="\na=rtcp-mux",r+=Bl(c),r+=Nl(s,n,a,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${c.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=mid:${e}\na=sendrecv`,r+=Rl(h),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Bl(c),r+=Nl(s,n,a,l)}}return r+=Ul(2),r+="\n",r}}class _l{static generateOffer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];if(!o.length)return"v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0\na=msid-semantic: WMS\n";let r="v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0";t&&t.forEach(e=>{const{hash:t,fingerprint:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`}),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),r+="\na=group:BUNDLE 0 1 2\na=extmap-allow-mixed\na=msid-semantic: WMS *";const l="stream"+o.map(e=>e.ssrc).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(s){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${a.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=Rl(c),i&&(r+=`\na=msid:${l} audio${i}`),r+="\na=rtcp-mux",r+=Bl(a),r+=Nl(s,i,n,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${a.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=Rl(c),i&&(r+=`\na=msid:${l} video${i}`),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Bl(a),r+=Nl(s,i,n,l)}}return r+=Ul(2),r+="\n",r}static generateAnswer(e){const{fingerprints:t,ufrag:s,pwd:i,audio:n,video:a}=e;n.type="audio",a.type="video";const o=[n,a];if(!o.length)return"v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0\na=msid-semantic: WMS\n";let r="v=0\no=- 1 2 IN IP4 127.0.0.1\ns=-\nt=0 0";t&&t.forEach(e=>{const{hash:t,fingerprint:s,setup:i}=e;r+=`\na=fingerprint:${t} ${s}\na=setup:${i}`}),s&&i&&(r+=`\na=ice-ufrag:${s}\na=ice-pwd:${i}`),r+="\na=group:BUNDLE 0 1 2\na=extmap-allow-mixed\na=msid-semantic: WMS *";const l="stream"+o.map(e=>e.ssrc).join("_");for(let e=0;e<o.length;e++){const t=o[e],{type:s,ssrc:i,ssrcGroups:n,payloadTypes:a,rtpExtensions:c}=t;switch(s){case"audio":r+=`\nm=audio 9 UDP/TLS/RTP/SAVPF ${a.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=Rl(c),i&&(r+=`\na=msid:${l} audio${i}`),r+="\na=rtcp-mux",r+=Bl(a),r+=Nl(s,i,n,l);break;case"video":r+=`\nm=video 9 UDP/TLS/RTP/SAVPF ${a.map(e=>e.id).join(" ")}\nc=IN IP4 0.0.0.0\na=rtcp:9 IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:${e}\na=sendrecv`,r+=Rl(c),i&&(r+=`\na=msid:${l} video${i}`),r+="\na=rtcp-mux\na=rtcp-rsize",r+=Bl(a),r+=Nl(s,i,n,l)}}return r+=Ul(2),r+="\n",r}}function Fl(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function Dl(){return navigator.userAgent.toLowerCase().indexOf("safari")>-1&&-1===navigator.userAgent.toLowerCase().indexOf("chrome")}function Rl(e){let t=[];for(let s=0;s<e.length;s++){const i=e[s],{id:n,uri:a}=i;console.log("[extmap] add",n,a),t.push(`a=extmap:${n} ${a}`)}return t.join("\n")}function Bl(e){let t=[];console.log("[SDP] addPayloadTypes",e);for(let s=0;s<e.length;s++){const i=e[s],{id:n,name:a,clockrate:o,channels:r,feedbackTypes:l,parameters:c}=i;if(t.push(`a=rtpmap:${n} ${a}/${o}${r?"/"+r:""}`),l&&l.forEach(e=>{const{type:s,subtype:i}=e;t.push(`a=rtcp-fb:${n} ${[s,i].join(" ")}`)}),c){const e=[];Object.getOwnPropertyNames(c).forEach(t=>{e.push(`${t}=${c[t]}`)}),t.push(`a=fmtp:${n} ${e.join(";")}`)}}return t.join("\n")}function Nl(e,t,s,i){let n=[];return s&&s.length>0?s.forEach(t=>{t&&t.ssrcs.length>0&&(n.push(`a=ssrc-group:${t.semantics} ${t.ssrcs.join(" ")}`),t.ssrcs.forEach(t=>{n.push(`a=ssrc:${t} cname:stream${t}`,`a=ssrc:${t} msid:${i} ${e}${t}`,`a=ssrc:${t} mslabel:${e}${t}`,`a=ssrc:${t} label:${e}${t}`)}))}):t&&n.push(`a=ssrc:${t} cname:stream${t}`,`a=ssrc:${t} msid:${i} ${e}${t}`,`a=ssrc:${t} mslabel:${e}${t}`,`a=ssrc:${t} label:${e}${t}`),n.join("\n")}function Ul(e){return"m=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 0.0.0.0\na=ice-options:trickle\na=mid:2\na=sctp-port:5000\na=max-message-size:262144"}class Hl{static generateCandidate(e){if(!e)return null;const{sdpString:t,sdpMLineIndex:s,sdpMid:i,foundation:n,component:a,protocol:o,priority:r,address:l,type:c,relAddress:d,generation:h,tcpType:p,networkId:u,networkCost:g,username:m}=e;if(t)return{candidate:t,sdpMLineIndex:s,sdpMid:i};throw"no sdpString"}static generateOffer(e){return Fl()?jl.generateOffer(e):Dl()?_l.generateOffer(e):Ol.generateOffer(e)}static generateAnswer(e){return Fl()?jl.generateAnswer(e):Dl()?_l.generateAnswer(e):Ol.generateAnswer(e)}}var zl=s(147),Vl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Kl extends Cl.a{constructor(e){super(),this.log=Object(Y.b)("CALL"),this.protocol||(this.protocol={_:"phoneCallProtocol",pFlags:{udp_p2p:!0,udp_reflector:!0},min_layer:92,max_layer:92,library_versions:["4.0.0"]}),Object(w.a)(this,e),this.createdAt=Date.now(),this.offerReceived=!1,this.offerSent=!1,this.decryptQueue=[],this.candidates=[],this.addEventListener("state",e=>{this.log("state",dl[e]),e===dl.CLOSED&&this.cleanup()});const t=this.streamManager=new zl.a(Ll.b);t.direction="sendrecv",t.types.push("screencast"),this.isOutgoing||(t.locked=!0,t.canCreateConferenceEntry=!1);let s={"@type":"MediaState",type:"input",lowBattery:!1,muted:!0,screencastState:"inactive",videoRotation:0,videoState:"inactive"};const i=this;s=new Proxy(s,{set:function(e,t,n){return e[t]=n,i.setMediaState(s),i.sendMediaState(),!0}}),this.mediaStates={input:s},this.sendMediaState=Object(lt.a)(this._sendMediaState.bind(this),0,!1,!0)}get connectionState(){const{_connectionState:e,connectionInstance:t}=this;if(void 0!==e)return e;if(t){const{iceConnectionState:e}=t.connection;return"closed"===e?dl.CLOSED:"connected"===e||ae.g&&"completed"===e?dl.CONNECTED:dl.CONNECTING}return dl.CONNECTING}get sortIndex(){const e=this.connectionState;let t=1e13*(dl.CLOSED-e+1);return t+=2147483647e3-(e===dl.PENDING&&this.isOutgoing?0:this.createdAt),t}getVideoElement(e){if("input"===e)return this.elements.get("main");{const e=this.getMediaState("output");if(!e)return;const t="active"===e.videoState?"video":"active"===e.screencastState?"screencast":void 0;if(!t)return;const s=this.description.findEntry(e=>e.type===t);if(!s)return;return this.elements.get(""+s.recvEntry.source)}}startScreenSharingInternal(){return Vl(this,void 0,void 0,(function*(){try{this.wasStartingScreen=!0,this.wasStartingVideo=!1,this.streamManager.types=["audio","screencast"],yield this.requestScreen()}catch(e){this.log.error("startScreenSharing error",e)}}))}toggleScreenSharing(){return Vl(this,void 0,void 0,(function*(){return this.isSharingVideo&&(yield this.stopVideoSharing()),this.isSharingScreen?this.stopVideoSharing():this.startScreenSharingInternal()}))}startVideoSharingInternal(){return Vl(this,void 0,void 0,(function*(){try{this.wasStartingScreen=!1,this.wasStartingVideo=!0,this.streamManager.types=["audio","video"],yield this.requestInputSource(!1,!0,!1)}catch(e){this.log.error("startVideoSharing error",e)}}))}stopVideoSharing(){return Vl(this,void 0,void 0,(function*(){const e=this.getMediaState("input");e.videoState=e.screencastState="inactive";const{streamManager:t,description:s}=this,i=t.inputStream.getVideoTracks()[0];i&&(Object(Il.a)(i),t.appendToConference(s))}))}toggleVideoSharing(){return Vl(this,void 0,void 0,(function*(){return this.isSharingScreen&&(yield this.stopVideoSharing()),this.isSharingVideo?this.stopVideoSharing():this.startVideoSharingInternal()}))}getMediaState(e){return this.mediaStates[e]}setMediaState(e){this.mediaStates[e.type]=e,this.dispatchEvent("mediaState",e)}isSharingVideoType(e){try{return super.isSharingVideo&&!!(this.wasStartingScreen&&"screencast"===e||this.wasStartingVideo&&"video"===e)}catch(e){return!1}}get isSharingVideo(){return this.isSharingVideoType("video")}get isSharingScreen(){return this.isSharingVideoType("screencast")}get isMuted(){const e=this.streamManager.inputStream.getAudioTracks()[0];return!(null==e?void 0:e.enabled)}get isClosing(){const{connectionState:e}=this;return e===dl.CLOSING||e===dl.CLOSED}get description(){var e;return null===(e=this.connectionInstance)||void 0===e?void 0:e.description}setHangUpTimeout(e,t){this.clearHangUpTimeout(),this.hangUpTimeout=ln.a.setTimeout(()=>{this.hangUpTimeout=void 0,this.hangUp(t)},e)}clearHangUpTimeout(){void 0!==this.hangUpTimeout&&(clearTimeout(this.hangUpTimeout),this.hangUpTimeout=void 0)}setPhoneCall(e){this.call=e;const{id:t}=e;if(this.id!==t){const e=this.id;this.id=t,this.dispatchEvent("id",t,e)}}acceptCall(){var e;return Vl(this,void 0,void 0,(function*(){const t=null===(e=(yield Promise.all(this.dispatchResultableEvent("acceptCallOverride")))[0])||void 0===e||e;if(this.isClosing||!t)return;this.overrideConnectionState(dl.EXCHANGING_KEYS);const s=this.call;this.requestInputSource(!0,!!s.pFlags.video,!1);const i=s.g_a_hash;this.appCallsManager.generateDh().then(e=>(this.dh={g_a_hash:i,b:e.a,g_b:e.g_a,g_b_hash:e.g_a_hash,p:e.p},this.apiManager.invokeApi("phone.acceptCall",{peer:this.appCallsManager.getCallInput(this.id),protocol:this.protocol,g_b:this.dh.g_b}))).then(e=>{this.appCallsManager.savePhonePhoneCall(e)}).catch(e=>{this.log.error("accept call error",e),this.hangUp("phoneCallDiscardReasonHangup")})}))}joinCall(){this.log("joinCall"),this.getEmojisFingerprint(),this.overrideConnectionState();const{isOutgoing:e,encryptionKey:t,streamManager:s}=this,i=function(e){const t=[];return e.connections.forEach(e=>{switch(e._){case"phoneConnectionWebrtc":{const{ip:s,ipv6:i,port:n,username:a,password:o}=e,r=[];e.pFlags.turn?(s&&r.push(`turn:${s}:${n}`),i&&r.push(`turn:[${i}]:${n}`)):e.pFlags.stun&&(s&&r.push(`stun:${s}:${n}`),i&&r.push(`stun:[${i}]:${n}`)),r.length>0&&t.push({urls:r,username:a,credential:o});break}}}),{iceServers:t,iceTransportPolicy:e.pFlags.p2p_allowed?"all":"relay"}}(this.call);if(this.log("joinCall configuration",i),!i)return;const n=this.connectionInstance=new Sl({call:this,streamManager:s,log:this.log.bindPrefix("connection")}),a=n.createPeerConnection(i);a.addEventListener("iceconnectionstatechange",()=>{const e=this.connectionState;void 0===this.connectedAt&&e===dl.CONNECTED&&(this.connectedAt=Date.now()),this.dispatchEvent("state",e)}),a.addEventListener("negotiationneeded",()=>{n.negotiate()}),a.addEventListener("icecandidate",e=>{const{candidate:t}=e;a.log("onicecandidate",t),(null==t?void 0:t.candidate)&&this.sendIceCandidate(t)}),a.addEventListener("track",e=>{const{track:t}=e;a.log("ontrack",t),this.onTrack(e)});n.createDescription();this.encryptor=new xl(e,t),this.decryptor=new xl(!e,t),this.log("currentCall",this),e&&n.appendStreamToConference(),this.createDataChannel(),this.processDecryptQueue()}createDataChannelEntry(){const e=this.description.createEntry("application");e.setDirection("sendrecv"),e.sendEntry=e.recvEntry=e}createDataChannel(){if(this.connectionInstance.dataChannel)return;const e=this.connectionInstance.createDataChannel({id:0,negotiated:!0});e.addEventListener("message",e=>{this.applyDataChannelData(JSON.parse(e.data))}),e.addEventListener("open",()=>{this.sendMediaState()})}applyDataChannelData(e){switch(e["@type"]){case"MediaState":e.type="output",this.log("got output media state",e),this.setMediaState(e);break;default:this.log.error("unknown data channel data:",e)}}_sendMediaState(){const{connectionInstance:e}=this;if(!e)return;const t=Object.assign({},this.getMediaState("input"));delete t.type,this.log("sendMediaState",t),e.sendDataChannelData(t)}sendCallSignalingData(e){return Vl(this,void 0,void 0,(function*(){const t=JSON.stringify(e),s=(new TextEncoder).encode(t),{bytes:i}=yield this.encryptor.encryptRawPacket(s);this.log("sendCallSignalingData",this.id,t),yield this.apiManager.invokeApi("phone.sendSignalingData",{peer:this.appCallsManager.getCallInput(this.id),data:i})}))}sendIceCandidate(e){this.log("sendIceCandidate",e);const{candidate:t,sdpMLineIndex:s}=e;if(0!==s)return;const i=function(e){if(!e||!e.startsWith("candidate:"))return;const t=e;e=e.substr("candidate:".length);const[s,i,n,a,o,r,...l]=e.split(" "),c={sdpString:t,foundation:s,component:i,protocol:n,priority:a,address:{ip:o,port:r}};for(let e=0;e<l.length;e+=2)switch(l[e]){case"typ":c.type=l[e+1];break;case"raddr":c.relAddress||(c.relAddress={}),c.relAddress.ip=l[e+1];break;case"rport":c.relAddress||(c.relAddress={}),c.relAddress.port=l[e+1];break;case"generation":c.generation=l[e+1];break;case"tcptype":c.tcpType=l[e+1];break;case"network-id":c.networkId=l[e+1];break;case"network-cost":c.networkCost=l[e+1];break;case"ufrag":c.username=l[e+1]}return c}(t);this.sendCallSignalingData({"@type":"Candidates",candidates:[i]})}confirmCall(){return Vl(this,void 0,void 0,(function*(){const{appCallsManager:e,apiManager:t,protocol:s,id:i,call:n}=this,a=this.dh;this.overrideConnectionState(dl.EXCHANGING_KEYS);const{key:o,key_fingerprint:r}=yield e.computeKey(n.g_b,a.a,a.p),l=yield t.invokeApi("phone.confirmCall",{peer:e.getCallInput(i),protocol:s,g_a:a.g_a,key_fingerprint:r});this.encryptionKey=o,e.savePhonePhoneCall(l),this.joinCall()}))}getEmojisFingerprint(){return this.emojisFingerprint?this.emojisFingerprint:this.getEmojisFingerprintPromise?this.getEmojisFingerprintPromise:this.getEmojisFingerprintPromise=this.apiManager.invokeCrypto("get-emojis-fingerprint",this.encryptionKey,this.dh.g_a).then(e=>(this.getEmojisFingerprintPromise=void 0,this.emojisFingerprint=e.map(e=>Object(se.a)(e))))}unlockStreamManager(){this.connectionInstance.streamManager.locked=!1,this.connectionInstance.appendStreamToConference()}doTheMagic(){return Vl(this,void 0,void 0,(function*(){this.connectionInstance.appendStreamToConference();const e=this.connectionInstance.connection;let t=yield e.createAnswer();this.log("[sdp] local",t.type,t.sdp),yield e.setLocalDescription(t),e.getTransceivers().filter(e=>"recvonly"===e.direction).forEach(e=>{const t=this.connectionInstance.description.getEntryByMid(e.mid);t.transceiver=t.recvEntry.transceiver=e,e.direction="sendrecv"});const s=this.description;let i=s.entries.map(e=>e.mid);const n={type:"offer",sdp:s.generateSdp({bundle:i,entries:s.entries.filter(e=>i.includes(e.mid)),isAnswer:!0})};yield e.setRemoteDescription(n),t=yield e.createAnswer(),yield e.setLocalDescription(t);const a=fl(Object(yl.b)(t.sdp));this.log("[InitialSetup] send 1"),this.sendCallSignalingData(a),this.unlockStreamManager()}))}overrideConnectionState(e){this._connectionState=e,this.dispatchEvent("state",this.connectionState)}get duration(){return void 0!==this.connectedAt?(Date.now()-this.connectedAt)/1e3|0:0}onInputStream(e){super.onInputStream(e);const t=e.getVideoTracks()[0];if(t){const e=this.getMediaState("input");this.wasStartingScreen||this.wasStartingVideo||(this.wasStartingVideo=!0),this.isSharingVideo?e.videoState="active":this.isSharingScreen&&(e.screencastState="active"),t.addEventListener("ended",()=>{this.stopVideoSharing()},{once:!0})}e.getAudioTracks().length&&this.onMutedChange()}onMutedChange(){const e=this.isMuted;this.dispatchEvent("muted",e);this.getMediaState("input").muted=e}toggleMuted(){return this.requestAudioSource(!0).then(()=>{this.setMuted(),this.onMutedChange()})}hangUp(e,t){return Vl(this,void 0,void 0,(function*(){if(!this.isClosing&&(this.discardReason=e,this.log("hangUp",e),this.overrideConnectionState(dl.CLOSED),this.connectionInstance&&this.connectionInstance.closeConnectionAndStream(!0),e&&!t)){let t=!1;for(const e in this.mediaStates){const s=this.mediaStates[e];t="active"===s.videoState||"active"===s.screencastState||t}yield this.appCallsManager.discardCall(this.id,this.duration,e,t)}}))}performCodec(e){const t=e.payloadTypes.map(e=>Object.assign(Object.assign({},e),{"rtcp-fbs":e.feedbackTypes}));return{"rtp-hdrexts":e.rtpExtensions,"payload-types":t}}setDataToDescription(e){this.description.setData({transport:{pwd:e.pwd,ufrag:e.ufrag,fingerprints:e.fingerprints,"rtcp-mux":!0},audio:this.performCodec(e.audio),video:e.video?this.performCodec(e.video):void 0,screencast:e.screencast?this.performCodec(e.screencast):void 0})}filterNotVP8(e){this.isOutgoing||[e.video,e.screencast].filter(Boolean).forEach(e=>{const t=e.payloadTypes,s=t.findIndex(e=>"VP8"===e.name),i=t[s],n=t.findIndex(e=>{var t;return+(null===(t=e.parameters)||void 0===t?void 0:t.apt)===i.id});e.payloadTypes=[t[s],t[n]]})}applyCallSignalingData(e){return Vl(this,void 0,void 0,(function*(){this.log("applyCallSignalingData",this,e);const{connection:t,description:s}=this.connectionInstance;switch(e["@type"]){case"InitialSetup":{this.log("[sdp] InitialSetup",e),this.filterNotVP8(e),this.setDataToDescription(e);const i=e=>e.map(e=>({_:"groupCallParticipantVideoSourceGroup",semantics:e.semantics,sources:e.ssrcs.map(e=>+e)}));[Object(Ml.c)("audio",+e.audio.ssrc),e.video?Object(Ml.c)("video",i(e.video.ssrcGroups)):void 0,e.screencast?Object(Ml.c)("screencast",i(e.screencast.ssrcGroups)):void 0].filter(Boolean).forEach(e=>{let t=s.getEntryBySource(e.source);if(t)return;const i=s.findFreeSendRecvEntry(e.type,!1);t=new Ml.a(i.mid,e.type),t.setDirection("sendrecv"),i.recvEntry=t,s.setEntrySource(t,e.sourceGroups||e.source)}),this.createDataChannelEntry();const n=this.offerSent;this.offerSent=!1;let a=s.entries.map(e=>e.mid);const o={type:n?"answer":"offer",sdp:s.generateSdp({bundle:a,entries:s.entries.filter(e=>a.includes(e.mid)),isAnswer:!n})};this.log("[sdp] remote",o.sdp),yield t.setRemoteDescription(o),yield this.tryToReleaseCandidates(),n||(yield this.doTheMagic());break}case"Candidates":for(const t of e.candidates){const e=Hl.generateCandidate(t);e.sdpMLineIndex=0;const s=new RTCIceCandidate(e);this.candidates.push(s)}yield this.tryToReleaseCandidates();break;default:this.log.error("unrecognized signaling data",e)}}))}tryToReleaseCandidates(){return Vl(this,void 0,void 0,(function*(){const{connectionInstance:e}=this;if(!e)return;const{connection:t}=e;if(t.remoteDescription){const e=this.candidates.map(e=>this.addIceCandidate(t,e));this.candidates.length=0,yield Promise.all(e)}else this.log("[candidates] postpone")}))}addIceCandidate(e,t){return Vl(this,void 0,void 0,(function*(){this.log("[candidate] start",t);try{yield e.addIceCandidate(t),this.log("[candidate] add",t)}catch(e){this.log.error("[candidate] error",t,e)}}))}processDecryptQueue(){return Vl(this,void 0,void 0,(function*(){const{encryptor:e}=this;if(!e)return void this.log.warn("got encrypted signaling data before the encryption key");if(!this.decryptQueue.length)return;const t=this.decryptQueue.slice();this.decryptQueue.length=0;for(const s of t){const t=yield e.decryptRawPacket(s);if(!t)continue;const i=(new TextDecoder).decode(t);try{const e=JSON.parse(i);this.log("[update] updateNewCallSignalingData",e),this.applyCallSignalingData(e)}catch(e){this.log.error("wrong signaling data",i),this.hangUp("phoneCallDiscardReasonDisconnect"),a.a.dispatchEvent("call_incompatible",this.interlocutorUserId)}}}))}onUpdatePhoneCallSignalingData(e){this.decryptQueue.push(e.data),this.processDecryptQueue()}}class Gl{constructor(e,t,s,i,n){this.appGroupCallsManager=e,this.appPeersManager=t,this.appChatsManager=s,this.appAvatarsManager=i,this.appCallsManager=n,this.onState=()=>{this.updateInstance(this.instance)};const o=this.listenerSetter=new R.a;o.add(a.a)("call_instance",({instance:e})=>{this.instance||this.updateInstance(e)}),o.add(a.a)("call_accepting",e=>{this.instance!==e&&this.updateInstance(e)}),o.add(a.a)("group_call_instance",e=>{this.updateInstance(e)}),o.add(a.a)("group_call_update",e=>{const t=this.appGroupCallsManager.groupCall;(null==t?void 0:t.id)===e.id&&this.updateInstance(t)}),o.add(a.a)("group_call_amplitude",({amplitudes:e,type:t})=>{const{weave:s}=this;if(!e.length||!s)return;let i=0;for(let t=0;t<e.length;++t){const{type:s,value:n}=e[t];i=n>i?n:i}s.setAmplitude(i)})}clearCurrentInstance(){this.instance&&(this.center.textContent="",this.currentDescription&&(this.currentDescription.detach(),this.currentDescription=void 0),this.instance=void 0,this.instanceListenerSetter.removeAll())}updateInstance(e){this.construct&&(this.construct(),this.construct=void 0);const t=this.instance!==e;t&&(this.clearCurrentInstance(),this.instance=e,this.instanceListenerSetter=new R.a,this.instanceListenerSetter.add(e)("state",this.onState),e instanceof cl.a?this.currentDescription=this.groupCallDescription:(this.currentDescription=this.callDescription,this.instanceListenerSetter.add(e)("muted",this.onState)),this.container.classList.toggle("is-call",!(e instanceof cl.a)));const s=this.instance.isMuted;let i=e instanceof cl.a?e.state:function(e,t){switch(e){case dl.CLOSING:case dl.CLOSED:return Pr.a.CLOSED;case dl.CONNECTED:return t?Pr.a.MUTED:Pr.a.UNMUTED;default:return Pr.a.CONNECTING}}(e.connectionState,s);const{weave:n}=this;n.componentDidMount();const a=i===Pr.a.CLOSED;(!document.body.classList.contains("is-calling")||t||a)&&(a&&n.setAmplitude(0),Object(is.a)(document.body,"is-calling",!a,250,a?()=>{n.componentWillUnmount(),this.clearCurrentInstance()}:void 0)),a||(n.setCurrentState(i,!0),this.setTitle(e),this.setDescription(e),this.groupCallMicrophoneIconMini.setState(!s))}setDescription(e){return this.currentDescription.update(e)}setTitle(e){if(e instanceof cl.a)return this.groupCallTitle.update(e);Object(k.a)(this.center,new wt.a({peerId:e.interlocutorUserId.toPeerId()}).element)}construct(){const{listenerSetter:e}=this,t=this.container=document.createElement("div");t.classList.add("sidebar-header","topbar-call-container");const s=document.createElement("div");s.classList.add("topbar-call-left");const i=this.groupCallMicrophoneIconMini=new pl,n=N();n.append(i.container),s.append(n);const a=Object(ws.a)(()=>{this.instance.toggleMuted()},600,!0);Object(l.b)(n,e=>{Object(c.a)(e),a()},{listenerSetter:e});const o=this.center=document.createElement("div");o.classList.add("topbar-call-center"),this.groupCallTitle=new Qr(o),this.groupCallDescription=new qr(s),this.callDescription=new hl(s);const r=document.createElement("div");r.classList.add("topbar-call-right");const d=N("endcall_filled");r.append(d),Object(l.b)(d,e=>{Object(c.a)(e);const{instance:t}=this;t&&(t instanceof cl.a?t.hangUp():t.hangUp("phoneCallDiscardReasonHangup"))},{listenerSetter:e}),Object(l.b)(t,()=>{if(this.instance instanceof cl.a){if(ht.b.getPopups(rl).length)return;new rl({appGroupCallsManager:this.appGroupCallsManager,appPeersManager:this.appPeersManager,appChatsManager:this.appChatsManager}).show()}else if(this.instance instanceof Kl){if(ht.b.getPopups(ml).find(e=>e.getCallInstance()===this.instance))return;new ml({appCallsManager:this.appCallsManager,appAvatarsManager:this.appAvatarsManager,appPeersManager:this.appPeersManager,instance:this.instance}).show()}},{listenerSetter:e}),t.append(s,o,r);const h=this.weave=new xr,p=h.render("topbar-call-weave");t.prepend(p),document.getElementById("column-center").prepend(t),h.componentDidMount()}}var Wl=s(179),ql=s(119),Ql=s(24),$l=s(123),Yl=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Xl=new class{constructor(){this.log=Object(Y.b)("CALLS"),this.tempId=0,this.calls=new Map,this.instances=new Map,this.sortedInstances=[],qa&&(a.a.addMultipleEventsListeners({updatePhoneCall:e=>Yl(this,void 0,void 0,(function*(){var t;const s=this.saveCall(e.phone_call);let i=this.instances.get(s.id);switch(s._){case"phoneCallDiscarded":i&&i.hangUp(null===(t=s.reason)||void 0===t?void 0:t._,!0);break;case"phoneCallAccepted":i&&i.confirmCall();break;case"phoneCallRequested":i||(i=this.createCallInstance({isOutgoing:!1,interlocutorUserId:s.admin_id}),i.overrideConnectionState(dl.PENDING),i.setPhoneCall(s),i.setHangUpTimeout(45e3,"phoneCallDiscardReasonMissed"));break;case"phoneCall":{if(!i||i.encryptionKey)break;const e=i.dh.g_a=s.g_a_or_b,t=i.dh,n=yield ct.a.invokeCrypto("sha256",e);if(!Object(ql.a)(t.g_a_hash,n)){this.log.error("Incorrect g_a_hash",t.g_a_hash,n);break}const{key:a,key_fingerprint:o}=yield this.computeKey(e,t.b,t.p);if(s.key_fingerprint!==o){this.log.error("Incorrect key fingerprint",s.key_fingerprint,o);break}i.encryptionKey=a,i.joinCall();break}}})),updatePhoneCallSignalingData:e=>{const t=this.instances.get(e.phone_call_id);(null==t?void 0:t.id)===e.phone_call_id&&t.onUpdatePhoneCallSignalingData(e)}}),this.audioAsset=new Wl.a(["call_busy.mp3","call_connect.mp3","call_end.mp3","call_incoming.mp3","call_outgoing.mp3","voip_failed.mp3"]))}get currentCall(){return this.sortedInstances[0]}getCallByUserId(e){for(const[t,s]of this.instances)if(s.interlocutorUserId===e)return s}computeKey(e,t,s){return Yl(this,void 0,void 0,(function*(){return ct.a.invokeCrypto("compute-dh-key",e,t,s)}))}saveCall(e){const t="phoneCallDiscarded"===e._,s=this.calls.get(e.id);return s?(Object($l.a)(s,e),t&&this.calls.delete(e.id),e=s):t||this.calls.set(e.id,e),e}getCall(e){return this.calls.get(e)}getCallInput(e){const t=this.getCall(e);return{_:"inputPhoneCall",id:t.id,access_hash:t.access_hash}}createCallInstance(e){const t=new Kl(Object.assign({appCallsManager:this,apiManager:ct.a,apiUpdatesManager:vi.a},e));return t.addEventListener("state",e=>{const s=this.currentCall;e===dl.CLOSED?(this.instances.delete(t.id),Object(V.a)(this.sortedInstances,t)):Object(Us.a)(this.sortedInstances,t,"sortIndex"),e===dl.EXCHANGING_KEYS&&(t.wasTryingToJoin=!0);const i=void 0!==t.connectedAt;e===dl.EXCHANGING_KEYS||e===dl.CONNECTING&&i?t.setHangUpTimeout(45e3,"phoneCallDiscardReasonDisconnect"):t.clearHangUpTimeout(),s!==t&&s||(e===dl.CLOSED?t.isOutgoing||t.wasTryingToJoin?t.wasTryingToJoin&&!i?this.audioAsset.playSound("voip_failed.mp3"):this.audioAsset.playSound("phoneCallDiscardReasonBusy"===t.discardReason?"call_busy.mp3":"call_end.mp3"):this.audioAsset.stopSound():e===dl.PENDING?this.audioAsset.playSound(t.isOutgoing?"call_outgoing.mp3":"call_incoming.mp3",!0):e===dl.EXCHANGING_KEYS?this.audioAsset.playSoundIfDifferent("call_connect.mp3"):e===dl.CONNECTING?t.duration&&this.audioAsset.playSound("voip_connecting.mp3",!0):this.audioAsset.stopSound())}),t.addEventListener("id",(e,s)=>{void 0!==s&&this.instances.delete(s);const i=!!this.currentCall;this.instances.set(e,t),void 0===s&&a.a.dispatchEvent("call_instance",{instance:t,hasCurrent:i})}),t}savePhonePhoneCall(e){return E.a.saveApiUsers(e.users),this.saveCall(e.phone_call)}generateDh(){return ct.a.invokeApi("messages.getDhConfig",{version:0,random_length:256}).then(e=>Yl(this,void 0,void 0,(function*(){return ct.a.invokeCrypto("generate-dh",e)})))}startCallInternal(e,t){this.log("p2pStartCallInternal",e,t);const s=n.default.getCachedFullUser(e);if(!s)return;const{video_calls_available:i}=s.pFlags,a=this.createCallInstance({isOutgoing:!0,interlocutorUserId:e});a.requestInputSource(!0,!(!t||!i),!1),a.overrideConnectionState(dl.REQUESTING),a.setPhoneCall({_:"phoneCallWaiting",access_hash:"",admin_id:Me.c,date:Object(pr.a)(!0),id:--this.tempId,participant_id:e,protocol:a.protocol,pFlags:{video:t||void 0}}),this.generateDh().then(s=>(a.dh=s,ct.a.invokeApi("phone.requestCall",{user_id:E.a.getUserInput(e),protocol:a.protocol,video:t&&i,random_id:Object(st.a)(32),g_a_hash:a.dh.g_a_hash}))).then(e=>{const t=this.savePhonePhoneCall(e);a.overrideConnectionState(dl.PENDING),a.setPhoneCall(t),a.setHangUpTimeout(45e3,"phoneCallDiscardReasonHangup")})}verifyProtocolCompatibility(e){const t={_:"phoneCallProtocol",pFlags:{udp_p2p:!0,udp_reflector:!0},min_layer:92,max_layer:92,library_versions:["4.0.0"]}.library_versions[0];return!e.library_versions.find(e=>Object(Ql.a)(t,e)>0)}discardCall(e,t,s,i){return Yl(this,void 0,void 0,(function*(){if(!this.getCall(e))return;const n=yield ct.a.invokeApi("phone.discardCall",{video:i,peer:this.getCallInput(e),duration:t,reason:{_:s},connection_id:"0"});vi.a.processUpdateMessage(n)}))}};le.a&&(le.a.appCallsManager=Xl);var Jl=Xl,Zl=s(109),ec=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const tc="chat",sc=he.a?"touchstart":"mousemove";const ic=new class{constructor(){this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.tabId=-1,this.chats=[],this.onHashChange=()=>{const e=location.hash,t=e.split("?"),s=this.parseUriParams(e,t);if(this.log("hashchange",e,t[0],s),s.tgaddr){F.a.replaceState();const{onclick:e}=X.b.wrapUrl(s.tgaddr);if(e){const t=document.createElement("a");t.href=s.tgaddr,window[e](t)}}else switch(t[0]){case"#/im":{const e=s.p;let t=void 0!==s.post?v.a.generateMessageId(+s.post):void 0;switch(e[0]){case"@":this.openUsername({userName:e,lastMsgId:t});break;default:this.setInnerPeer({peerId:t?e.toPeerId(!0):e.toPeerId(),lastMsgId:t})}}}},this.setSettings=()=>{document.documentElement.style.setProperty("--messages-text-size",a.a.settings.messagesTextSize+"px"),document.body.classList.toggle("animation-level-0",!a.a.settings.animationsEnabled),document.body.classList.toggle("animation-level-1",!1),document.body.classList.toggle("animation-level-2",a.a.settings.animationsEnabled),this.chatsSelectTabDebounced=Object(lt.a)(()=>{const e=this.chat.topbar;e.pinnedMessage&&e.pinnedMessage.setCorrectIndex(0),ct.a.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)},a.a.settings.animationsEnabled?250:0,!1,!0),oe.a.setLoop(a.a.settings.stickers.loop),I.a.checkAnimations(!1);for(const e of this.chats)e.setAutoDownloadMedia();T.c.setTimeFormat(a.a.settings.timeFormat),this.toggleChatGradientAnimation(this.chat)},this.onDocumentPaste=(e,t)=>{const s=To();if(this.canDrag()||s){if(e instanceof DragEvent){const t=e.dataTransfer.types;(t.contains?t.contains("Files"):t.indexOf("Files")>=0)&&Object(c.a)(e)}Object(pe.d)(e).then(e=>{if(e.length){if(s)return void s.addFiles(e);const i=this.chat.input;i.willAttachType=t||(g.has(e[0].type)?"media":"document"),new xo(this.chat,e,i.willAttachType)}})}},vi.a.attach(T.c.lastRequestedLangCode),Bt.a.start(),this.log=Object(Y.b)("IM",Y.a.Log|Y.a.Warn|Y.a.Debug|Y.a.Error),this.backgroundPromises={},M.b.settings.themes.forEach(e=>{if(e.background.slug){const t="assets/img/"+e.background.slug+".svg"+(ae.d?"?1":"");this.backgroundPromises[e.background.slug]=Promise.resolve(t)}}),this.selectTab(0),window.addEventListener("blur",()=>{I.a.checkAnimations(!0),this.offline=a.a.idle.isIDLE=!0,this.updateStatus(),clearInterval(this.updateStatusInterval),a.a.dispatchEvent("idle",a.a.idle.isIDLE),window.addEventListener("focus",()=>{this.offline=a.a.idle.isIDLE=!1,this.updateStatus(),this.updateStatusInterval=window.setInterval(()=>this.updateStatus(),5e4),I.a.checkAnimations(!1),a.a.dispatchEvent("idle",a.a.idle.isIDLE)},{once:!0})}),window.addEventListener(sc,()=>{this.updateStatusInterval=window.setInterval(()=>this.updateStatus(),5e4),this.updateStatus(),this.offline=a.a.idle.isIDLE=!1,a.a.dispatchEvent("idle",a.a.idle.isIDLE)},{once:!0,passive:!0}),this.chatsContainer=document.createElement("div"),this.chatsContainer.classList.add("chats-container","tabs-container"),this.chatsContainer.dataset.animation="navigation",this.emojiAnimationContainer=document.createElement("div"),this.emojiAnimationContainer.classList.add("emoji-animation-container"),this.appendEmojiAnimationContainer(b.b.activeScreen),this.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),F.a.onHashChange=this.onHashChange,this.setSettings(),a.a.addEventListener("settings_updated",this.setSettings),Object(Ds.a)(()=>{I.a.setOnlyOnePlayableGroup("lock"),I.a.checkAnimations(!0)},()=>{I.a.setOnlyOnePlayableGroup(""),I.a.checkAnimations(!1)}),ae.d&&M.c.oldVersion&&-1===Object(Ql.a)(M.c.oldVersion,"1.4.3")?this.deleteFilesIterative(e=>"image/svg+xml"===e.headers.get("Content-Type")).then(()=>{this.applyCurrentTheme()}):this.applyCurrentTheme(),b.b.addEventListener("changeScreen",(e,t)=>{document.body.classList.contains("is-left-column-shown")&&document.body.classList.contains("is-right-column-shown")&&ts.toggleSidebar(!1),this.appendEmojiAnimationContainer(t)}),b.b.addEventListener("resize",()=>{const e=this.chatsContainer.getBoundingClientRect();vr.resizeInstances(e.width,e.height).then(()=>{})}),a.a.addEventListener("history_focus",e=>{let{peerId:t,threadId:s,mid:i,startParam:n}=e;s&&(s=v.a.generateMessageId(s)),i&&(i=v.a.generateMessageId(i)),this.setInnerPeer({peerId:t,lastMsgId:i,type:s?"discussion":void 0,threadId:s,startParam:n})}),a.a.addEventListener("peer_changing",e=>{this.saveChatPosition(e)}),a.a.addEventListener("theme_change",()=>{this.applyCurrentTheme()}),a.a.addEventListener("choosing_sticker",e=>{this.setChoosingStickerTyping(!e)}),a.a.addEventListener("peer_typings",({peerId:e,typings:t})=>{var s;const n=this.chat;if(!n||n.peerId!==e||a.a.overlaysActive||b.b.activeScreen===b.a.mobile&&1!==this.tabId)return;const o=t.find(e=>"sendMessageEmojiInteraction"===e.action._);if("sendMessageEmojiInteraction"===(null===(s=null==o?void 0:o.action)||void 0===s?void 0:s._)){const t=o.action,s=n.bubbles.bubbles[v.a.generateMessageId(o.action.msg_id)];if(s&&s.classList.contains("emoji-big")&&s.classList.contains("sticker")&&Qa(s,n.bubbles.scrollable.container)){const n=s.querySelector(".media-sticker-wrapper:not(.bubble-hover-reaction-sticker):not(.reaction-sticker)");JSON.parse(t.interaction.data).a.forEach(e=>{setTimeout(()=>{Object(l.d)(n)},1e3*e.t)}),i.a.setTyping(e,{_:"sendMessageEmojiInteractionSeen",emoticon:t.emoticon})}}}),a.a.addEventListener("instance_deactivated",()=>{const e=new ht.b("popup-instance-deactivated",void 0,{overlayClosable:!0}),t=document.createElement("div");t.classList.add("instance-deactivated-container"),e.container.replaceWith(t);const s=document.createElement("div");s.classList.add("header"),s.append(Object(T.d)("Deactivated.Title"));const i=document.createElement("div");i.classList.add("subtitle"),i.append(Object(T.d)("Deactivated.Subtitle")),t.append(s,i),document.body.classList.add("deactivated"),e.addEventListener("close",()=>{document.body.classList.add("deactivated-backwards"),Ir.a.activateInstance(),setTimeout(()=>{document.body.classList.remove("deactivated","deactivated-backwards")},333)}),e.show()}),a.a.addEventListener("chat_changing",({to:e})=>{this.toggleChatGradientAnimation(e)}),a.a.addEventListener("service_notification",e=>{Mn({button:{langKey:"OK",isCancel:!0},description:X.b.wrapRichText(e.message)})}),ga.a.get("chatPositions").then(e=>{ga.a.setToCache("chatPositions",e||{})}),(qa||hr)&&(this.topbarCall=new Gl(Er.a,o.a,G.a,d.a,Jl)),qa&&(a.a.addEventListener("call_instance",({instance:e})=>{const t=new ml({appCallsManager:Jl,appAvatarsManager:d.a,appPeersManager:o.a,instance:e});e.addEventListener("acceptCallOverride",()=>this.discardCurrentCall(e.interlocutorUserId.toPeerId(),void 0,e).then(()=>(a.a.dispatchEvent("call_accepting",e),!0)).catch(()=>!1)),t.addEventListener("close",()=>{const t=Jl.currentCall;t&&t!==e&&!e.wasTryingToJoin&&e.hangUp("phoneCallDiscardReasonBusy")},{once:!0}),t.show()}),a.a.addEventListener("call_incompatible",e=>{rt({langPackKey:"VoipPeerIncompatible",langPackArguments:[new wt.a({peerId:e.toPeerId()}).element]})})),Ir.a.activateInstance();const e=()=>{Mr.default.setAuthorized(!0)};setInterval(e,ne.a),e(),this.addAnchorListener({name:"showMaskedAlert",callback:(e,t)=>{const s=t.href,i=t.cloneNode(!0);i.className="anchor-url",i.innerText=s,i.removeAttribute("onclick"),new ut("popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[i],buttons:[{langKey:"Open",callback:()=>{i.click()}}]}).show()}}),this.addAnchorListener({name:"execBotCommand",callback:({uriParams:e})=>{const{command:t,bot:s}=e;i.a.sendText(this.chat.peerId,"/"+t+(s?"@"+s:""))}}),this.addAnchorListener({name:"searchByHashtag",callback:({uriParams:e})=>{const{hashtag:t}=e;t&&this.chat.initSearch("#"+t+" ")}}),this.addAnchorListener({name:"addstickers",callback:({pathnameParams:e})=>{const t={_:$a.STICKER_SET,set:e[1]};this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",callback:({pathnameParams:e})=>{const t={_:$a.JOIN_CHAT,invite:e[1]||decodeURIComponent(e[0]).slice(1)};this.processInternalLink(t)}}),hr&&this.addAnchorListener({name:"voicechat",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink($a.VOICE_CHAT,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"im",callback:({pathnameParams:e,uriParams:t})=>ec(this,void 0,void 0,(function*(){let s;s=X.b.PHONE_NUMBER_REG_EXP.test(e[0])?{_:$a.USER_PHONE_NUMBER,phone:e[0].slice(1)}:"c"===e[0]?{_:$a.PRIVATE_POST,channel:e[1],post:e[2],thread:"thread"in t&&t.thread,comment:t.comment}:{_:$a.MESSAGE,domain:e[0],post:e[1],comment:t.comment,start:"start"in t?t.start:void 0},this.processInternalLink(s)}))}),this.addAnchorListener({name:"resolve",protocol:"tg",callback:({uriParams:e})=>{let t;e.phone?t=this.makeLink($a.USER_PHONE_NUMBER,e):"telegrampassport"===e.domain||(t=this.makeLink($a.MESSAGE,e)),this.processInternalLink(t)}}),this.addAnchorListener({name:"privatepost",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink($a.PRIVATE_POST,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"addstickers",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink($a.STICKER_SET,e);this.processInternalLink(t)}}),["joinchat","join"].forEach(e=>{this.addAnchorListener({name:e,protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink($a.JOIN_CHAT,e);this.processInternalLink(t)}})}),this.onHashChange(),this.attachKeydownListener()}get myId(){return a.a.myId}get chat(){return this.chats[this.chats.length-1]}deleteFilesIterative(e){return ce.a.cacheStorage.timeoutOperation(t=>{const s=performance.now();return t.keys().then(s=>{const i=s.map(s=>t.match(s).then(t=>e(t)));return Promise.all(i).then(e=>(e.map((e,i)=>{if(!e)return;const n=s[i];return t.delete(n)}),Promise.all(e.filter(Boolean))))}).then(()=>{this.log("deleted files",performance.now()-s)})})}toggleChatGradientAnimation(e){this.chats.forEach(t=>{t.gradientRenderer&&t.gradientRenderer.scrollAnimate(a.a.settings.animationsEnabled&&t===e)})}appendEmojiAnimationContainer(e){const t=e===b.a.mobile?this.columnEl:document.body;this.emojiAnimationContainer.parentElement!==t&&t.append(this.emojiAnimationContainer)}attachKeydownListener(){const e=new Set(["PageUp","PageDown","Meta","Control"]);document.body.addEventListener("keydown",t=>{var s;const n=t.key;if(a.a.isOverlayActive||e.has(n))return;const o=t.target,r=this.chat;if("KeyC"!==t.code||!t.ctrlKey&&!t.metaKey||"INPUT"===o.tagName){if(!t.altKey||"ArrowUp"!==n&&"ArrowDown"!==n){if("ArrowUp"===n){if(r.input.editMsgId||!r.input.isInputEmpty())return;{const e=i.a.getHistoryStorage(r.peerId,r.threadId).history.slice;if(e.isEnd(ra.a.Bottom)&&e.length){let s;for(const t of e){const e=r.getMessage(t);if((this.myId===r.peerId?e.fromId===this.myId:e.pFlags.out)&&i.a.canEditMessage(r.getMessage(t),"text")){s=t;break}}s&&(r.input.initMessageEditing(s),Object(c.a)(t))}}}else if("ArrowDown"===n)return}else{const e=i.a.dialogsStorage.getFolderDialogs(a.a.filterId,!0);let t;if(a.a.peerId){const s=e.findIndex(e=>e.peerId===a.a.peerId);if(-1!==s){t=e["ArrowUp"===n?s-1:s+1]}}else"ArrowDown"===n&&(t=e[0]);t&&this.setPeer({peerId:t.peerId})}if((null===(s=null==r?void 0:r.input)||void 0===s?void 0:s.messageInput)&&t.target!==r.input.messageInput&&"INPUT"!==o.tagName&&!o.hasAttribute("contenteditable")&&!he.a&&(!b.b.isMobile||1===this.tabId)&&!r.selection.isSelecting&&!r.input.recording){r.input.messageInput.focus(),Object(Eo.a)(r.input.messageInput);const e=new KeyboardEvent(t.type,t);r.input.messageInput.dispatchEvent(e)}}})}makeLink(e,t){return Object.assign({_:e},t)}processInternalLink(e){return ec(this,void 0,void 0,(function*(){switch(null==e?void 0:e._){case $a.MESSAGE:{const t=e.post?v.a.generateMessageId(+e.post):void 0,s=e.comment?v.a.generateMessageId(+e.comment):void 0;this.openUsername({userName:e.domain,lastMsgId:t,commentId:s,startParam:e.start});break}case $a.PRIVATE_POST:{const t=e.channel.toChatId(),s=t.toPeerId(!0);if(G.a.getChat(t).deleted)try{yield G.a.resolveChannel(t)}catch(e){throw rt({langPackKey:"LinkNotFound"}),e}const i=v.a.generateMessageId(+e.post),n=e.thread?v.a.generateMessageId(+e.thread):void 0;n?this.openThread(s,i,n):this.setInnerPeer({peerId:s,lastMsgId:i,threadId:n});break}case $a.STICKER_SET:new on({id:e.set}).show();break;case $a.JOIN_CHAT:ct.a.invokeApi("messages.checkChatInvite",{hash:e.invite}).then(t=>{t.chat&&G.a.saveApiChat(t.chat,!0),"chatInviteAlready"!==t._&&"chatInvitePeek"!==t._?new Xa(e.invite,t).show():this.setInnerPeer({peerId:t.chat.id.toPeerId(!0)})},e=>{"INVITE_HASH_EXPIRED"===e.type&&ot(Object(T.d)("InviteExpired"))});break;case $a.VOICE_CHAT:hr&&this.joinGroupCall(e.chat_id.toPeerId(!0),e.id);break;case $a.USER_PHONE_NUMBER:E.a.resolvePhone(e.phone).then(e=>{this.setInnerPeer({peerId:e.id.toPeerId(!1)})}).catch(e=>{"PHONE_NOT_OCCUPIED"===e.type&&rt({langPackKey:"Alert.UserDoesntExists"})});break;default:this.log.warn("Not supported internal link:",e)}}))}openUrl(e){const{url:t,onclick:s}=X.b.wrapUrl(e),i=document.createElement("a");i.href=t,window[s](i)}addAnchorListener(e){window[(e.protocol?e.protocol+"_":"")+e.name]=t=>{Object(c.a)(null);const s=t.href;let i,n;e.noPathnameParams||(i=new URL(t.href).pathname.split("/").slice(1)),e.noUriParams||(n=this.parseUriParams(s));const a=e.callback({pathnameParams:i,uriParams:n},t);return void 0===a&&a}}parseUriParams(e,t=e.split("?")){const s={};return t[1]?(t[1].split("&").forEach(e=>{s[e.split("=")[0]]=decodeURIComponent(e.split("=")[1])}),s):s}openUsername(e){const{userName:t,lastMsgId:s,threadId:i,commentId:n,startParam:a}=e;return E.a.resolveUsername(t).then(e=>{const t="user"===e._,o=e.id.toPeerId(!t);return i?this.openThread(o,s,i):n?this.openComment(o,s,n):this.setInnerPeer({peerId:o,lastMsgId:s,startParam:a})},e=>{"USERNAME_NOT_OCCUPIED"===e.type?rt({langPackKey:"NoUsernameFound"}):"USERNAME_INVALID"===e.type&&rt({langPackKey:"Alert.UserDoesntExists"})})}openThread(e,t,s){return i.a.wrapSingleMessage(e,s).then(()=>{const n=i.a.getMessageByPeer(e,s);return"messageEmpty"===n._?t=void 0:i.a.generateThreadServiceStartMessage(n),this.setInnerPeer({peerId:e,lastMsgId:t,threadId:s,type:"discussion"})})}openComment(e,t,s){return i.a.getDiscussionMessage(e,t).then(e=>this.openThread(e.peerId,s,e.mid))}callUser(e,t){return ec(this,void 0,void 0,(function*(){if(Jl.getCallByUserId(e))return;(yield n.default.getProfile(e)).pFlags.phone_calls_private?Mn({descriptionLangKey:"Call.PrivacyErrorMessage",descriptionLangArgs:[new wt.a({peerId:e.toPeerId()}).element],button:{langKey:"OK",isCancel:!0}}):(yield this.discardCurrentCall(e.toPeerId()),Jl.startCallInternal(e,"video"===t))}))}discardCurrentCall(e,t,s){return Er.a.groupCall&&Er.a.groupCall!==t?this.discardGroupCallConfirmation(e):Jl.currentCall&&Jl.currentCall!==s?this.discardCallConfirmation(e):Promise.resolve()}discardCallConfirmation(e){return ec(this,void 0,void 0,(function*(){const t=Jl.currentCall;t&&(yield Mn({titleLangKey:"Call.Confirm.Discard.Call.Header",descriptionLangKey:e.isUser()?"Call.Confirm.Discard.Call.ToCall.Text":"Call.Confirm.Discard.Call.ToVoice.Text",descriptionLangArgs:[new wt.a({peerId:t.interlocutorUserId.toPeerId(!1)}).element,new wt.a({peerId:e}).element],button:{langKey:"OK"}}),t.isClosing||(yield t.hangUp("phoneCallDiscardReasonDisconnect")))}))}discardGroupCallConfirmation(e){return ec(this,void 0,void 0,(function*(){const t=Er.a.groupCall;t&&(yield Mn({titleLangKey:"Call.Confirm.Discard.Voice.Header",descriptionLangKey:e.isUser()?"Call.Confirm.Discard.Voice.ToCall.Text":"Call.Confirm.Discard.Voice.ToVoice.Text",descriptionLangArgs:[new wt.a({peerId:t.chatId.toPeerId(!0)}).element,new wt.a({peerId:e}).element],button:{langKey:"OK"}}),Er.a.groupCall===t&&(yield t.hangUp()))}))}joinGroupCall(e,t){return ec(this,void 0,void 0,(function*(){const s=e.toChatId(),i=G.a.hasRights(s,"manage_call");if(t){if("groupCallDiscarded"===(yield Er.a.getGroupCallFull(t))._){if(!i)return void rt({langPackKey:"VoiceChat.Chat.Ended"});yield Mn({descriptionLangKey:"VoiceChat.Chat.StartNew",button:{langKey:"VoiceChat.Chat.StartNew.OK"}})}}yield this.discardCurrentCall(e),(()=>{ec(this,void 0,void 0,(function*(){const e=yield n.default.getChatFull(s);let t;if(e.call)t=Er.a.saveGroupCall(e.call,s);else{if(!i)return;t=yield Er.a.createGroupCall(s)}Er.a.joinGroupCall(s,t.id,!0,!1)}))})()}))}setCurrentBackground(e=!1){const t=a.a.getTheme();if(t.background.slug){const s=M.a.STATE_INIT.settings.themes.find(e=>e.name===t.name);return this.getBackground(t.background.slug).then(t=>this.setBackground(t,e),()=>(t.background=Object(ue.a)(s.background),this.setCurrentBackground(!0)))}return this.setBackground("",e)}getBackground(e){return this.backgroundPromises[e]?this.backgroundPromises[e]:this.backgroundPromises[e]=ce.a.cacheStorage.getFile("backgrounds/"+e).then(e=>URL.createObjectURL(e))}setBackground(e,t=!0){this.lastBackgroundUrl=e;const s=this.chats.map(t=>t.setBackground(e));return s[s.length-1].then(()=>{t&&a.a.dispatchEvent("background_change")})}saveChatPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.bubbles,s=e.peerId+(e.threadId?"_"+e.threadId:""),i=ga.a.getFromCache("chatPositions");if(t.scrollable.getDistanceToEnd()<=16&&t.scrollable.loadedAll.bottom||!t.getRenderedLength())delete i[s],this.log("deleted chat position");else{t.sliceViewport(!0);const e=t.scrollable.scrollTop,n={mids:Object(li.a)(t.bubbles,"desc").filter(e=>!t.skippedMids.has(e)),top:e};i[s]=n,this.log("saved chat position:",n)}ga.a.set({chatPositions:i},!0)}getChatSavedPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),s=ga.a.getFromCache("chatPositions");return s&&s[t]}applyHighlightningColor(){let e;const t=a.a.getTheme();t.background.highlightningColor?(e=t.background.highlightningColor,document.documentElement.style.setProperty("--message-highlightning-color",e)):document.documentElement.style.removeProperty("--message-highlightning-color"),!he.a&&e&&(a.a.themeColor=function(e){return Ji(e).slice(0,-2)}(e))}applyCurrentTheme(e,t,s){return this.applyHighlightningColor(),a.a.setTheme(),t&&(this.backgroundPromises[e]=Promise.resolve(t)),this.setCurrentBackground(void 0===s?!!e:s)}chatsSelectTab(e,t){if(this.prevTab!==e){if(!1===t&&this.prevTab&&Lr([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),a.a.settings.animationsEnabled&&!1!==t&&Object(Ds.b)(Object(da.a)(400),400);const s=Object(Bs.a)(this.prevTab);Object(Bs.a)(e)>s&&F.a.pushItem({type:"chat",onPop:e=>{this.setPeer({},e),Object(ti.a)()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),he.a||this.attachDragAndDropListeners(),this.markupTooltip=new yr(this),this.markupTooltip.handleSelection()}attachDragAndDropListeners(){const e=[],t=[];let s=!1;const i=(r,l)=>ec(this,void 0,void 0,(function*(){if(l===s)return;const c=r.dataTransfer.types,d=c.contains?c.contains("Files"):c.indexOf("Files")>=0,h=To();if(!d||!this.canDrag()&&!h)return void(n=0);const p=h?o:a,u=h?t:e;if(l&&!u.length){const e=yield Object(pe.d)(r,!0),t=d&&!e.length,s=e.filter(e=>g.has(e)).length;this.log("drag files",e),h?(h.appendDrops(p),(e.length||t)&&u.push(new Cr(p,{header:"Preview.Dragging.AddItems",headerArgs:[e.length],onDrop:e=>{i(e,!1),ic.log("drop",e),ic.onDocumentPaste(e,"document")}}))):((e.length||t)&&u.push(new Cr(p,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:e=>{i(e,!1),ic.log("drop",e),ic.onDocumentPaste(e,"document")}})),(s||t)&&u.push(new Cr(p,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:e=>{i(e,!1),ic.log("drop",e),ic.onDocumentPaste(e,"media")}})),this.chat.container.append(p))}Object(is.a)(p,"is-visible",l,200,()=>{l||(u.forEach(e=>{e.destroy()}),u.length=0)}),l?u.forEach(e=>{e.setPath()}):n=0,document.body.classList.toggle("is-dragging",l),s=l}));let n=0;document.body.addEventListener("dragenter",e=>{n++}),document.body.addEventListener("dragover",e=>{i(e,!0),Object(c.a)(e)}),document.body.addEventListener("dragleave",e=>{n--,0===n&&i(e,!1)});const a=document.createElement("div");a.classList.add("drops-container");const o=a.cloneNode(!0)}canDrag(){const e=this.chat;return!(!(null==e?void 0:e.peerId)||a.a.isOverlayActive||!e.canSend("send_media"))}selectTab(e,t){!1===t&&Lr([$n.sidebarEl,this.columnEl,ts.sidebarEl]),document.body.classList.toggle("is-left-column-shown",0===e);const s=this.tabId;this.log("selectTab",e,s);let i=a.a.settings.animationsEnabled?Object(Le.a)():Promise.resolve();if(-1!==s&&s!==e&&a.a.settings.animationsEnabled&&!1!==t){const e=100+(b.b.isMobile?250:200);i=Object(da.a)(e),Object(Ds.b)(i,e)}return this.tabId=e,Object(ti.a)(),b.b.isMobile&&2===s&&e<2&&document.body.classList.remove("is-right-column-shown"),-1!==s&&e>s&&(e<2||!F.a.findItemByType("im"))&&F.a.pushItem({type:"im",onPop:e=>{this.setPeer({},e)}}),a.a.dispatchEvent("im_tab_change",e),i}updateStatus(){return this.myId?(E.a.setUserStatus(this.myId,this.offline),ct.a.invokeApiSingle("account.updateStatus",{offline:this.offline})):Promise.resolve()}createNewChat(){const e=new fr(this,G.a,L.a,_a,i.a,o.a,r.a,n.default,gs.a,E.a,di.a,$e.a,ct.a,Vi.a,Ye.a,ga.a,Bt.a,fa,v.a,Er.a,jt.a);return this.chats.length&&e.setBackground(this.lastBackgroundUrl,!0),this.chats.push(e),e}spliceChats(e,t=!0,s,i){if(e>=this.chats.length)return;const n=this.chat;this.chats.length>1&&t&&a.a.dispatchEvent("peer_changing",this.chat),i||(i=this.chats.splice(e,this.chats.length-e)),a.a.dispatchEvent("chat_changing",{from:n,to:this.chat});for(let e=0;e<i.length-1;++e)F.a.removeByType("chat",!0);if(i.length>1&&i.slice(0,-1).forEach(e=>{e.container.remove()}),this.chatsSelectTab(this.chat.container,s),t){a.a.dispatchEvent("peer_changed",this.chat.peerId);const e=ts.getTab(mr);e&&e.close();ts.sharedMediaTab.setPeer(this.chat.peerId,this.chat.threadId)&&(ts.sharedMediaTab.loadSidebarMedia(!0),ts.sharedMediaTab.fillProfileElements())}i.forEach(e=>{e.beforeDestroy()}),setTimeout(()=>{i.forEach(e=>{e.destroy()})},350)}setPeer(e={},t){var s;this.init&&(this.init(),this.init=null),null!==(s=e.peerId)&&void 0!==s||(e.peerId=Me.c);const{peerId:i,lastMsgId:n}=e,a=this.chat,o=this.chats.indexOf(a);if(i){if(o>0&&a.peerId&&a.peerId!==i){const t=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===i)return void this.spliceChats(0,!0,!0,t);{const s=this.setPeer(e);return this.spliceChats(0,!1,!1,t),s}}}else{if(o>0)return void this.spliceChats(o,void 0,t);if(b.b.activeScreen===b.a.medium)return void this.selectTab(+!this.tabId,t)}if(i===a.peerId&&b.b.activeScreen<=b.a.medium&&document.body.classList.contains("is-left-column-shown"))return this.selectTab(1,t),!1;if(i||b.b.activeScreen!==b.a.mobile){const s=a.setPeer(i,n,e.startParam),o=(null==s?void 0:s.cached)?s.promise:Promise.resolve();i&&Promise.all([o,a.setBackgroundPromise]).then(()=>{setTimeout(()=>{setTimeout(()=>{this.chatsSelectTab(this.chat.container)},0),this.selectTab(1,t)},0)})}return i?void 0:(this.selectTab(0,t),!1)}setInnerPeer(e){var t;const{peerId:s}=e;if(s===Me.c||!s)return;const i=null!==(t=e.type)&&void 0!==t?t:e.type="chat",n=this.chats.findIndex(e=>e.peerId===s&&e.type===i);if(-1!==n)return this.spliceChats(n+1),this.setPeer(e);const o=this.chat;let r=o;return o.inited&&(r=this.createNewChat()),i&&(r.setType(i),e.threadId&&(r.threadId=e.threadId)),a.a.dispatchEvent("chat_changing",{from:o,to:r}),this.setPeer(e)}openScheduled(e){this.setInnerPeer({peerId:e,type:"scheduled"})}getTypingElement(e){const t=document.createElement("span");let s="peer-typing";switch(t.classList.add(s),t.dataset.action=e._,e._){case"sendMessageTypingAction":s+="-text";for(let e=0;e<3;++e){const e=document.createElement("span");e.className=s+"-dot",t.append(e)}break;case"sendMessageUploadAudioAction":case"sendMessageUploadDocumentAction":case"sendMessageUploadRoundAction":case"sendMessageUploadVideoAction":case"sendMessageUploadPhotoAction":s+="-upload";break;case"sendMessageRecordAudioAction":case"sendMessageRecordRoundAction":case"sendMessageRecordVideoAction":s+="-record";break;case"sendMessageEmojiInteractionSeen":case"sendMessageChooseStickerAction":s+="-choosing-sticker";for(let e=0;e<2;++e){const e=document.createElement("div");e.className=s+"-eye",t.append(e)}}return t.classList.add(s),t}getPeerTyping(e,t){if(!E.a.isBot(e)){const s=n.default.getPeerTypings(e);if(!s||!s.length)return;const i=s[0],a={private:{sendMessageTypingAction:"Peer.Activity.User.TypingText",sendMessageUploadAudioAction:"Peer.Activity.User.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.User.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.User.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.User.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.User.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.User.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.User.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.User.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.User.PlayingGame",sendMessageChooseStickerAction:"Peer.Activity.User.ChoosingSticker",sendMessageEmojiInteractionSeen:"Peer.Activity.User.EnjoyingAnimations"},chat:{sendMessageTypingAction:"Peer.Activity.Chat.TypingText",sendMessageUploadAudioAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.Chat.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.Chat.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.Chat.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.Chat.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.Chat.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.Chat.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.Chat.PlayingGame",sendMessageChooseStickerAction:"Peer.Activity.Chat.ChoosingSticker",sendMessageEmojiInteractionSeen:"Peer.Activity.Chat.EnjoyingAnimations"},multi:{sendMessageTypingAction:"Peer.Activity.Chat.Multi.TypingText1",sendMessageUploadAudioAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadDocumentAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadPhotoAction:"Peer.Activity.Chat.Multi.SendingPhoto1",sendMessageUploadVideoAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageUploadRoundAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageRecordVideoAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageRecordAudioAction:"Peer.Activity.Chat.Multi.RecordingAudio1",sendMessageRecordRoundAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageGamePlayAction:"Peer.Activity.Chat.Multi.PlayingGame1",sendMessageChooseStickerAction:"Peer.Activity.Chat.Multi.ChoosingSticker1"}},o=e.isUser()?a.private:s.length>1?a.multi:a.chat;let r=i.action;if(s.length>1){const e={};s.forEach(t=>{const s=t.action._;void 0===e[s]&&(e[s]=0),++e[s]}),Object.keys(e).length>1&&(r={_:"sendMessageTypingAction"})}const l=o[r._];if(!l)return;t||(t=document.createElement("span")).classList.add("online","peer-typing-container"),t.classList.toggle("peer-typing-flex","sendMessageChooseStickerAction"===r._||"sendMessageEmojiInteractionSeen"===r._);let c,d=t.firstElementChild;if(d?d.dataset.action!==r._&&d.replaceWith(this.getTypingElement(r)):(d=this.getTypingElement(r),t.prepend(d)),e.isAnyChat()&&(c=[new wt.a({peerId:i.userId.toPeerId(!1),onlyFirstName:!0}).element,s.length-1]),"sendMessageEmojiInteractionSeen"===r._){c?c.pop():c=[];const e=Object(Zl.a)(X.b.wrapEmojiText(r.emoticon));c.push(e)}const h=Object(T.d)(l,c);return h.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(h):t.append(h),t}}getPeerStatus(e,t){var s;return ec(this,void 0,void 0,(function*(){let i;if(e){if(e.isAnyChat()){let t=this.getPeerTyping(e);if(t)return t;const s=e.toChatId(),a=yield n.default.getChatFull(s);this.chat.log("chatInfo res:",a);const o=a.participants_count||a.participants&&a.participants.participants&&a.participants.participants.length||1;if(i=n.default.getChatMembersString(s),o<2)return i;const r=yield n.default.getOnlines(s);if(r>1){const e=document.createElement("span");e.append(...Object(T.f)([i,Object(T.d)("OnlineCount",[Object(Ya.a)(r)])],!1)),i=e}return i}{const n=E.a.getUser(e);if(a.a.myId===e&&!t)return;if(n){if(i=E.a.getUserStatusString(n.id),!E.a.isBot(e)){let t=this.getPeerTyping(e);if(t||"userStatusOnline"!==(null===(s=n.status)||void 0===s?void 0:s._)||(t=document.createElement("span"),t.classList.add("online"),t.append(i)),t)return t}return i}}}}))}setPeerStatus(e,t,s,i,n,a){s&&(t.innerHTML=i?"":"");const o=t.querySelector(".peer-typing-container");o&&this.getPeerTyping(e,o)||this.getPeerStatus(e,a).then(e=>{n()&&Object(k.a)(t,e||(i?"":""))})}setChoosingStickerTyping(e){i.a.setTyping(this.chat.peerId,{_:e?"sendMessageCancelAction":"sendMessageChooseStickerAction"})}};le.a&&(le.a.appImManager=ic);var nc=ic;class ac extends Hr{constructor({video:e,play:t=!1,streamable:s=!1,duration:i,onPlaybackRackMenuToggle:n,onPip:a,onPipClose:o}){if(super(),this.video=e,this.wrapper=document.createElement("div"),this.wrapper.classList.add("ckin__player"),this.onPlaybackRackMenuToggle=n,this.onPip=a,this.onPipClose=o,this.listenerSetter=new R.a,this.setup({element:this.wrapper,listenerSetter:this.listenerSetter,canHideControls:()=>!(this.video.paused||this.playbackRateButton&&this.playbackRateButton.classList.contains("menu-open")),showOnLeaveToClassName:"media-viewer-caption",ignoreClickClassName:"ckin__controls"}),e.parentNode.insertBefore(this.wrapper,e),this.wrapper.appendChild(e),this.skin="default",this.stylePlayer(i),this.setBtnMenuToggle(),"default"===this.skin){const t=this.wrapper.querySelector(".default__controls.ckin__controls");this.progress=new Oe(e,s),t.prepend(this.progress.container)}if(t){e.play().catch(t=>{"NotAllowedError"===t.name&&(e.muted=!0,e.autoplay=!0,e.play())}).finally(()=>{this.wrapper.classList.toggle("is-playing",!this.video.paused)})}}stylePlayer(e){const{wrapper:t,video:s,skin:i,listenerSetter:n}=this;t.classList.add(i);const o=this.buildControls();let r;if(t.insertAdjacentHTML("beforeend",o),"default"===i){this.playbackRateButton=this.wrapper.querySelector(".playback-rate"),this.pipButton=this.wrapper.querySelector(".pip");const e=t.querySelectorAll(".toggle"),i=t.querySelector(".fullscreen"),o=t.querySelector("#time-elapsed");r=t.querySelector("#time-duration"),r.innerHTML=Te(0|s.duration);const l=new ir(n),d=t.querySelector(".left-controls");if(l.btn.classList.remove("btn-icon"),d.insertBefore(l.btn,o.parentElement),Array.from(e).forEach(e=>{n.add(e)("click",()=>{this.togglePlay()})}),this.pipButton){n.add(this.pipButton)("click",()=>{this.video.requestPictureInPicture()});const e=e=>{this.wrapper.style.visibility=e?"hidden":"",this.onPip&&this.onPip(e)},t=20,i=Object(lt.a)(e,t,!1,!0);n.add(s)("enterpictureinpicture",()=>{i(!0),n.add(s)("leavepictureinpicture",()=>{const e=n.add(s)("pause",()=>{clearTimeout(i),this.onPipClose&&this.onPipClose()},{once:!0}),i=setTimeout(()=>{n.remove(e)},t)},{once:!0})}),n.add(s)("leavepictureinpicture",()=>{i(!1)})}he.a||(n.add(s)("click",()=>{this.togglePlay()}),n.add(document)("keydown",e=>{if(a.a.overlaysActive>1||document.pictureInPictureElement===s)return;const{key:i,code:n}=e;let o=!0;if("KeyF"===n)this.toggleFullScreen();else if("KeyM"===n)fe.muted=!fe.muted;else if("Space"===n)this.togglePlay();else if(!e.altKey||"Equal"!==n&&"Minus"!==n)!t.classList.contains("ckin__fullscreen")||"ArrowLeft"!==i&&"ArrowRight"!==i?o=!1:"ArrowLeft"===i?fe.seekBackward({action:"seekbackward"}):fe.seekForward({action:"seekforward"});else{const e="Equal"===n?1:-1,t=fe.playbackRate,s=ac.PLAYBACK_RATES.indexOf(t)+e;s>=0&&s<ac.PLAYBACK_RATES.length&&(fe.playbackRate=ac.PLAYBACK_RATES[s])}return o?(Object(c.a)(e),!1):void 0})),n.add(s)("dblclick",()=>{he.a||this.toggleFullScreen()}),n.add(i)("click",()=>{this.toggleFullScreen()}),Object(Rr.a)(t,this.onFullScreen.bind(this,i),n),n.add(s)("timeupdate",()=>{o.innerHTML=Te(0|s.currentTime)}),n.add(s)("play",()=>{t.classList.add("played"),he.a||n.add(s)("play",()=>{this.hideControls(!0)})},{once:!0}),n.add(s)("pause",()=>{this.showControls(!1)}),n.add(a.a)("media_playback_params",()=>{this.setPlaybackRateIcon()})}n.add(s)("play",()=>{t.classList.add("is-playing")}),n.add(s)("pause",()=>{t.classList.remove("is-playing")}),s.duration||e?r.innerHTML=Te(Math.round(s.duration||e)):Object(pe.e)(s).then(()=>{r.innerHTML=Te(Math.round(s.duration))})}togglePlay(){this.video[this.video.paused?"play":"pause"]()}buildControls(){const e=this.skin;if("default"===e)return`\n <button class="${e}__button--big toggle tgico" title="Toggle Play"></button>\n <div class="${e}__gradient-bottom ckin__controls"></div>\n <div class="${e}__controls ckin__controls">\n <div class="bottom-controls">\n <div class="left-controls">\n <button class="btn-icon ${e}__button toggle tgico" title="Toggle Video"></button>\n <div class="time">\n <time id="time-elapsed">0:00</time>\n <span> / </span>\n <time id="time-duration">0:00</time>\n </div>\n </div>\n <div class="right-controls">\n <button class="btn-icon ${e}__button btn-menu-toggle playback-rate night" title="Playback Rate"></button>\n ${!ae.e&&document.pictureInPictureEnabled?`<button class="btn-icon ${e}__button pip tgico-pip" title="Picture-in-Picture"></button>`:""}\n <button class="btn-icon ${e}__button fullscreen tgico-fullscreen" title="Full Screen"></button>\n </div>\n </div>\n </div>`}setBtnMenuToggle(){const e=ac.PLAYBACK_RATES.map((e,t)=>({regularText:e+"x",onClick:()=>{fe.playbackRate=e}})),t=$s(e);t.classList.add("top-left"),gi(this.playbackRateButton,this.onPlaybackRackMenuToggle?()=>{this.onPlaybackRackMenuToggle(!0)}:void 0,void 0,this.onPlaybackRackMenuToggle?()=>{this.onPlaybackRackMenuToggle(!1)}:void 0),this.playbackRateButton.append(t),this.setPlaybackRateIcon()}setPlaybackRateIcon(){const e=this.playbackRateButton;ac.PLAYBACK_RATES_ICONS.forEach(t=>{t="tgico-"+t,e.classList.remove(t)});let t=ac.PLAYBACK_RATES.indexOf(fe.playbackRate);-1===t&&(t=ac.PLAYBACK_RATES.indexOf(1)),e.classList.add("tgico-"+ac.PLAYBACK_RATES_ICONS[t])}toggleFullScreen(){const e=this.wrapper;if(ae.c){const e=this.video;return e.webkitEnterFullscreen(),void e.enterFullscreen()}Object(Rr.d)()?Object(Rr.b)():Object(Rr.e)(e)}onFullScreen(e){const t=Object(Rr.d)();this.wrapper.classList.toggle("ckin__fullscreen",t),t?(e.classList.remove("tgico-fullscreen"),e.classList.add("tgico-smallscreen"),e.setAttribute("title","Exit Full Screen")):(e.classList.remove("tgico-smallscreen"),e.classList.add("tgico-fullscreen"),e.setAttribute("title","Full Screen"))}cleanup(){super.cleanup(),this.listenerSetter.removeAll(),this.progress.removeListeners(),this.onPlaybackRackMenuToggle=this.onPip=void 0}}ac.PLAYBACK_RATES=[.5,1,1.5,2],ac.PLAYBACK_RATES_ICONS=["playback_05","playback_1x","playback_15","playback_2x"];var oc=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class rc extends D.a{constructor(e,t){super(!1),this.listLoader=e,this.author={},this.content={},this.buttons={},this.tempId=0,this.preloader=null,this.preloaderStreamable=null,this.isFirstOpen=!0,this.pageEl=document.getElementById("page-chats"),this.zoomElements={},this.zoomSwipeStartX=0,this.zoomSwipeStartY=0,this.zoomSwipeX=0,this.zoomSwipeY=0,this.setZoomValue=(e=this.zoomElements.rangeSelector.value)=>{1===e&&(this.zoomSwipeX=0,this.zoomSwipeY=0),this.moversContainer.style.transform=`matrix(${e}, 0, 0, ${e}, ${this.zoomSwipeX}, ${this.zoomSwipeY})`,this.zoomElements.btnOut.classList.toggle("inactive",.5===e),this.zoomElements.btnIn.classList.toggle("inactive",4===e),this.toggleZoom(1!==e)},this.onClick=e=>{if(this.setMoverAnimationPromise)return;const t=e.target;if("A"===t.tagName)return;if(Object(c.a)(e),he.a)return this.highlightSwitchersTimeout?clearTimeout(this.highlightSwitchersTimeout):this.wholeDiv.classList.add("highlight-switchers"),void(this.highlightSwitchersTimeout=window.setTimeout(()=>{this.wholeDiv.classList.remove("highlight-switchers"),this.highlightSwitchersTimeout=0},3e3));const s=this.isZooming();let i=null;const n=["ckin__player","media-viewer-buttons","media-viewer-author","media-viewer-caption","zoom-container"];s&&n.push("media-viewer-movers"),n.find(e=>{try{if(i=Object(Ce.a)(t,e),i)return!0}catch(e){return!1}}),i&&(s||"IMG"!==t.tagName&&"image"!==t.tagName)||this.close()},this.onKeyDown=e=>{if(a.a.overlaysActive>1)return;const t=e.key;let s=!0;"ArrowRight"===t?this.buttons.next.click():"ArrowLeft"===t?this.buttons.prev.click():"-"===t||"="===t?this.ctrlKeyDown&&this.changeZoom("="===t):s=!1,(e.ctrlKey||e.metaKey)&&(this.ctrlKeyDown=!0),s&&Object(c.a)(e)},this.onKeyUp=e=>{a.a.overlaysActive>1||e.ctrlKey||e.metaKey||(this.ctrlKeyDown=!1,this.isZooming()&&this.setZoomValue())},this.onWheel=e=>{if(!(a.a.overlaysActive>1||Object(Ce.a)(e.target,"media-viewer-caption")&&!this.ctrlKeyDown)&&(Object(c.a)(e),this.ctrlKeyDown)){const t=e.deltaY<0;this.changeZoom(!!t)}},this.log=Object(Y.b)("AMV"),this.preloader=new ye.a,this.preloaderStreamable=new ye.a({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new Z.a,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add("media-viewer-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays");const s=document.createElement("div");s.classList.add("media-viewer");const i=this.topbar=document.createElement("div");i.classList.add("media-viewer-topbar","media-viewer-appear");const n=document.createElement("div");n.classList.add("media-viewer-topbar-left"),this.buttons["mobile-close"]=N("close",{onlyMobile:!0}),this.author.container=document.createElement("div"),this.author.container.classList.add("media-viewer-author","no-select");const o=document.createElement("div");this.author.avatarEl=new fc,this.author.avatarEl.classList.add("media-viewer-userpic","avatar-44"),this.author.nameEl=document.createElement("div"),this.author.nameEl.classList.add("media-viewer-name"),this.author.date=document.createElement("div"),this.author.date.classList.add("media-viewer-date"),o.append(this.author.nameEl,this.author.date),this.author.container.append(this.author.avatarEl,o);const r=document.createElement("div");r.classList.add("media-viewer-buttons"),t.concat(["download","zoom","close"]).forEach(e=>{const t=N(e,{noRipple:!0});this.buttons[e]=t,r.append(t)}),this.buttons.zoom.classList.add("zoom-in"),this.zoomElements.container=document.createElement("div"),this.zoomElements.container.classList.add("zoom-container"),this.zoomElements.btnOut=N("zoomout",{noRipple:!0}),Object(l.b)(this.zoomElements.btnOut,()=>this.changeZoom(!1)),this.zoomElements.btnIn=N("zoomin",{noRipple:!0}),Object(l.b)(this.zoomElements.btnIn,()=>this.changeZoom(!0)),this.zoomElements.rangeSelector=new Ae({step:.5,min:.5,max:4,withTransition:!0},1),this.zoomElements.rangeSelector.setListeners(),this.zoomElements.rangeSelector.setHandlers({onScrub:this.setZoomValue,onMouseUp:()=>this.setZoomValue()}),this.zoomElements.container.append(this.zoomElements.btnOut,this.zoomElements.rangeSelector.container,this.zoomElements.btnIn),this.wholeDiv.append(this.zoomElements.container),this.content.main=document.createElement("div"),this.content.main.classList.add("media-viewer-content"),this.content.container=document.createElement("div"),this.content.container.classList.add("media-viewer-container"),this.content.media=document.createElement("div"),this.content.media.classList.add("media-viewer-media"),this.content.container.append(this.content.media),this.content.main.append(this.content.container),s.append(this.content.main),this.overlaysDiv.append(s),n.append(this.buttons["mobile-close"],this.author.container),i.append(n,r),this.buttons.prev=document.createElement("div"),this.buttons.prev.className="media-viewer-switcher media-viewer-switcher-left",this.buttons.prev.innerHTML='<span class="tgico-down media-viewer-prev-button"></span>',this.buttons.next=document.createElement("div"),this.buttons.next.className="media-viewer-switcher media-viewer-switcher-right",this.buttons.next.innerHTML='<span class="tgico-down media-viewer-next-button"></span>',this.moversContainer=document.createElement("div"),this.moversContainer.classList.add("media-viewer-movers"),this.wholeDiv.append(this.overlaysDiv,this.buttons.prev,this.buttons.next,this.topbar,this.moversContainer),this.listLoader.onLoadedMore=()=>{this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length)},this.setNewMover()}get target(){return this.listLoader.current}set target(e){this.listLoader.current=e}setListeners(){if(Object(l.b)(this.buttons.download,this.onDownloadClick),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach(e=>{Object(l.b)(e,this.close.bind(this))}),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach(([e,t])=>{t.addEventListener("click",t=>{Object(c.a)(t),this.setMoverPromise||this.listLoader.go(e)})}),Object(l.b)(this.buttons.zoom,()=>{this.isZooming()?this.toggleZoom(!1):this.changeZoom(!0)}),this.wholeDiv.addEventListener("click",this.onClick),this.listLoader.onJump=(e,t)=>{t?this.onNextClick(e):this.onPrevClick(e)},he.a){new Qt({element:this.wholeDiv,onSwipe:(e,t)=>{if(Object(Rr.d)())return;if(Math.abs(e)/St.a.width>.2||e>125)return e<0?this.buttons.prev.click():this.buttons.next.click(),!0;return(Math.abs(t)/St.a.height>.2||t>125)&&(this.close(),!0)},verifyTouchTarget:e=>"INPUT"!==e.target.tagName&&!Object(Ce.a)(e.target,"media-viewer-caption")})}}toggleZoom(e){const t=this.isZooming();if((this.zoomElements.rangeSelector.mousedown||this.ctrlKeyDown)&&(e=!0),t===e)return;void 0===e&&(e=!t),this.buttons.zoom.classList.toggle("zoom-in",!e),this.zoomElements.container.classList.toggle("is-visible",e);const s=e?this.zoomElements.rangeSelector.value:1;if(this.setZoomValue(s),this.zoomElements.rangeSelector.setProgress(s),this.videoPlayer&&this.videoPlayer.lockControls(!e&&void 0),e){if(this.zoomSwipeHandler)this.zoomSwipeHandler.setListeners();else{let e,t;const s=-1;this.zoomSwipeHandler=new Qt({element:this.moversContainer,onFirstSwipe:()=>{e=t=0,this.moversContainer.classList.add("no-transition")},onSwipe:(i,n)=>{[i,n]=[i*s,n*s],this.zoomSwipeX+=i-e,this.zoomSwipeY+=n-t,[e,t]=[i,n],this.setZoomValue()},onReset:()=>{this.moversContainer.classList.remove("no-transition")},cursor:"move"})}this.zoomElements.rangeSelector.setProgress(s)}else e||this.zoomSwipeHandler.removeListeners()}changeZoom(e){this.zoomElements.rangeSelector.addProgress(.5*(e?1:-1)),this.setZoomValue()}isZooming(){return this.zoomElements.container.classList.contains("is-visible")}setBtnMenuToggle(e){const t=bi({onlyMobile:!0},"bottom-left",e);this.topbar.append(t)}close(e){var t;if(e&&Object(c.a)(e),this.setMoverAnimationPromise)return Promise.reject();this.navigationItem&&F.a.removeItem(this.navigationItem),this.lazyLoadQueue.clear();const s=this.setMoverToTarget(null===(t=this.target)||void 0===t?void 0:t.element,!0).then(({onAnimationEnd:e})=>e);return this.listLoader.reset(),this.listLoader.cleanup&&this.listLoader.cleanup(),this.setMoverPromise=null,this.tempId=-1,window.appMediaViewer===this&&(window.appMediaViewer=void 0),this.removeGlobalListeners(),this.zoomSwipeHandler=void 0,s.finally(()=>{this.wholeDiv.remove(),this.toggleOverlay(!1)}),s}toggleOverlay(e){a.a.isOverlayActive=e,I.a.checkAnimations(e)}toggleGlobalListeners(e){e?this.setGlobalListeners():this.removeGlobalListeners()}removeGlobalListeners(){this.zoomSwipeHandler&&this.zoomSwipeHandler.removeListeners(),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),window.removeEventListener("wheel",this.onWheel,{capture:!0})}setGlobalListeners(){this.isZooming()&&this.zoomSwipeHandler.setListeners(),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),he.a||window.addEventListener("wheel",this.onWheel,{passive:!1,capture:!0})}setMoverToTarget(e,t=!1,s=0){return oc(this,void 0,void 0,(function*(){this.dispatchEvent("setMoverBefore");const i=this.content.mover;t||(i.innerHTML="");const n=this.isZooming()&&t?this.zoomElements.rangeSelector.value:1;this.removeCenterFromMover(i);const o=0!==s,r=a.a.settings.animationsEnabled?o?350:200:0;let l,c;e&&(e instanceof fc||e.classList.contains("grid-item")?(l=e,c=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=Object(Ce.a)(e,"attachment"),c=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=Object(Ce.a)(e,"profile-avatars-container"),c=l.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==c.left&&(e=l=c=void 0))),e||(e=this.content.media),c||(l=e.parentElement,c=e.getBoundingClientRect());let d=!1;if(e!==this.content.media&&!e.classList.contains("profile-avatars-avatar")){const s=Qa(l,Object(Ce.a)(l,"scrollable"),!0);!t||s&&2!==s.overflow.vertical&&2!==s.overflow.horizontal?!s||1!==s.overflow.vertical&&1!==s.overflow.horizontal||(d=!0):(l=(e=this.content.media).parentElement,c=e.getBoundingClientRect())}const h=this.content.media.getBoundingClientRect();let p,u,g,m="";if(o?(p=1===s?St.a.width:-h.width,u=h.top):(p=c.left,u=c.top),m+=`translate3d(${p}px,${u}px,0) `,e instanceof HTMLImageElement||e instanceof HTMLVideoElement||"DIV"===e.tagName){if(i.firstElementChild&&i.firstElementChild.classList.contains("media-viewer-aspecter")){g=i.firstElementChild;const e=g.querySelector(".ckin__player");if(e){const t=e.firstElementChild;g.append(t),e.remove()}g.style.cssText||(i.classList.remove("active"),this.setFullAspect(g,h,c),i.offsetLeft,i.classList.add("active"))}else g=document.createElement("div"),g.classList.add("media-viewer-aspecter"),i.prepend(g);g.style.cssText=`width: ${c.width}px; height: ${c.height}px; transform: scale3d(${h.width/c.width}, ${h.height/c.height}, 1);`}i.style.width=h.width+"px",i.style.height=h.height+"px";const b=c.width/h.width,v=c.height/h.height;o||(m+=`scale3d(${b},${v},1) `);let f=window.getComputedStyle(l).getPropertyValue("border-radius");const y=function(e){let t=e.split(" ");if(4!==t.length){t[0]||(t[0]="0px");for(let e=t.length;e<4;++e)t[e]=t[e%2]||t[0]||"0px"}return t}(f);if(f=y.map(e=>parseInt(e)/b+"px").join(" "),o||(i.style.borderRadius=f),t&&1!==n){const e=St.a.width/2-c.width/2,t=St.a.height/2-c.height/2,s=c.left-e,i=c.top-t;this.moversContainer.style.transform=`matrix(${b}, 0, 0, ${v}, ${s}, ${i})`}else i.style.transform=m;let w;d&&(i.style.opacity="0");const S=e.classList.contains("is-out"),C=this.setMoverAnimationPromise=Object(ie.a)(),L={onAnimationEnd:C},I=setTimeout(()=>{C.isFulfilled||C.isRejected||C.resolve()},1e3);if(C.finally(()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===C&&(this.setMoverAnimationPromise=null),clearTimeout(I)}),t)return e instanceof SVGSVGElement&&(w=i.querySelector("path"),w&&this.sizeTailPath(w,h,b,r,!1,S,f)),e.classList.contains("media-viewer-media")&&i.classList.add("hiding"),this.toggleWholeActive(!1),setTimeout(()=>{i.style.borderRadius=f,i.firstElementChild&&(i.firstElementChild.style.borderRadius=f)},r/2),setTimeout(()=>{i.innerHTML="",i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",C.resolve()},r),i.classList.remove("opening"),L;{let t,s;if(e instanceof HTMLVideoElement){const t=Array.from(e.parentElement.querySelectorAll("img"));t.length&&(e=t.pop())}if("DIV"===e.tagName||"AVATAR-ELEMENT"===e.tagName){const n=Array.from(e.querySelectorAll("img")).pop();n&&(t=new Image,s=n.src,i.append(t))}else if(e instanceof HTMLImageElement)t=new Image,s=e.src;else if(e instanceof HTMLVideoElement)t=Cs(),t.src=e.src;else if(e instanceof SVGSVGElement){const t=e.dataset.clipId,s=t+"-mv",{width:n,height:a}=h,o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttributeNS(null,"width",""+n),o.setAttributeNS(null,"height",""+a),o.setAttributeNS(null,"viewBox",`0 0 ${n} ${a}`),o.setAttributeNS(null,"preserveAspectRatio","xMidYMid meet"),o.insertAdjacentHTML("beforeend",e.firstElementChild.outerHTML.replace(t,s)),o.insertAdjacentHTML("beforeend",e.lastElementChild.outerHTML.replace(t,s));const r=o.firstElementChild,l=r.firstElementChild.firstElementChild;if(l instanceof SVGUseElement){let e,t=l.getAttributeNS(null,"transform");t=t.replace(/translate\((.+?), (.+?)\) scale\((.+?), (.+?)\)/,(e,t,s,i,o)=>`translate(${t=2!==(t=+t)?n-2/b:2/b}, ${a}) scale(${+i/b}, ${+o/v})`),l.setAttributeNS(null,"transform",t),w=r.firstElementChild.lastElementChild;const s=f.split(" ").map(e=>parseInt(e));e=S?Sr(0,0,n-9/b,a,...s):Sr(9/b,0,n-9/b,a,...s),w.setAttributeNS(null,"d",e)}const c=o.lastElementChild;c.setAttributeNS(null,"width",""+h.width),c.setAttributeNS(null,"height",""+h.height),i.prepend(o)}g&&(g.style.borderRadius=f,t&&g.append(t)),t=i.querySelector("video, img"),t instanceof HTMLImageElement&&(t.classList.add("thumbnail"),g||(t.style.width=h.width+"px",t.style.height=h.height+"px"),s&&(yield Object(ps.b)(t,s))),i.style.display="",Object(Le.b)(()=>{i.classList.add(o?"moving":"active")})}return i.classList.add("opening"),yield Object(Le.a)(),i.style.transform=`translate3d(${h.left}px,${h.top}px,0) scale3d(1,1,1)`,d&&(i.style.opacity=""),g&&this.setFullAspect(g,h,c),setTimeout(()=>{i.style.borderRadius="",i.firstElementChild&&(i.firstElementChild.style.borderRadius="")},0),i.dataset.timeout=""+setTimeout(()=>{i.classList.remove("moving","opening"),g&&(i.querySelector("video"),i.classList.remove("active"),g.style.cssText="",i.offsetLeft),i.classList.add("center","no-transition"),i.classList.add("active"),delete i.dataset.timeout,C.resolve()},r),w&&this.sizeTailPath(w,h,b,r,!0,S,f),L}))}toggleWholeActive(e){e?this.wholeDiv.classList.add("active"):(this.wholeDiv.classList.add("backwards"),setTimeout(()=>{this.wholeDiv.classList.remove("active")},0))}setFullAspect(e,t,s){const i=t.width/t.height;let{width:n,height:a}=s;i>0?n=a*i:a=n*i,e.style.cssText=`width: ${n}px; height: ${a}px; transform: scale3d(${t.width/n}, ${t.height/a}, 1);`}sizeTailPath(e,t,s,i,n,a,o){const r=Date.now(),{width:l,height:c}=t;i/=2;const d=o.split(" ").map(e=>parseInt(e)),h=()=>{const t=Date.now()-r;let o=i?t/i:1;o>1&&(o=1),n&&(o=1-o);const p=d.map(e=>e*o);let u;u=a?Sr(0,0,l-9/s*o,c,...p):Sr(9/s*o,0,l,c,...p),e.setAttributeNS(null,"d",u),t<i&&Object(Le.b)(h)};h()}removeCenterFromMover(e){if(e.classList.contains("center")){const t=this.content.media.getBoundingClientRect();e.style.transform=`translate3d(${t.left}px,${t.top}px,0)`,e.classList.remove("center"),e.offsetLeft,e.classList.remove("no-transition")}}moveTheMover(e,t=!0){const s=St.a.width;this.removeCenterFromMover(e),e.classList.add("moving"),e.dataset.timeout&&clearTimeout(+e.dataset.timeout);const i=e.getBoundingClientRect(),n=e.style.transform.replace(/translate3d\((.+?),/,(e,n)=>{const a=t?-i.width:s;return e.replace(n,a+"px")});e.style.transform=n,setTimeout(()=>{e.remove()},350)}setNewMover(){const e=document.createElement("div");if(e.classList.add("media-viewer-mover"),e.style.display="none",this.content.mover){this.content.mover.parentElement.append(e)}else this.moversContainer.append(e);return this.content.mover=e}updateMediaSource(e,t,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);if(i&&!Object(Ce.a)(e,"document")){if(Object(Ce.a)(e,"attachment")){const t=e.parentElement.parentElement.querySelector(".preloader-container");if(t){if("video"===s)return void(t.classList.contains("manual")&&t.click());t.remove()}}Object(ps.a)(i,t),i.classList.contains("thumbnail")&&i.parentElement.classList.contains("media-container-aspecter")&&i.classList.remove("thumbnail")}}setAuthorInfo(e,t){Object(k.a)(this.author.date,Object(ne.d)(t));const s=e.isPeerId();let i;s?i=new wt.a({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1}).element:(i=document.createElement("span"),i.append(X.b.wrapEmojiText(e)),i.classList.add("peer-title")),Object(k.a)(this.author.nameEl,i);let n=this.author.avatarEl;this.author.avatarEl=n.cloneNode(),this.author.avatarEl.updateWithOptions({peerId:e||Me.c,peerTitle:s?void 0:""+e}),n.parentElement.replaceChild(this.author.avatarEl,n)}_openMedia(e,t,s,i,n,a=!1,o=[],l=[],d){return oc(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;this.setAuthorInfo(s,t);const h="document"===e._,p=h&&e.mime_type&&(["video","gif"].includes(e.type)||0===e.mime_type.indexOf("video/"));this.isFirstOpen&&(this.isFirstOpen=!1,this.listLoader.setTargets(o,l,a),window.appMediaViewer=this),this.listLoader.next.length<10&&setTimeout(()=>{this.listLoader.load(!0)},0),this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const u=this.content.media,g=!n||n===u;g&&(n=u),this.target={element:n};const m=++this.tempId;u.firstElementChild&&(u.innerHTML="");0!==i?(this.moveTheMover(this.content.mover,1===i),this.setNewMover()):(this.toggleOverlay(!0),this.setGlobalListeners(),this.wholeDiv.parentElement||(this.pageEl.insertBefore(this.wholeDiv,document.getElementById("main-columns")),this.wholeDiv.offsetLeft),this.toggleWholeActive(!0),ae.f||(this.navigationItem={type:"media",onPop:e=>{if(this.setMoverAnimationPromise)return!1;this.close()}},F.a.pushItem(this.navigationItem)));const v=this.content.mover,f=St.a.width;let y=0;const w=St.a.height;w<1e6&&!b.b.isMobile&&(y=120);const S=w-120-y;let C=Promise.resolve();const I=r.a.setAttachmentSize(e,u,f,S,!b.b.isMobile,void 0,!!(h&&e.w&&e.h)).photoSize;if(g){const t=ce.a.getCacheContext(e,I.type);let s;if(t.downloaded)s=new Image,s.src=t.url;else{const i=r.a.getStrippedThumbIfNeeded(e,t,!0);i&&(C=i.loadPromise,s=i.image)}s&&(s.classList.add("thumbnail"),u.append(s))}const M=!(!h||!e.supportsStreaming),E=M?this.preloaderStreamable:this.preloader;let P;if(p){const t=d&&"gif"!==e.type,s=Cs({pip:t}),a=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:i})=>{const a=v.firstElementChild&&v.firstElementChild.classList.contains("media-viewer-aspecter")?v.firstElementChild:v,o=v.querySelector("video");o&&o.remove(),s.setAttribute("playsinline","true"),s.addEventListener("timeupdate",()=>{this.tempId!==m&&s.pause()}),s.addEventListener("error",()=>{4!==s.error.code&&this.log.error("Error "+s.error.code+"; details: "+s.error.message),E&&E.detach()},{once:!0}),this.addEventListener("setMoverAfter",()=>{s.src="",s.load()},{once:!0}),ae.g&&(s.autoplay=!0),"gif"===e.type?(s.muted=!0,s.autoplay=!0,s.loop=!0):e.duration<60&&(s.loop=!0),a.append(s);const r=new Promise(e=>{s.addEventListener("canplay",e,{once:!0})}),l=()=>{"gif"!==e.type&&(s.dataset.ckin="default",s.dataset.overlay="1",Promise.all([r,i]).then(()=>{if(this.tempId!==m)return;(this.videoPlayer=new ac({video:s,play:!0,streamable:M,onPlaybackRackMenuToggle:e=>{this.wholeDiv.classList.toggle("hide-caption",!!e)},onPip:e=>{const i=window.appMediaViewer;if(!e&&i&&i!==this)return this.releaseSingleMedia=void 0,void this.close();this.moversContainer.lastElementChild.classList.toggle("hiding",e),this.toggleWholeActive(!e),this.toggleOverlay(!e),this.toggleGlobalListeners(!e),this.navigationItem&&(e?F.a.removeItem(this.navigationItem):F.a.pushItem(this.navigationItem)),t&&(e?(this.releaseSingleMedia(!1),this.releaseSingleMedia=void 0,fe.setPictureInPicture(s)):this.releaseSingleMedia=fe.setSingleMedia(s,d))},onPipClose:()=>{this.close()}})).addEventListener("toggleControls",e=>{this.wholeDiv.classList.toggle("has-video-controls",e)}),this.addEventListener("setMoverBefore",()=>{this.wholeDiv.classList.remove("has-video-controls"),this.videoPlayer.cleanup(),this.videoPlayer=void 0},{once:!0}),this.isZooming()&&this.videoPlayer.lockControls(!1)}))};if(M){i.then(()=>{s.readyState<s.HAVE_FUTURE_DATA&&E.attach(v,!0)});const e=()=>{s.addEventListener("canplay",()=>{E.detach(),s.parentElement.classList.remove("is-buffering")},{once:!0})};s.addEventListener("waiting",()=>{const t=s.networkState===s.NETWORK_LOADING,i=s.readyState<s.HAVE_FUTURE_DATA;t&&i&&(e(),E.attach(v,!0),s.parentElement.classList.add("is-buffering"))}),this.wholeDiv.classList.contains("no-forwards")&&s.addEventListener("contextmenu",e=>{Object(c.a)(e)}),e()}this.lazyLoadQueue.unshift({load:()=>{const o=ce.a.getCacheContext(e),r=M?Promise.resolve():L.a.downloadDoc(e);return M||i.then(()=>{o.url||E.attach(v,!0,r)}),Promise.all([r,i]).then(()=>{if(this.tempId!==m)return void this.log.warn("media viewer changed video");const e=o.url;n instanceof SVGSVGElement?a.firstElementChild.lastElementChild.append(s):Object(ps.a)(s,e),t&&(this.releaseSingleMedia=fe.setSingleMedia(s,d),this.addEventListener("setMoverBefore",()=>{this.releaseSingleMedia&&(this.releaseSingleMedia(),this.releaseSingleMedia=void 0)},{once:!0})),this.updateMediaSource(n,e,"video"),l()}),r}})});P=C.then(a)}else{const t=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:t})=>{this.lazyLoadQueue.unshift({load:()=>{const s=ce.a.getCacheContext(e,I.type),i=h?L.a.downloadDoc(e):r.a.preloadPhoto(e,I);return t.then(()=>{s.url||this.preloader.attachPromise(i)}),Promise.all([t,i]).then(()=>{var e;if(this.tempId!==m)return void this.log.warn("media viewer changed photo");const t=s.url;if(n instanceof SVGSVGElement){if(this.updateMediaSource(n,t,"img"),this.updateMediaSource(v,t,"img"),b.b.isMobile){const e=v.querySelectorAll("img");e&&e.length&&e.forEach(e=>{e.classList.remove("thumbnail")})}}else{const s=v.firstElementChild&&v.firstElementChild.classList.contains("media-viewer-aspecter")?v.firstElementChild:v,i="IMG"===(null===(e=s.firstElementChild)||void 0===e?void 0:e.tagName)?s.firstElementChild:null;if(!i||i.src!==t){let e=new Image;e.classList.add("thumbnail"),Object(ps.a)(e,t,()=>{this.updateMediaSource(n,t,"img"),i&&Object(Le.b)(()=>{i.remove()}),s.append(e)})}}}).catch(e=>{this.log.error(e),this.preloader.attach(v),this.preloader.setManual()}),i}})});P=C.then(t)}return this.setMoverPromise=P.catch(()=>{this.setMoverAnimationPromise=null}).finally(()=>{this.setMoverPromise=null})}))}}var lc=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class cc extends rc{constructor(){let e;super(new C({processItem:e=>{const t="inputMessagesFilterDocument"===this.searchContext.inputFilter._,{mid:s,peerId:n}=e,a=i.a.getMediaFromMessage(e);if(a&&(!t||cc.isMediaCompatibleForDocumentViewer(a)))return{element:null,mid:s,peerId:n}}}),["delete","forward"]),this.onPrevClick=e=>{this.openMedia(this.getMessageByPeer(e.peerId,e.mid),e.element,-1)},this.onNextClick=e=>{this.openMedia(this.getMessageByPeer(e.peerId,e.mid),e.element,1)},this.onDeleteClick=()=>{const e=this.target;new Js(e.peerId,[e.mid],"chat",()=>{this.target={element:this.content.media},this.close()})},this.onForwardClick=()=>{const e=this.target;e.mid&&new Xs({[e.peerId]:[e.mid]},()=>this.close())},this.onAuthorClick=e=>{const{mid:t,peerId:s}=this.target;if(t&&t!==Number.MAX_SAFE_INTEGER){const i=this.searchContext.threadId,n=this.getMessageByPeer(s,t);this.close(e).then(()=>{if(b.b.isMobile){const e=ts.getTab(Zt);e&&e.close()}nc.setInnerPeer({peerId:n.peerId,lastMsgId:t,type:i?"discussion":void 0,threadId:i})})}},this.onDownloadClick=()=>{const{peerId:e,mid:t}=this.target,s=this.getMessageByPeer(e,t);if(s.media.photo)r.a.savePhotoFile(s.media.photo,nc.chat.bubbles.lazyLoadQueue.queueId);else{let e=null;e=s.media.webpage?s.media.webpage.document:s.media.document,e&&L.a.saveDocFile(e,nc.chat.bubbles.lazyLoadQueue.queueId)}},this.listLoader.onEmptied=()=>{this.close()},this.content.caption=document.createElement("div"),this.content.caption.classList.add("media-viewer-caption");const t=()=>{e&&clearTimeout(e),e=window.setTimeout(()=>{e=void 0,this.content.caption.classList.remove("is-focused")},800)};this.content.caption.addEventListener("touchstart",()=>{b.b.isMobile&&(this.content.caption.classList.add("is-focused"),e&&(clearTimeout(e),e=void 0),document.addEventListener("touchend",t,{once:!0}))});new P.b(this.content.caption).onAdditionalScroll=t,this.wholeDiv.append(this.content.caption),Object(l.b)(this.buttons.delete,this.onDeleteClick);const s=[this.btnMenuForward={icon:"forward",text:"Forward",onClick:this.onForwardClick},this.btnMenuDownload={icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick},this.btnMenuDelete={icon:"delete danger",text:"Delete",onClick:this.onDeleteClick}];this.setBtnMenuToggle(s),this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),Object(l.b)(this.buttons.forward,this.onForwardClick),Object(l.b)(this.author.container,this.onAuthorClick);const e=t=>{if(t.target instanceof HTMLAnchorElement){const s=t.target.getAttribute("onclick");if(!s||s.includes("showMaskedAlert"))return;return Object(c.a)(t),this.close().then(()=>{Object(l.c)(this.content.caption,e,{capture:!0}),t.target.click()}),!1}};Object(l.b)(this.content.caption,e,{capture:!0})}getMessageByPeer(e,t){return this.searchContext.isScheduled?i.a.getScheduledMessageByPeer(e,t):i.a.getMessageByPeer(e,t)}setCaption(e){const t=e.message;let s="";t&&(s=X.b.wrapRichText(t,{entities:e.totalEntities})),Object(m.a)(this.content.caption.firstElementChild,s),this.content.caption.classList.toggle("hide",!t)}setSearchContext(e){return this.listLoader.setSearchContext(e),this}openMedia(e,t,s=0,n=!1,a=[],o=[]){const r=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return lc(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const l=e.mid,c=e.fwd_from&&!e.fromId?e.fwd_from.from_name:e.fromId,d=i.a.getMediaFromMessage(e),h="messageService"===e._||!i.a.canForward(e);[this.buttons.forward,this.btnMenuForward.element].forEach(e=>{e.classList.toggle("hide",h)}),this.wholeDiv.classList.toggle("no-forwards",h);const p=h;[this.buttons.download,this.btnMenuDownload.element].forEach(e=>{e.classList.toggle("hide",p)});const u=i.a.canDeleteMessage(e);[this.buttons.delete,this.btnMenuDelete.element].forEach(e=>{e.classList.toggle("hide",!u)}),this.setCaption(e);const g=r._openMedia.call(this,d,e.date,c,s,t,n,a,o,e);return this.target.mid=l,this.target.peerId=e.peerId,g}))}static isMediaCompatibleForDocumentViewer(e){return"photo"===e._||g.has(e.mime_type)}}class dc extends S{constructor(e){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{if(this.peerId.isAnyChat()||!t)return Promise.resolve({count:0,items:[]});const i=null==e?void 0:e.photoId;return r.a.getUserPhotos(this.peerId,i,s).then(e=>{const t=e.photos.map(e=>({element:null,photoId:e}));return{count:e.count,items:t}})}})),this.loadedAllUp=!0,this.peerId=e.peerId}}var hc=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class pc extends rc{constructor(e){super(new dc({peerId:e}),[]),this.onPrevClick=e=>{this.openMedia(e.photoId,e.element,-1)},this.onNextClick=e=>{this.openMedia(e.photoId,e.element,1)},this.onDownloadClick=()=>{r.a.savePhotoFile(r.a.getPhoto(this.target.photoId),nc.chat.bubbles.lazyLoadQueue.queueId)},this.peerId=e,this.setBtnMenuToggle([{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}openMedia(e,t,s=0,i,n){const a=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return hc(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const o=r.a.getPhoto(e),l=a._openMedia.call(this,o,o.date,this.peerId,s,t,!1,i,n);return this.target.photoId=o.id,l}))}}var uc=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const gc=e=>{d.a.removeFromAvatarsCache(e),Array.from(document.querySelectorAll('avatar-element[data-peer-id="'+e+'"]')).forEach(e=>{e.update()})};function mc(e,t,s,a,o,l){return uc(this,void 0,void 0,(function*(){let c=yield n.default.getFullPhoto(t);if(!s()||!c)return;const d=()=>Array.from(e.querySelectorAll("img")).find(e=>!e.classList.contains("emoji"))?e:null;if(t.isAnyChat()){const e=!!a,n="inputMessagesFilterChatPhotos";if(!a&&(a=yield i.a.getSearch({peerId:t,inputFilter:{_:n},maxId:0,limit:1}).then(e=>e.history[0]),!s()))return;if(a){a.action.photo.id!==c.id&&(e||(a=i.a.generateFakeAvatarMessage(t,c)));const s=e=>e.map(e=>({element:e.element,mid:e.item.mid,peerId:e.item.peerId}));return void(new cc).setSearchContext({peerId:t,inputFilter:{_:n}}).openMedia(a,d(),void 0,void 0,o?s(o):void 0,l?s(l):void 0)}}if(c){!Object(ha.a)(a)&&a&&(c=r.a.getPhoto(a));const e=e=>e.map(e=>({element:e.element,photoId:e.item}));new pc(t).openMedia(c.id,d(),void 0,o?e(o):void 0,l?e(l):void 0)}}))}a.a.addEventListener("avatar_update",gc),a.a.addEventListener("peer_title_edit",e=>{d.a.isAvatarCached(e)||gc(e)});const bc=new Map,vc=new Set;class fc extends HTMLElement{constructor(){super(...arguments),this.addedToQueue=!1}disconnectedCallback(){const e=bc.get(this.peerId);e&&e.has(this)&&(e.delete(this),e.size||bc.delete(this.peerId)),this.lazyLoadQueue&&this.lazyLoadQueue.unobserve(this)}attachClickEvent(){let e=!1;Object(l.b)(this,t=>uc(this,void 0,void 0,(function*(){if(Object(c.a)(t),e)return;const s=this.peerId;e=!0,yield mc(this,this.peerId,()=>this.peerId===s),e=!1})))}updateOptions(e){for(let t in e)this[t]=e[t]}updateWithOptions(e){const t=this.peerId;this.updateOptions(e);const s=this.peerId;if(t!==s){if(this.peerId=o.a.getPeerMigratedTo(s)||s,this.dataset.peerId=""+s,t){const e=bc.get(t);e&&(e.delete(this),e.size||bc.delete(t))}return this.update()}}r(e=!1){const t=d.a.putPhoto(this,this.peerId,this.isDialog,this.peerTitle,e,this.isBig),s=t?t.loadPromise:Promise.resolve();return this.loadPromises&&(t&&t.cached&&this.loadPromises.push(s),s.finally(()=>{this.loadPromises=void 0})),t}update(){if(this.lazyLoadQueue){if(!vc.has(this.peerId)){if(this.addedToQueue)return;this.addedToQueue=!0;let e=bc.get(this.peerId);return e||(e=new Set,bc.set(this.peerId,e)),e.add(this),this.r(!0),void this.lazyLoadQueue.push({div:this,load:()=>(vc.add(this.peerId),this.update())})}this.addedToQueue&&this.lazyLoadQueue.unobserve(this)}vc.add(this.peerId);const e=this.r(),t=e?e.loadPromise:Promise.resolve();this.addedToQueue&&t.finally(()=>{this.addedToQueue=!1});const s=bc.get(this.peerId);if(s){s.delete(this);const e=Array.from(s);bc.delete(this.peerId);for(let t=0,s=e.length;t<s;++t)e[t].update()}return t}}customElements.define("avatar-element",fc);class yc{constructor(){this.onArchiveClick=()=>{let e=i.a.getDialogOnly(this.selectedId);e&&i.a.editPeerFolders([e.peerId],+!e.folder_id)},this.onPinClick=()=>{i.a.toggleDialogPin(this.selectedId,this.filterId).catch(e=>{"PINNED_DIALOGS_TOO_MUCH"===e.type&&(this.filterId>=1?rt({langPackKey:"PinFolderLimitReached"}):new ut("pinned-dialogs-too-much",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"FiltersSetupPinAlert",callback:()=>{new Sn($n).open()}}],descriptionLangKey:"PinToTopLimitReached2",descriptionLangArgs:[Object(T.d)("Chats",[a.a.config.pinned_dialogs_count_max])]}).show())})},this.onUnmuteClick=()=>{i.a.togglePeerMute(this.selectedId,!1)},this.onMuteClick=()=>{new ur(this.selectedId)},this.onUnreadClick=()=>{const e=i.a.getDialogOnly(this.selectedId);e&&(e.unread_count?(i.a.readHistory(this.selectedId,e.top_message),i.a.markDialogUnread(this.selectedId,!0)):i.a.markDialogUnread(this.selectedId))},this.onDeleteClick=()=>{new Ot(this.selectedId)},this.onContextMenu=e=>{this.init&&(this.init(),this.init=null);let t=null;try{t=Object(bt.a)(e.target,"LI")}catch(e){}if(t){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),this.filterId=_c.filterId,this.selectedId=t.dataset.peerId.toPeerId(),this.dialog=i.a.getDialogOnly(this.selectedId),this.buttons.forEach(e=>{const t=e.verify();e.element.classList.toggle("hide",!t)}),this.buttons[this.buttons.length-1].element.lastChild.replaceWith(Object(T.d)(o.a.getDeleteButtonText(this.selectedId))),t.classList.add("menu-open"),Object(ee.e)(e,this.element),Object(ee.d)(this.element,()=>{t.classList.remove("menu-open"),this.selectedId=this.dialog=this.filterId=void 0})}}}init(){this.buttons=[{icon:"unread",text:"MarkAsUnread",onClick:this.onUnreadClick,verify:()=>!i.a.isDialogUnread(this.dialog)},{icon:"readchats",text:"MarkAsRead",onClick:this.onUnreadClick,verify:()=>i.a.isDialogUnread(this.dialog)},{icon:"pin",text:"ChatList.Context.Pin",onClick:this.onPinClick,verify:()=>{var e;return!(this.filterId>1?i.a.filtersStorage.getFilter(this.filterId).pinnedPeerIds.includes(this.dialog.peerId):!!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.pinned))}},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:this.onPinClick,verify:()=>{var e;return this.filterId>1?i.a.filtersStorage.getFilter(this.filterId).pinnedPeerIds.includes(this.dialog.peerId):!!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.pinned)}},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:()=>this.selectedId!==a.a.myId&&!Bt.a.isPeerLocalMuted(this.dialog.peerId)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.selectedId!==a.a.myId&&Bt.a.isPeerLocalMuted(this.dialog.peerId)},{icon:"archive",text:"Archive",onClick:this.onArchiveClick,verify:()=>0===this.filterId&&this.selectedId!==a.a.myId},{icon:"unarchive",text:"Unarchive",onClick:this.onArchiveClick,verify:()=>1===this.filterId&&this.selectedId!==a.a.myId},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>!0}],this.element=$s(this.buttons),this.element.id="dialogs-contextmenu",this.element.classList.add("contextmenu"),document.getElementById("page-chats").append(this.element)}}var wc,Sc;!function(e){e[e.Connected=0]="Connected",e[e.Connecting=1]="Connecting",e[e.Closed=2]="Closed",e[e.TimedOut=3]="TimedOut"}(wc||(wc={}));class Cc{constructor(e){this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=()=>{zn.a.get("dc").then(e=>{e||(e=Hn.a.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const t=a.a.connectionStatus["NET-"+e],s=t&&t.status===wc.Connected;this.connecting&&s&&vi.a.forceGetDifference(),s&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=t&&t.status===wc.TimedOut,this.connecting=!s,this.retryAt=t&&t.retryAt,le.b&&this.log("connecting",this.connecting),this.setState()})},this.setStatusText=(e,t)=>{this.currentLangPackKey!==e&&(this.currentLangPackKey=e,Object(k.a)(this.statusEl,Object(T.d)(e,t)),this.statusPreloader.attach(this.statusEl))},this.setState=()=>{const e=Cc.CHANGE_STATE_DELAY;if(this.connecting)if(this.timedOut){const e=this.getA("ConnectionStatus.ForceReconnect",()=>ct.a.forceReconnect());this.setStatusText("ConnectionStatus.TimedOut",[e])}else if(this.hadConnect)if(void 0!==this.retryAt){const e=document.createElement("span"),t=this.retryAt,s=()=>{const s=Date.now();e.innerText=""+Math.round((t-s)/1e3),s>t&&clearInterval(i)},i=setInterval(s,1e3);s();const n=this.getA("ConnectionStatus.Reconnect",()=>ct.a.forceReconnectTimeout());this.setStatusText("ConnectionStatus.ReconnectIn",[e,n])}else this.setStatusText("ConnectionStatus.Reconnecting");else this.setStatusText("ConnectionStatus.Waiting");else this.updating&&this.setStatusText("Updating");le.b&&this.log("setState",this.connecting||this.updating),window.requestAnimationFrame(()=>{this.setStateTimeout&&clearTimeout(this.setStateTimeout);this.setStateTimeout=window.setTimeout(()=>{Object(is.a)(this.statusContainer,"is-shown",this.connecting||this.updating,200),this.setStateTimeout=0,le.b&&this.log("setState: isShown:",this.connecting||this.updating)},e)})},this.log=Object(Y.b)("CS",void 0,void 0),this.statusContainer=document.createElement("div"),this.statusContainer.classList.add("connection-status"),this.statusEl=Object(B.a)("btn-primary bg-warning connection-status-button",{noRipple:!0}),this.statusPreloader=new ye.a({cancelable:!1}),this.statusPreloader.constructContainer({color:"transparent",bold:!0}),this.statusContainer.append(this.statusEl),e.prepend(this.statusContainer),a.a.addEventListener("connection_status_change",e=>{console.log(e),this.setConnectionStatus()}),a.a.addEventListener("state_synchronizing",e=>{e||(this.updating=!0,le.b&&this.log("updating",this.updating),this.setState())}),a.a.addEventListener("state_synchronized",e=>{le.b&&this.log("state_synchronized",e),e||(this.updating=!1,le.b&&this.log("updating",this.updating),this.setState())}),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,Cc.CHANGE_STATE_DELAY+1e3)}getA(e,t){const s=document.createElement("a");return s.classList.add("force-reconnect"),s.append(Object(T.d)(e)),Object(l.b)(s,e=>{Object(c.a)(e),t()}),s}}function Lc(e,t,s,i,n,a,o,r){if("number"==typeof a)a={tl:a,tr:a,br:a,bl:a};else{const e={tl:0,tr:0,br:0,bl:0};for(const t in e)a[t]=a[t]||e[t]}e.beginPath(),e.moveTo(t+a.tl,s),e.lineTo(t+i-a.tr,s),e.quadraticCurveTo(t+i,s,t+i,s+a.tr),e.lineTo(t+i,s+n-a.br),e.quadraticCurveTo(t+i,s+n,t+i-a.br,s+n),e.lineTo(t+a.bl,s+n),e.quadraticCurveTo(t,s+n,t,s+n-a.bl),e.lineTo(t,s+a.tl),e.quadraticCurveTo(t,s,t+a.tl,s),e.closePath(),o&&e.fill(),r&&e.stroke()}Cc.CHANGE_STATE_DELAY=1e3,function(e){e[e.Error=-1]="Error",e[e.Pending=0]="Pending",e[e.Sent=1]="Sent",e[e.Read=2]="Read"}(Sc||(Sc={}));const Ic=window.devicePixelRatio,Mc=20*Ic,Ec=2.5*Ic,Pc=2*Ic,kc=1*Ic;function Tc(e=!1){const t=document.createElement("canvas");t.width=t.height=Mc;const s=t.getContext("2d"),i=(Mc-(3*Pc+2*Ec))/2,n=Date.now();let a=!1;const o=()=>{if(t.isConnected)a||(a=t.isConnected);else if(a)return!1;const o=Date.now(),r=(l=(o-n)%1e3,c=0,d=1e3,-1/2*(Math.cos(Math.PI*l/d)-1)+c);var l,c,d;s.clearRect(0,0,Mc,Mc),s.fillStyle=e&&!b.b.isMobile?Ar.getProperty("primary-color"):"#fff";for(let e=0;e<3;++e){let t;t=r>=.5?e%2?2-2*r:2*(r-.5):e%2?2*r:1-2*r;let n=4+8*t;n*=Ic;Lc(s,i+e*Pc+e*Ec,(Mc-n)/2,Pc,n,kc,!0)}return!0};return{canvas:t,startAnimation:()=>{Object(Pe.a)(o),o()},setActive:t=>{e=t,o()}}}var xc=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ac extends Hs{constructor(e,t,s){super({getIndex:e=>i.a.getDialogOnly(e.id)[this.indexKey],onDelete:e=>{e.dom.listEl.remove(),this.onListLengthChange&&this.onListLengthChange()},onSort:(e,t)=>{const s=e.dom.listEl.parentElement!==this.list;Ns(e.dom.listEl,this.list,t),s&&this.onListLengthChange&&this.onListLengthChange()},onElementCreate:(e,t)=>{const s=t?[]:void 0,{dom:i}=jc.addListDialog({dialog:e.id,loadPromises:s,isBatch:t});return e.dom=i,(null==s?void 0:s.length)&&(e.loadPromises=s,Promise.all(s).finally(()=>{delete e.loadPromises})),e},updateElementWith:Le.c}),this.list=e,this.indexKey=t,this.onListLengthChange=s}clear(){this.list.innerHTML="",super.clear()}}class Oc{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.scroll=null,this.log=Object(Y.b)("DIALOGS",Y.a.Log|Y.a.Error|Y.a.Warn|Y.a.Debug),this.contextMenu=new yc,this.sortedLists={},this.scrollables={},this.folders={menu:document.getElementById("folders-tabs"),menuScrollContainer:null,container:document.getElementById("folders-container")},this.filtersRendered={},this.lastActiveElements=new Set,this.offsets={top:0,bottom:0},this.initedListeners=!1,this.loadedDialogsAtLeastOnce=!1,this.onTabChange=()=>{this.scroll=this.scrollables[this.filterId],this.scroll.loadedAll.top=!0,this.scroll.loadedAll.bottom=!1,this.offsets.top=this.offsets.bottom=0,this.loadDialogsPromise=void 0,this.sortedList=this.sortedLists[this.filterId],this.onChatsScroll()},this._onListLengthChange=()=>{if(!this.loadedDialogsAtLeastOnce)return;if(this.checkIfPlaceholderNeeded(),this.filterId>0)return;const e=this.chatList,t=e.childElementCount,s=e.parentElement.parentElement,i=e.parentElement.nextElementSibling,n=!!i.childElementCount;if(t>=10)return void(n&&this.removeContactsPlaceholder());if(n)return;s.classList.add("with-contacts");const a=new Kn({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});a.container.classList.add("hide"),E.a.getContactsPeerIds(void 0,void 0,"online").then(e=>{let t=!1;const s=()=>{t&&a.container.classList.toggle("hide",!i.list.childElementCount),this.updateContactsLength(!0)},i=new Vs({avatarSize:42,createChatListOptions:{dialogSize:48,new:!0},autonomous:!1,onListLengthChange:s});this.loadContacts=()=>{const t=St.a.height/60|0;e.splice(0,t).filter(this.verifyPeerIdForContacts).forEach(e=>{i.add(e)}),e.length||(this.loadContacts=void 0)},this.loadContacts(),this.processContact=e=>{if(e.isAnyChat())return;const t=this.verifyPeerIdForContacts(e),s=i.has(e);!s&&t?i.add(e):s&&!t&&i.delete(e)};const n=i.list;n.classList.add("chatlist-new"),this.setListClickListener(n),a.content.append(n),t=!0,s()}),i.append(a.container)},this.verifyPeerIdForContacts=e=>e.isContact()&&!i.a.getDialogOnly(e),this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout(()=>{this.sliceTimeout=void 0,this.chatList.childElementCount&&!this.processContact&&Object(Le.c)(()=>{const e=performance.now(),t=this.scroll.scrollTop,s=this.chatList.firstElementChild,i=this.scroll.container.getBoundingClientRect(),n=s.getBoundingClientRect(),a=Array.from(this.scroll.splitUp.children);let o=this.scroll.splitUp.offsetTop;o&&t<o&&(o-=t);const r=i.y+o,l=i.y,c=Object(bt.a)(document.elementFromPoint(Math.ceil(n.x),Math.ceil(r+1)),s.tagName),d=Object(bt.a)(document.elementFromPoint(Math.ceil(n.x),Math.floor(l+i.height-1)),s.tagName);if(!c||!d)return;const h=c.getBoundingClientRect().y-r,p=[],u=a.indexOf(c),g=a.indexOf(d),m=ae.g?[]:a.slice(0,Math.max(0,u-10)),b=a.slice(g+10);m.length&&(this.scroll.loadedAll.top=!1),b.length&&(this.scroll.loadedAll.bottom=!1),p.push(...m),p.push(...b),p.forEach(e=>{const t=e.dataset.peerId.toPeerId();this.deleteDialog(t)}),this.setOffsets(),this.scroll.scrollTop=c.offsetTop-h,this.log("slice time",performance.now()-e)})},200)},this.onChatsScrollTop=()=>this.onChatsScroll("top"),this.onChatsScroll=(e="bottom")=>this.scroll.loadedAll[e]?(this.loadContacts&&this.loadContacts(),Promise.resolve()):this.loadDialogsPromise?this.loadDialogsPromise:(this.log("onChatsScroll",e),this.loadDialogs(e)),this.chatsPreloader=Object(ee.f)(null,!0),this.allUnreadCount=this.folders.menu.querySelector(".badge"),this.folders.menuScrollContainer=this.folders.menu.parentElement,this.onListLengthChange=Object(lt.a)(this._onListLengthChange,100,!1,!0);const e=document.createElement("div");e.classList.add("connection-status-bottom"),e.append(this.folders.container),he.a&&Ws({element:this.folders.container,onSwipe:e=>{const t=s.prevId();s(e>0?t+1:t-1)}}),this.allChatsIntlElement=new T.c.IntlElement({key:"FilterAllChatsShort"}),this.setFilterId(0),this.addFilter({id:this.filterId,title:"",titleEl:this.allChatsIntlElement.element,orderIndex:0}),this.sortedList=this.sortedLists[this.filterId],this.scroll=this.scrollables[this.filterId],a.a.addEventListener("state_cleared",()=>{M.c.getState().then(e=>{this.loadedDialogsAtLeastOnce=!1,E.a.clear(),G.a.clear();const t=i.a.filtersStorage.filters;for(const e in t)a.a.dispatchEvent("updateDialogFilter",{_:"updateDialogFilter",id:+e});i.a.clear(),this.sortedList.clear(),this.onTabChange(),this.onStateLoaded(e)})});const t=new P.a(this.folders.menuScrollContainer);e.prepend(this.folders.menuScrollContainer);const s=Object(J.a)(this.folders.menu,this.folders.container,(e,t)=>{e=+t.dataset.filterId||0,ae.f||(e?this.filtersNavigationItem||(this.filtersNavigationItem={type:"filters",onPop:()=>{s(0),this.filtersNavigationItem=void 0}},F.a.spliceItems(1,0,this.filtersNavigationItem)):this.filtersNavigationItem&&(F.a.removeItem(this.filtersNavigationItem),this.filtersNavigationItem=void 0)),this.filterId!==e&&(this.sortedLists[e].clear(),this.setFilterId(e),this.onTabChange())},()=>{for(const e in this.sortedLists)+e!==this.filterId&&this.sortedLists[e].clear()},void 0,t);this.folders.menu.firstElementChild.click(),i.a.construct(),M.c.getState().then(e=>(fe.setPlaybackParams(e.playbackParams),a.a.addEventListener("media_playback_params",e=>{M.c.pushToState("playbackParams",e)}),this.onStateLoaded(e))),b.b.addEventListener("resize",()=>{this.changeFiltersAllChatsKey()}),new Cc(this.chatsContainer),this.chatsContainer.append(e),setTimeout(()=>{oe.a.loadLottieWorkers()},200)}get chatList(){return this.sortedList.list}setFilterId(e){this.filterId=e,this.indexKey=i.a.dialogsStorage?i.a.dialogsStorage.getDialogIndexKey(this.filterId):"index",a.a.filterId=e}setOnlineStatus(e,t){const s=e.classList.contains("is-online");!s&&t&&e.classList.add("is-online"),Object(is.a)(e,"is-visible",t,250,t?void 0:()=>{e.classList.remove("is-online")},t&&!s?2:0)}initListeners(){a.a.addEventListener("user_update",e=>{var t;const s=e.toPeerId(),i=this.getDialogDom(s);if(i&&!E.a.isBot(e)&&s!==a.a.myId){const s="userStatusOnline"===(null===(t=E.a.getUser(e).status)||void 0===t?void 0:t._);this.setOnlineStatus(i.avatarEl,s)}}),a.a.addEventListener("chat_update",e=>{const t=e.toPeerId(!0),s=i.a.getDialogOnly(t);s&&this.processDialogForCallStatus(s)}),a.a.addEventListener("folder_unread",e=>{this.setFilterUnreadCount(e.id)}),a.a.addEventListener("contacts_update",e=>{this.processContact&&this.processContact(e.toPeerId())}),a.a.addEventListener("dialog_flush",({peerId:e})=>{const t=i.a.getDialogOnly(e);t&&(this.setLastMessage(t,void 0,void 0,void 0,void 0,void 0,!0),this.validateDialogForFilter(t),this.setFiltersUnreadCount())}),a.a.addEventListener("dialogs_multiupdate",e=>{for(const t in e){const s=e[t];this.updateDialog(s),this.processContact&&this.processContact(t.toPeerId()),this.validateDialogForFilter(s)}}),a.a.addEventListener("dialog_drop",({peerId:e})=>{this.deleteDialog(e),this.processContact&&this.processContact(e)}),a.a.addEventListener("dialog_unread",({peerId:e})=>{const t=i.a.getDialogOnly(e);t&&(this.setUnreadMessages(t),this.validateDialogForFilter(t))}),a.a.addEventListener("dialog_notify_settings",e=>{this.validateDialogForFilter(e),this.setUnreadMessages(e),this.setFiltersUnreadCount()}),a.a.addEventListener("dialog_draft",({dialog:e,drop:t,peerId:s})=>{t?this.sortedList.delete(s):this.updateDialog(e),this.processContact&&this.processContact(s)}),a.a.addEventListener("peer_changed",e=>{for(const t of this.lastActiveElements)t.dataset.peerId.toPeerId()!==e&&this.setDialogActive(t,!1);Array.from(document.querySelectorAll(`[data-autonomous="0"] li[data-peer-id="${e}"]`)).forEach(e=>{this.setDialogActive(e,!0)})}),a.a.addEventListener("filter_update",e=>{if(!this.filtersRendered[e.id])return void this.addFilter(e);if(e.id===this.filterId){const e=i.a.dialogsStorage.getCachedDialogs(!0);this.validateListForFilter();for(let t=0,s=e.length;t<s;++t){const s=e[t];this.updateDialog(s)}}const t=this.filtersRendered[e.id];Object(m.a)(t.title,X.a.wrapEmojiText(e.title))}),a.a.addEventListener("filter_delete",e=>{const t=this.filtersRendered[e.id];t&&(this.folders.menu.firstElementChild.click(),t.container.remove(),t.menu.remove(),delete this.sortedLists[e.id],delete this.scrollables[e.id],delete this.filtersRendered[e.id],this.onFiltersLengthChange())}),a.a.addEventListener("filter_order",e=>{const t=this.folders.menu;e.forEach(e=>{const s=i.a.filtersStorage.getFilter(e),n=this.filtersRendered[e];this.sortedLists[e].indexKey=i.a.dialogsStorage.getDialogIndexKey(e),Ns(n.menu,t,s.orderIndex),Ns(n.container,this.folders.container,s.orderIndex)}),this.indexKey=i.a.dialogsStorage.getDialogIndexKey(this.filterId)}),a.a.addEventListener("peer_typings",({peerId:e,typings:t})=>{const s=i.a.getDialogOnly(e);s&&(t.length?this.setTyping(s):this.unsetTyping(s))})}setDialogActive(e,t){const s=e.dialogDom;e.classList.toggle("active",t),t?this.lastActiveElements.add(e):this.lastActiveElements.delete(e),(null==s?void 0:s.callIcon)&&s.callIcon.setActive(t)}onStateLoaded(e){return xc(this,void 0,void 0,(function*(){if(e.notifySettings)for(const t in e.notifySettings)Object(ys.a)(t),Bt.a.savePeerSettings({key:t,settings:e.notifySettings[t]});Bt.a.getNotifyPeerTypeSettings(),this.initedListeners||(this.initListeners(),this.initedListeners=!0);const t=i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.addFilter(t)});return e.filters&&Object.keys(e.filters).length&&(yield t,this.showFiltersPromise&&(yield this.showFiltersPromise)),M.c.storagesResults.dialogs.length&&Vi.a.addMissedDialogs(),this.onChatsScroll().then(()=>{i.a.fillConversations()})}))}getOffsetIndex(e){return{index:this.scroll.loadedAll[e]?0:this.offsets[e]}}isDialogMustBeInViewport(e){if(void 0!==e.migratedTo||!this.testDialogForFilter(e))return!1;const t=this.getOffsetIndex("top"),s=this.getOffsetIndex("bottom");if(!t.index&&!s.index)return!0;const i=e[this.indexKey];return(!t.index||i<=t.index)&&(!s.index||i>=s.index)}deleteDialog(e){this.sortedList.delete(e)}updateDialog(e){if(!this.isDialogMustBeInViewport(e))return void this.deleteDialog(e.peerId);if(!this.sortedList.has(e.peerId))return void this.sortedList.add(e.peerId);const t=this.getDialogDom(e.peerId);t&&(this.setLastMessage(e,void 0,t,void 0,void 0,void 0,!0),this.sortedList.update(e.peerId))}setFilterUnreadCount(e){var t;const s=0===e?this.allUnreadCount:null===(t=this.filtersRendered[e])||void 0===t?void 0:t.unread;if(!s)return;const n=i.a.dialogsStorage.getFolder(e),a=0===e||!!n.dialogs.find(e=>(e.unread_count||e.pFlags.unread_mark)&&!Bt.a.isPeerLocalMuted(e.peerId,!0));s.classList.toggle("badge-gray",!a);const o=n.unreadDialogsCount;s.innerText=o?""+o:""}setFiltersUnreadCount(){for(const e in this.filtersRendered)this.setFilterUnreadCount(+e)}validateListForFilter(){const e=i.a.filtersStorage.getFilter(this.filterId)||null;this.sortedList.getAll().forEach(t=>{const s=i.a.getDialogOnly(t.id);this.testDialogForFilter(s,e)||this.deleteDialog(t.id)})}validateDialogForFilter(e,t){this.getDialogDom(e.peerId)&&(this.testDialogForFilter(e,t)||this.deleteDialog(e.peerId))}testDialogForFilter(e,t=i.a.filtersStorage.getFilter(this.filterId)){return!(!e||t&&!i.a.filtersStorage.testDialogForFilter(e,t)||!t&&this.filterId!==e.folder_id)}generateScrollable(e,t){const s=new P.b(null,"CL",500);s.container.addEventListener("scroll",this.onChatsRegularScroll),s.container.dataset.filterId=""+t,s.onScrolledTop=this.onChatsScrollTop,s.onScrolledBottom=this.onChatsScroll,s.setVirtualContainer(e);const n=new Ac(e,i.a.dialogsStorage?i.a.dialogsStorage.getDialogIndexKey(t):"index",this.onListLengthChange);return this.scrollables[t]=s,this.sortedLists[t]=n,s}addFilter(e){if(this.filtersRendered[e.id])return;const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const s=document.createElement("span"),i=document.createElement("span");i.classList.add("text-super"),e.titleEl?i.append(e.titleEl):Object(m.a)(i,X.a.wrapEmojiText(e.title));const n=document.createElement("div");n.classList.add("badge","badge-20","badge-primary");const a=document.createElement("i");s.append(i,n,a),Object(te.a)(t),t.append(s);Ns(t,this.folders.menu,e.orderIndex);const o=this.createChatList(),r=this.generateScrollable(o,e.id);r.container.classList.add("tabs-tab","chatlist-parts");const l=document.createElement("div");l.classList.add("chatlist-top");const c=document.createElement("div");c.classList.add("chatlist-bottom"),l.append(o),r.container.append(l,c);const d=r.container;Ns(r.container,this.folders.container,e.orderIndex),this.setListClickListener(o,null,!0),this.filtersRendered[e.id]={menu:t,container:d,unread:n,title:i},this.onFiltersLengthChange()}changeFiltersAllChatsKey(){const e=this.folders.menuScrollContainer.firstElementChild,t=e.scrollWidth>e.clientWidth?"FilterAllChatsShort":"FilterAllChats";this.allChatsIntlElement.compareAndUpdate({key:t})}onFiltersLengthChange(){return this.showFiltersPromise||(this.showFiltersPromise=new Promise(e=>{window.setTimeout(()=>{const t=Object.keys(this.filtersRendered).length>1,s=!this.folders.menuScrollContainer.classList.contains("hide");t!==s&&(this.folders.menuScrollContainer.classList.toggle("hide",!t),t&&!s&&this.setFiltersUnreadCount(),this.chatsContainer.classList.toggle("has-filters",t)),this.changeFiltersAllChatsKey(),this.showFiltersPromise=void 0,e()},0)})),this.showFiltersPromise}loadDialogs(e){if(this.loadDialogsPromise)return this.loadDialogsPromise;const t=new Promise(s=>xc(this,void 0,void 0,(function*(){const{chatList:n,filterId:a,indexKey:o}=this;let r=St.a.height/72*1.25|0,l=0;const{index:c}=this.getOffsetIndex(e);if(c)if("top"===e){const e=i.a.dialogsStorage.getFolderDialogs(a,!0),t=e.findIndex(e=>e[o]<=c),s=Math.max(0,t-r);r=t-s,l=e[s][o]+1}else l=c;try{const s=i.a.getConversations("",l,r,a,!0);if(!s.cached&&!n.childElementCount){n.parentElement.append(this.chatsPreloader)}const c=yield s.promise;if(this.loadDialogsPromise!==t)return;if("bottom"===e?c.isEnd&&(this.scroll.loadedAll[e]=!0):c.isTopEnd&&(this.scroll.loadedAll[e]=!0),this.loadedDialogsAtLeastOnce=!0,c.dialogs.length){const t="top"===e?c.dialogs.slice().reverse():c.dialogs,s=[],n=[],a=e=>{n.push(e)};t.forEach(e=>{if(!i.a.getDialogOnly(e.peerId))return;const t=this.sortedList.add(e.peerId,!0,a,!1);t.loadPromises&&s.push(...t.loadPromises)}),yield Promise.all(s).finally(),n.forEach(e=>e())}else this.onListLengthChange();const d=c.dialogs["top"===e?0:c.dialogs.length-1];d&&(this.offsets[e]=d[o]),this.log.debug("getDialogs "+r+" dialogs by offset:",l,c,n.childElementCount),setTimeout(()=>{this.scroll.onScroll()},0)}catch(e){this.log.error(e)}this.chatsPreloader.parentElement&&this.chatsPreloader.remove(),s()}))).finally(()=>{this.loadDialogsPromise=void 0});return this.loadDialogsPromise=t}generateEmptyPlaceholder(e){const t="empty-placeholder",s=document.createElement("div");s.classList.add(t,t+"-"+e.classNameType);const i=document.createElement("div");i.classList.add(t+"-header"),Object(T.b)(i,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&Object(T.b)(n,e.subtitle,e.subtitleArgs),s.append(i,n),{container:s,header:i,subtitle:n}}checkIfPlaceholderNeeded(){if(1===this.filterId)return;const e=this.chatList,t=e.parentElement;let s=Array.from(t.children).find(e=>e.matches(".empty-placeholder"));const n=this.scroll.loadedAll.bottom&&!e.childElementCount;if(n&&s)return;if(!n)return void(s&&(t.classList.remove("with-placeholder"),s.remove()));let a,o;if(this.filterId){a=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:o="folder"}),s=a.container,s.prepend(function({emoji:e,width:t,height:s}){const i=document.createElement("div"),n=gs.a.getAnimatedEmojiSticker(e);return n?xs({doc:n,div:i,loop:!1,play:!0,width:t,height:s,emoji:e}).then(()=>{}):i.classList.add("media-sticker-wrapper"),{container:i}}({emoji:"📂",width:128,height:128}).container);const e=Object(B.a)("btn-primary btn-color-primary btn-control tgico",{text:"FilterHeaderEdit",icon:"settings"});Object(l.b)(e,()=>{new yn($n).open(i.a.filtersStorage.getFilter(this.filterId))}),s.append(e)}else{a=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:o="dialogs"}),s=a.container;const e=document.createElement("img");e.classList.add("empty-placeholder-dialogs-icon"),this.emptyDialogsPlaceholderSubtitle=new T.c.IntlElement({element:a.subtitle}),Promise.all([this.updateContactsLength(!1),Object(ps.b)(e,"assets/img/EmptyChats.svg"),Object(Le.d)()]).then(([e])=>{s.classList.add("visible"),t.classList.toggle("has-contacts",!!e)}),s.prepend(e)}t.append(s),t.classList.add("with-placeholder"),t.dataset.placeholderType=o}updateContactsLength(e){return this.updateContactsLengthPromise?this.updateContactsLengthPromise:this.updateContactsLengthPromise=E.a.getContacts().then(t=>{const s=this.emptyDialogsPlaceholderSubtitle;if(s){let e,i;t.length?(e="ChatList.Main.EmptyPlaceholder.Subtitle",i=[Object(T.d)("Contacts.Count",[t.length])]):(e="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",i=[]),s.compareAndUpdate({key:e,args:i})}if(e){this.chatList.parentElement.classList.toggle("has-contacts",!!t.length)}return this.updateContactsLengthPromise=void 0,t.length})}removeContactsPlaceholder(){const e=this.chatList,t=e.parentElement.parentElement,s=e.parentElement.nextElementSibling;t.classList.remove("with-contacts"),s.innerHTML="",this.loadContacts=void 0,this.processContact=void 0}setOffsets(){const e=this.chatList,t=this.getDialogFromElement(e.firstElementChild),s=this.getDialogFromElement(e.lastElementChild),i=this.indexKey;this.offsets.top=t[i],this.offsets.bottom=s[i]}getDialogFromElement(e){return i.a.getDialogOnly(e.dataset.peerId.toPeerId())}setListClickListener(e,t,s=!1,n=!1,a=!1){let o;const r=(a?nc.setInnerPeer:nc.setPeer).bind(nc);e.dataset.autonomous=""+ +n,e.addEventListener("mousedown",e=>{if(0!==e.button)return;this.log("dialogs click list");const s=e.target,i=Object(bt.a)(s,"LI");if(i){if(n){const e=o===i;o&&!e&&o.classList.remove("active"),i&&(i.classList.add("active"),o=i,this.lastActiveElements.add(i))}if(i){t&&t();const e=i.dataset.peerId.toPeerId(),s=+i.dataset.mid||void 0;r({peerId:e,lastMsgId:s})}else r()}},{capture:!0}),le.b&&e.addEventListener("dblclick",e=>{const t=Object(bt.a)(e.target,"LI");if(t){const e=t.dataset.peerId.toPeerId();this.log("debug dialog:",i.a.getDialogByPeerId(e))}}),s&&Object(ee.a)(e,this.contextMenu.onContextMenu)}createChatList(e={}){const t=document.createElement("ul");return t.classList.add("chatlist"),e.new&&t.classList.add("chatlist-new"),e.dialogSize&&t.classList.add("chatlist-"+e.dialogSize),t}setLastMessage(e,t,s,n,l,c=!1,d=!1){if(!s&&!(s=this.getDialogDom(e.peerId)))return;let h;if(t||(e.draft&&"draftMessage"===e.draft._&&(h=e.draft),t=i.a.getMessageByPeer(e.peerId,e.top_message)),"messageEmpty"===t._)return s.lastMessageSpan.innerHTML="",s.lastTimeSpan.innerHTML="",delete s.listEl.dataset.mid,void(d&&this.setUnreadMessages(e,s,c));const p=e.peerId,u=t&&i.a.isRestricted(t);{let e;if(!t.deleted&&!h&&!u){const s=i.a.getMediaFromMessage(t),n=new Set(["video","gif","round"]);if(s&&("photo"===s._||n.has(s.type))){const i=r.a.choosePhotoSize(s,20,20);if("photoSizeEmpty"!==i._&&(e=document.createElement("div"),e.classList.add("dialog-subtitle-media"),"round"===s.type&&e.classList.add("is-round"),Ps({photo:s,message:t,container:e,withoutPreloader:!0,size:i,loadPromises:l}),n.has(s.type))){const t=document.createElement("span");t.classList.add("tgico-play"),e.append(t)}}}const c=!!e&&!!(null==t?void 0:t.message);let d;if(d=n&&t.message?i.a.wrapMessageForReply(t,void 0,void 0,!1,n,c):h?i.a.wrapMessageForReply(h):t.deleted?document.createDocumentFragment():i.a.wrapMessageForReply(t,void 0,void 0,!1,void 0,c),e&&d.prepend(e),Object(k.a)(s.lastMessageSpan,d),h){const e=document.createElement("b");e.classList.add("danger"),e.append(Object(T.d)("Draft"),": "),s.lastMessageSpan.prepend(e)}else if(p.isAnyChat()&&p!==t.fromId&&!t.action){const e=o.a.getPeer(t.fromId);if(e&&e.id){const i=document.createElement("b");e.id===a.a.myId?i.append(Object(T.d)("FromYou")):i.append(new wt.a({peerId:t.fromId,onlyFirstName:!0}).element),i.append(": "),s.lastMessageSpan.prepend(i)}}}if(!t.deleted||h){const e=h?Math.max(h.date,t.date||0):t.date;Object(k.a)(s.lastTimeSpan,Object(ne.c)(new Date(1e3*e)))}else s.lastTimeSpan.textContent="";null!==d&&(d?this.setUnreadMessages(e,s,c):s.listEl.dataset.mid=t.mid)}setUnreadMessages(e,t=this.getDialogDom(e.peerId),s=!1){var n;if(!t)return;if(!s){const s=Bt.a.isPeerLocalMuted(e.peerId,!0);s!==t.listEl.classList.contains("is-muted")&&Object(is.a)(t.listEl,"is-muted",s,200)}let o;if("draftMessage"!==(null===(n=e.draft)||void 0===n?void 0:n._)){const t=i.a.getMessageByPeer(e.peerId,e.top_message);!t.deleted&&t.pFlags.out&&t.peerId!==a.a.myId&&(o=t)}!function(e,t,s){let i;if((null==t?void 0:t.pFlags.out)&&(i=t.pFlags.is_outgoing?"sending":t.pFlags.unread?"check":"checks"),!i)return void(e.textContent="");const n="tgico-"+i,a=e.lastElementChild;if(a&&a.classList.contains(n))return;const o=document.createElement("i");o.classList.add("sending-status-icon",n),e.append(o),a&&a.remove()}(t.statusSpan,o);const r=i.a.filtersStorage.getFilter(this.filterId);let l;l=r?-1!==r.pinnedPeerIds.indexOf(e.peerId):!!e.pFlags.pinned;const c=i.a.isDialogUnread(e),d=l||c,h=Object(ms.a)(t.unreadBadge);d&&!h&&t.subtitleEl.append(t.unreadBadge);const p=e.unread_mentions_count&&(e.unread_mentions_count>1||e.unread_count>1),u=t.mentionsBadge&&Object(ms.a)(t.mentionsBadge);p&&(t.mentionsBadge||(t.mentionsBadge=document.createElement("div"),t.mentionsBadge.className="dialog-subtitle-badge badge badge-24 mention mention-badge",t.mentionsBadge.innerText="@",t.subtitleEl.insertBefore(t.mentionsBadge,t.lastMessageSpan.nextSibling)));const g=s?0:200;if(Object(is.a)(t.unreadBadge,"is-visible",d,g,d?void 0:()=>{t.unreadBadge.remove()},h?0:2),t.mentionsBadge&&Object(is.a)(t.mentionsBadge,"is-visible",p,g,p?void 0:()=>{t.mentionsBadge.remove(),delete t.mentionsBadge},u?0:2),!d)return;l?t.unreadBadge.classList.add("tgico-chatspinned","tgico"):t.unreadBadge.classList.remove("tgico-chatspinned","tgico");let m=!0,b=!1;e.unread_mentions_count&&1===e.unread_count?(t.unreadBadge.innerText="@",b=!0):c?t.unreadBadge.innerText=""+(e.unread_count||" "):(t.unreadBadge.innerText="",m=!1),t.unreadBadge.classList.toggle("unread",m),t.unreadBadge.classList.toggle("mention",b)}getDialogDom(e){const t=this.sortedList.get(e);return null==t?void 0:t.dom}getDialog(e){if("object"!=typeof e){const t=i.a.getDialogOnly(e);if(!t){const t=e||Me.c;return{peerId:t,peer:o.a.getOutputPeer(t),pFlags:{}}}return t}return e}setCallStatus(e,t){let{callIcon:s,listEl:i}=e;if(!s&&t){const{canvas:t,startAnimation:n}=e.callIcon=s=Tc(i.classList.contains("active"));t.classList.add("dialog-group-call-icon"),i.append(t),n()}s&&Object(is.a)(e.callIcon.canvas,"is-visible",t,200,t?void 0:()=>{e.callIcon.canvas.remove(),e.callIcon=void 0},t?2:0)}addListDialog(e){const t=this.getDialog(e.dialog);e.autonomous=!1;const s=this.addDialogNew(e);if(s){const{peerId:i}=t;Bt.a.isPeerLocalMuted(i,!0)&&s.dom.listEl.classList.add("is-muted"),i.isUser()||this.processDialogForCallStatus(t,s.dom),this.setLastMessage(t,void 0,s.dom,void 0,e.loadPromises,e.isBatch,!0)}return s}processDialogForCallStatus(e,t){if(!hr)return;if(t||(t=this.getDialogDom(e.peerId)),!t)return;const s=G.a.getChat(e.peerId.toChatId());this.setCallStatus(t,!(!s.pFlags.call_active||!s.pFlags.call_not_empty))}addDialogAndSetLastMessage(e){const{peerId:t,message:s,query:n}=e,a=jc.addDialogNew(Object.assign(Object.assign(Object.assign({},e),i.a.getMessageSenderPeerIdOrName(s)),{dialog:this.getDialog(t)}));return this.setLastMessage(a.dialog,s,a.dom,n),s.peerId!==t&&(a.dom.listEl.dataset.peerId=""+s.peerId),a}addDialogNew(e){return this.addDialog(e.dialog,e.container,e.drawStatus,e.rippleEnabled,e.onlyFirstName,e.meAsSaved,e.append,e.avatarSize,e.autonomous,e.lazyLoadQueue,e.loadPromises,e.fromName)}addDialog(e,t,s=!0,i=!0,n=!1,o=!0,r=!0,l=54,c=!!t,d,h,p){var u,g;const m=this.getDialog(e),b=m.peerId,v=new fc;if(v.classList.add("dialog-avatar","avatar-"+l),v.updateWithOptions({loadPromises:h,lazyLoadQueue:d,isDialog:!!o,peerId:b,peerTitle:p}),s&&b!==a.a.myId&&b.isUser()){"userStatusOnline"===(null===(u=E.a.getUser(b).status)||void 0===u?void 0:u._)&&this.setOnlineStatus(v,!0)}const f=document.createElement("div");f.classList.add("user-caption");const y=document.createElement("span");y.classList.add("user-title");const w=new wt.a({peerId:b,fromName:p,dialog:o,onlyFirstName:n,plainText:!1});y.append(w.element),y.classList.add("tgico"),y.append(...Kt(b));const S=document.createElement("span");S.classList.add("user-last-message"),S.setAttribute("dir","auto");const C=document.createElement("li");C.classList.add("chatlist-chat"),i&&Object(te.a)(C),C.append(v,f),C.dataset.peerId=""+b;const L=document.createElement("span");L.classList.add("message-status","sending-status");const I=document.createElement("span");I.classList.add("message-time");const M=document.createElement("div");M.className="dialog-subtitle-badge badge badge-24";const P=document.createElement("p");P.classList.add("dialog-title");const k=document.createElement("span");k.classList.add("dialog-title-details"),k.append(L,I),P.append(y,k);const T=document.createElement("p");T.classList.add("dialog-subtitle"),T.append(S),f.append(P,T);const x={avatarEl:v,captionDiv:f,titleSpan:w.element,titleSpanContainer:y,statusSpan:L,lastTimeSpan:I,unreadBadge:M,lastMessageSpan:S,containerEl:C,listEl:C,subtitleEl:T};if(t){t[r?"append":"prepend"](C)}return c||(C.dialogDom=x,(null===(g=nc.chat)||void 0===g?void 0:g.peerId)===b&&this.setDialogActive(C,!0)),{dom:x,dialog:m}}setTyping(e){const t=this.getDialogDom(e.peerId);if(!t)return;const s=t.lastMessageSpan.querySelector(".peer-typing-container"),i=nc.getPeerTyping(e.peerId,s);!s&&i&&(Object(k.a)(t.lastMessageSpan,i),t.lastMessageSpan.classList.add("user-typing"))}unsetTyping(e){const t=this.getDialogDom(e.peerId);t&&(t.lastMessageSpan.classList.remove("user-typing"),this.setLastMessage(e,null,t,void 0,void 0,void 0,null))}}const jc=new Oc;le.a.appDialogsManager=jc;var _c=t.default=jc},194:function(e,t,s){"undefined"!=typeof self&&self,e.exports=function(e){var t={};function s(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,s),n.l=!0,n.exports}return s.m=e,s.c=t,s.d=function(e,t,i){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)s.d(i,n,function(t){return e[t]}.bind(null,n));return i},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=0)}([function(e,t,s){"use strict";(function(t){var s=t.AudioContext||t.webkitAudioContext,i=function(e){if(!i.isRecordingSupported())throw new Error("Recording is not supported in this browser");e||(e={}),this.state="inactive",this.config=Object.assign({bufferLength:4096,encoderApplication:2049,encoderFrameSize:20,encoderPath:"encoderWorker.min.js",encoderSampleRate:48e3,maxFramesPerPage:40,mediaTrackConstraints:!0,monitorGain:0,numberOfChannels:1,recordingGain:1,resampleQuality:3,streamPages:!1,reuseWorker:!1,wavBitDepth:16},e),this.encodedSamplePosition=0};i.isRecordingSupported=function(){return s&&t.navigator&&t.navigator.mediaDevices&&t.navigator.mediaDevices.getUserMedia&&t.WebAssembly},i.prototype.clearStream=function(){this.stream&&(this.stream.getTracks?this.stream.getTracks().forEach((function(e){e.stop()})):this.stream.stop(),delete this.stream),this.audioContext&&this.closeAudioContext&&(this.audioContext.close(),delete this.audioContext)},i.prototype.encodeBuffers=function(e){if("recording"===this.state){for(var t=[],s=0;s<e.numberOfChannels;s++)t[s]=e.getChannelData(s);this.encoder.postMessage({command:"encode",buffers:t})}},i.prototype.initAudioContext=function(e){return e&&e.context?(this.audioContext=e.context,this.closeAudioContext=!1):(this.audioContext=new s,this.closeAudioContext=!0),this.audioContext},i.prototype.initAudioGraph=function(){this.encodeBuffers=function(){delete this.encodeBuffers},this.scriptProcessorNode=this.audioContext.createScriptProcessor(this.config.bufferLength,this.config.numberOfChannels,this.config.numberOfChannels),this.scriptProcessorNode.connect(this.audioContext.destination),this.scriptProcessorNode.onaudioprocess=e=>{this.encodeBuffers(e.inputBuffer)},this.monitorGainNode=this.audioContext.createGain(),this.setMonitorGain(this.config.monitorGain),this.monitorGainNode.connect(this.audioContext.destination),this.recordingGainNode=this.audioContext.createGain(),this.setRecordingGain(this.config.recordingGain),this.recordingGainNode.connect(this.scriptProcessorNode)},i.prototype.initSourceNode=function(e){return e&&e.context?t.Promise.resolve(e):t.navigator.mediaDevices.getUserMedia({audio:this.config.mediaTrackConstraints}).then(e=>(this.stream=e,this.audioContext.createMediaStreamSource(e)))},i.prototype.loadWorker=function(){this.encoder||(this.encoder=new t.Worker(this.config.encoderPath))},i.prototype.initWorker=function(){var e=(this.config.streamPages?this.streamPage:this.storePage).bind(this);return this.recordedPages=[],this.totalLength=0,this.loadWorker(),new Promise((t,s)=>{var i=s=>{switch(s.data.message){case"ready":t();break;case"page":this.encodedSamplePosition=s.data.samplePosition,e(s.data.page);break;case"done":this.encoder.removeEventListener("message",i),this.finish()}};this.encoder.addEventListener("message",i),this.encoder.postMessage(Object.assign({command:"init",originalSampleRate:this.audioContext.sampleRate,wavSampleRate:this.audioContext.sampleRate},this.config))})},i.prototype.pause=function(e){if("recording"===this.state){if(this.state="paused",e&&this.config.streamPages){var t=this.encoder;return new Promise((e,s)=>{var i=s=>{"flushed"===s.data.message&&(t.removeEventListener("message",i),this.onpause(),e())};t.addEventListener("message",i),t.postMessage({command:"flush"})})}return this.onpause(),Promise.resolve()}},i.prototype.resume=function(){"paused"===this.state&&(this.state="recording",this.onresume())},i.prototype.setRecordingGain=function(e){this.config.recordingGain=e,this.recordingGainNode&&this.audioContext&&this.recordingGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},i.prototype.setMonitorGain=function(e){this.config.monitorGain=e,this.monitorGainNode&&this.audioContext&&this.monitorGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},i.prototype.start=function(e){if("inactive"===this.state)return this.initAudioContext(e),this.initAudioGraph(),this.encodedSamplePosition=0,this.initWorker().then(()=>this.initSourceNode(e)).then(e=>{this.sourceNode=e,this.state="recording",this.onstart(),this.encoder.postMessage({command:"getHeaderPages"}),this.sourceNode.connect(this.monitorGainNode),this.sourceNode.connect(this.recordingGainNode)})},i.prototype.stop=function(){if("inactive"!==this.state){this.state="inactive",this.monitorGainNode.disconnect(),this.scriptProcessorNode.disconnect(),this.recordingGainNode.disconnect(),this.sourceNode.disconnect(),this.clearStream();var e=this.encoder;return new Promise(t=>{var s=i=>{"done"===i.data.message&&(e.removeEventListener("message",s),t())};e.addEventListener("message",s),e.postMessage({command:"done"}),this.config.reuseWorker||e.postMessage({command:"close"})})}return Promise.resolve()},i.prototype.destroyWorker=function(){"inactive"===this.state&&this.encoder&&(this.encoder.postMessage({command:"close"}),delete this.encoder)},i.prototype.storePage=function(e){this.recordedPages.push(e),this.totalLength+=e.length},i.prototype.streamPage=function(e){this.ondataavailable(e)},i.prototype.finish=function(){if(!this.config.streamPages){var e=new Uint8Array(this.totalLength);this.recordedPages.reduce((function(t,s){return e.set(s,t),t+s.length}),0),this.ondataavailable(e)}this.onstop(),this.config.reuseWorker||delete this.encoder},i.prototype.ondataavailable=function(){},i.prototype.onpause=function(){},i.prototype.onresume=function(){},i.prototype.onstart=function(){},i.prototype.onstop=function(){},e.exports=i}).call(this,s(1))},function(e,t){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch(e){"object"==typeof window&&(s=window)}e.exports=s}])},67:function(e,t,s){"use strict";s.d(t,"b",(function(){return c})),s.d(t,"a",(function(){return d}));var i=s(14),n=s(4),a=s(102),o=s(93),r=s(33);class l{constructor(e,t="",s=document.createElement("div")){this.el=e,this.container=s,this.onScrollMeasure=0,this.lastScrollPosition=0,this.lastScrollDirection=0,this.isHeavyAnimationInProgress=!1,this.needCheckAfterAnimation=!1,this.onScroll=()=>{if(this.isHeavyAnimationInProgress)return this.cancelMeasure(),void(this.needCheckAfterAnimation=!0);(this.onScrolledTop||this.onScrolledBottom||this.splitUp||this.onAdditionalScroll)&&(this.onScrollMeasure||(this.onScrollMeasure=window.requestAnimationFrame(()=>{this.onScrollMeasure=0;const e=this.container[this.scrollProperty];this.lastScrollDirection=this.lastScrollPosition===e?0:this.lastScrollPosition<e?1:-1,this.lastScrollPosition=e,this.onAdditionalScroll&&this.onAdditionalScroll(),this.checkForTriggers&&this.checkForTriggers()})))},this.container.classList.add("scrollable"),this.log=Object(n.b)("SCROLL"+(t?"-"+t:""),n.a.Error),e&&(Array.from(e.children).forEach(e=>this.container.append(e)),e.append(this.container))}addScrollListener(){this.addedScrollListener||(this.addedScrollListener=!0,this.container.addEventListener("scroll",this.onScroll,{passive:!0,capture:!0}))}removeScrollListener(){this.addedScrollListener&&(this.addedScrollListener=!1,this.container.removeEventListener("scroll",this.onScroll,{capture:!0}))}setListeners(){this.removeHeavyAnimationListener||(window.addEventListener("resize",this.onScroll,{passive:!0}),this.addScrollListener(),this.removeHeavyAnimationListener=Object(o.a)(()=>{this.isHeavyAnimationInProgress=!0,this.onScrollMeasure&&(this.cancelMeasure(),this.needCheckAfterAnimation=!0)},()=>{this.isHeavyAnimationInProgress=!1,this.needCheckAfterAnimation&&(this.onScroll(),this.needCheckAfterAnimation=!1)}))}removeListeners(){this.removeHeavyAnimationListener&&(window.removeEventListener("resize",this.onScroll),this.removeScrollListener(),this.removeHeavyAnimationListener(),this.removeHeavyAnimationListener=void 0)}append(e){this.container.append(e)}scrollIntoViewNew(e){return Object(a.b)(Object.assign(Object.assign({},e),{container:this.container}))}cancelMeasure(){this.onScrollMeasure&&(window.cancelAnimationFrame(this.onScrollMeasure),this.onScrollMeasure=0)}}class c extends l{constructor(e,t="",s=300,i){super(e,t),this.onScrollOffset=s,this.loadedAll={top:!0,bottom:!1},this.checkForTriggers=()=>{if(!this.onScrolledTop&&!this.onScrolledBottom)return;if(this.isHeavyAnimationInProgress)return void this.onScroll();const e=this.container.scrollHeight;if(!e)return;const t=e-this.container.clientHeight,s=this.lastScrollPosition;this.onScrolledTop&&s<=this.onScrollOffset&&this.lastScrollDirection<=0&&this.onScrolledTop(),this.onScrolledBottom&&t-s<=this.onScrollOffset&&this.lastScrollDirection>=0&&this.onScrolledBottom()},this.container.classList.add("scrollable-y"),this.setListeners(),this.scrollProperty="scrollTop"}setVirtualContainer(e){this.splitUp=e,this.log("setVirtualContainer:",e,this)}prepend(...e){(this.splitUp||this.padding||this.container).prepend(...e)}append(...e){(this.splitUp||this.padding||this.container).append(...e)}getDistanceToEnd(){return this.scrollHeight-Math.round(this.scrollTop+this.container.offsetHeight)}get isScrolledDown(){return this.getDistanceToEnd()<=1}set scrollTop(e){this.container.scrollTop=e}get scrollTop(){return this.container.scrollTop}setScrollTopSilently(e){this.lastScrollPosition=e,this.ignoreNextScrollEvent(),this.scrollTop=e}ignoreNextScrollEvent(){this.removeHeavyAnimationListener&&(this.removeScrollListener(),this.container.addEventListener("scroll",e=>{Object(r.a)(e),this.addScrollListener()},{capture:!0,passive:!1,once:!0}))}get scrollHeight(){return this.container.scrollHeight}}class d extends l{constructor(e,t="",s=300,n=15,a=document.createElement("div")){if(super(e,t,a),this.onScrollOffset=s,this.splitCount=n,this.container=a,this.container.classList.add("scrollable-x"),!i.a){const e=e=>{!e.deltaX&&this.container.scrollWidth>this.container.clientWidth&&(this.container.scrollLeft+=e.deltaY/4,Object(r.a)(e))};this.container.addEventListener("wheel",e,{passive:!1})}this.scrollProperty="scrollLeft"}}},70:function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));var i=s(35),n=s(77),a=s(7),o=s(45);class r{constructor(e={}){const t=this.label=document.createElement("label");t.classList.add("checkbox-field"),e.restriction&&t.classList.add("checkbox-field-restriction"),e.round&&t.classList.add("checkbox-field-round"),e.disabled&&this.toggleDisability(!0);const s=this.input=document.createElement("input");let r;if(s.classList.add("checkbox-field-input"),s.type="checkbox",e.name&&(s.id="input-"+e.name),e.checked&&(s.checked=!0),e.stateKey&&i.c.getState().then(t=>{const n=Object(o.a)(t,e.stateKey);let a;a=e.stateValues?1===e.stateValues.indexOf(n):n,this.setValueSilently(a),s.addEventListener("change",()=>{let t;t=e.stateValues?e.stateValues[s.checked?1:0]:s.checked,i.c.setByKey(e.stateKey,t)})}),e.text?(r=this.span=document.createElement("span"),r.classList.add("checkbox-caption"),Object(a.b)(r,e.text,e.textArgs)):t.classList.add("checkbox-without-caption"),t.append(s),e.toggle){t.classList.add("checkbox-field-toggle");const e=document.createElement("div");e.classList.add("checkbox-toggle"),t.append(e)}else{const e=document.createElement("div");e.classList.add("checkbox-box");const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.classList.add("checkbox-box-check"),s.setAttributeNS(null,"viewBox","0 0 24 24");const i=document.createElementNS("http://www.w3.org/2000/svg","use");i.setAttributeNS(null,"href","#check"),i.setAttributeNS(null,"x","-1"),s.append(i);const n=document.createElement("div");n.classList.add("checkbox-box-background");const a=document.createElement("div");a.classList.add("checkbox-box-border"),e.append(a,n,s),t.append(e)}r&&t.append(r),e.withRipple?(t.classList.add("checkbox-ripple","hover-effect"),Object(n.a)(t,void 0,void 0,!0)):e.withHover&&t.classList.add("hover-effect")}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e);const t=new Event("change",{bubbles:!0,cancelable:!0});this.input.dispatchEvent(t)}setValueSilently(e){this.input.checked=e}toggleDisability(e){return this.label.classList.toggle("checkbox-disabled",e),()=>this.toggleDisability(!e)}}},78:function(e,t,s){"use strict";function i(e,t){return t?e.forEach(e=>e.setAttribute("disabled","true")):e.forEach(e=>e.removeAttribute("disabled")),()=>i(e,!t)}s.d(t,"a",(function(){return i}))},85:function(e,t,s){"use strict";function i(e,t){return e.closest(t)}s.d(t,"a",(function(){return i}))},94:function(e,t,s){"use strict";var i=s(1),n=s(8);const a=new class{getState(){return n.a.invokeApi("account.getPassword").then(e=>e)}updateSettings(e={}){return this.getState().then(t=>{let s,i;const a={password:null,new_settings:{_:"account.passwordInputSettings",hint:e.hint,email:e.email}};s=e.currentPassword?n.a.invokeCrypto("computeSRP",e.currentPassword,t,!1):Promise.resolve({_:"inputCheckPasswordEmpty"});const o=t.new_algo,r=new Uint8Array(o.salt1.length+32);return function(e){if(!crypto||!("getRandomValues"in crypto))throw new Error("NO_SECURE_RANDOM");crypto.getRandomValues(e)}(r),r.set(o.salt1,0),o.salt1=r,i=e.newPassword?n.a.invokeCrypto("computeSRP",e.newPassword,t,!0):Promise.resolve(new Uint8Array),Promise.all([s,i]).then(e=>(a.password=e[0],a.new_settings.new_algo=o,a.new_settings.new_password_hash=e[1],n.a.invokeApi("account.updatePasswordSettings",a)))})}check(e,t,s={}){return n.a.invokeCrypto("computeSRP",e,t,!1).then(e=>n.a.invokeApi("auth.checkPassword",{password:e},s).then(e=>("auth.authorization"===e._&&n.a.setUser(e.user),e)))}confirmPasswordEmail(e){return n.a.invokeApi("account.confirmPasswordEmail",{code:e})}resendPasswordEmail(){return n.a.invokeApi("account.resendPasswordEmail")}cancelPasswordEmail(){return n.a.invokeApi("account.cancelPasswordEmail")}};i.a.passwordManager=a;t.a=a}}]);
//# sourceMappingURL=13.234dc6639cd6dd1f11ca.chunk.js.map