(()=>{var e,t,n={3626:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Lt,clear:()=>Ht,fetch:()=>Ot,save:()=>qt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Gn,addContact:()=>Ws,answerCallbackButton:()=>Ci,blockContact:()=>Za,checkChatUsername:()=>fa,checkPassword:()=>Ia,checkUsername:()=>za,clearDraft:()=>pn,clearPassword:()=>Aa,createChannel:()=>hn,createGroupCall:()=>Na,createGroupChat:()=>Cn,deleteChannel:()=>wn,deleteChat:()=>yn,deleteChatFolder:()=>kn,deleteChatMember:()=>Kn,deleteChatUser:()=>_n,deleteContact:()=>$s,deleteHistory:()=>fs,deleteMessages:()=>gs,deleteScheduledMessages:()=>ps,destroy:()=>Jt,discardGroupCall:()=>Ua,disconnect:()=>Qt,downloadMedia:()=>en,editChatFolder:()=>Mn,editChatPhoto:()=>vn,editExportedChatInvite:()=>$n,editGroupCallParticipant:()=>Ea,editGroupCallTitle:()=>Da,editMessage:()=>rs,exportChatInvite:()=>Jn,exportGroupCallInvite:()=>Ta,faveSticker:()=>ta,fetchAnimatedEmojiEffects:()=>aa,fetchAnimatedEmojis:()=>sa,fetchAppConfig:()=>_i,fetchAuthorizations:()=>ei,fetchBlockedContacts:()=>Xa,fetchChat:()=>ln,fetchChatFolders:()=>Sn,fetchChats:()=>rn,fetchCommonChats:()=>qs,fetchContactList:()=>Ks,fetchContentSettings:()=>hi,fetchCountryList:()=>bi,fetchCurrentUser:()=>sn,fetchEmojiKeywords:()=>ua,fetchExportedChatInvites:()=>Wn,fetchFavoriteStickers:()=>Ys,fetchFeaturedStickers:()=>ea,fetchFullChat:()=>cn,fetchFullUser:()=>Os,fetchGroupCallParticipants:()=>Ba,fetchGroupsForDiscussion:()=>Ln,fetchInlineBot:()=>Ii,fetchInlineBotResults:()=>Ai,fetchLangPack:()=>ci,fetchLangStrings:()=>di,fetchLanguages:()=>ri,fetchMembers:()=>Fn,fetchMessage:()=>ss,fetchMessageReactions:()=>Vi,fetchMessageReactionsList:()=>Ni,fetchMessages:()=>ns,fetchNearestCountry:()=>Hs,fetchNotificationExceptions:()=>si,fetchNotificationSettings:()=>ai,fetchPinnedMessages:()=>Us,fetchPrivacySettings:()=>li,fetchProfilePhotos:()=>Js,fetchRecentStickers:()=>Zs,fetchRecommendedChatFolders:()=>Pn,fetchSavedGifs:()=>oa,fetchScheduledHistory:()=>Ms,fetchSeenBy:()=>Es,fetchSendAs:()=>Ds,fetchSponsoredMessages:()=>Bs,fetchStickerSets:()=>Xs,fetchStickers:()=>na,fetchStickersForEmoji:()=>la,fetchTopInlineBots:()=>vi,fetchTopUsers:()=>Gs,fetchUsers:()=>zs,fetchWallpapers:()=>Ja,fetchWebPagePreview:()=>vs,findFirstMessageIdAfterDate:()=>Ps,forwardMessages:()=>Ss,getAvailableReactions:()=>Bi,getChatByUsername:()=>Un,getGroupCall:()=>Ra,getPasswordInfo:()=>Ca,getPaymentForm:()=>Ui,getReceipt:()=>Ei,importChatInvite:()=>Qn,installStickerSet:()=>ra,joinChannel:()=>mn,joinGroupCall:()=>Va,joinGroupCallPresentation:()=>Fa,leaveChannel:()=>bn,leaveGroupCall:()=>xa,leaveGroupCallPresentation:()=>Oa,loadPollOptionResults:()=>As,markMessageListRead:()=>_s,markMessagesRead:()=>ys,migrateChat:()=>qn,openChatByInvite:()=>Hn,pinMessage:()=>ls,provideAuthCode:()=>Dt,provideAuthPassword:()=>Tt,provideAuthPhoneNumber:()=>Et,provideAuthRegistration:()=>Bt,provideRecoveryEmailCode:()=>Ma,registerDevice:()=>ui,reportMessages:()=>hs,requestChatUpdate:()=>un,requestThreadInfoUpdate:()=>bs,rescheduleMessage:()=>cs,restartAuth:()=>xt,restartAuthWithQr:()=>Vt,saveDefaultSendAs:()=>Ts,saveDraft:()=>gn,searchChats:()=>dn,searchGifs:()=>da,searchMessagesGlobal:()=>Cs,searchMessagesLocal:()=>ws,searchStickers:()=>ia,sendEmojiInteraction:()=>Ti,sendInlineBotResult:()=>Si,sendMessage:()=>is,sendMessageAction:()=>ms,sendPaymentForm:()=>Ri,sendPollVote:()=>Is,sendReaction:()=>xi,sendScheduledMessages:()=>ks,sendWatchingEmojiInteraction:()=>Di,setChatEnabledReactions:()=>Xn,setChatUsername:()=>ha,setDefaultReaction:()=>Fi,setDiscussionGroup:()=>On,setPrivacySettings:()=>pi,startBot:()=>Pi,terminateAllAuthorizations:()=>ni,terminateAuthorization:()=>ti,toggleChatArchived:()=>An,toggleChatPinned:()=>In,toggleDialogUnread:()=>Rn,toggleGroupCallStartSubscription:()=>La,toggleIsProtected:()=>Zn,togglePreHistoryHidden:()=>En,toggleSignatures:()=>Nn,unblockContact:()=>Ya,uninstallStickerSet:()=>ca,unpinAllMessages:()=>us,unregisterDevice:()=>gi,updateChatAbout:()=>Vn,updateChatAdmin:()=>Bn,updateChatDefaultBannedRights:()=>Dn,updateChatMemberBannedRights:()=>Tn,updateChatMutedState:()=>fn,updateChatTitle:()=>xn,updateContact:()=>js,updateContactSignUpNotification:()=>ii,updateContentSettings:()=>mi,updateIsOnline:()=>fi,updateNotificationSettings:()=>oi,updatePassword:()=>Sa,updatePrivateLink:()=>ma,updateProfile:()=>Ka,updateProfilePhoto:()=>Wa,updateRecoveryEmail:()=>Pa,updateUsername:()=>ja,uploadProfilePhoto:()=>$a,uploadWallpaper:()=>Qa,validateRequestedInfo:()=>ki,viewSponsoredMessage:()=>xs});const i=("undefined"!=typeof window&&window.innerHeight,Math.round(425)),o=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),r=new Set(["image/png","image/gif","image/jpeg"]),c=new Set(["video/mp4"]),d=(new Set([...r,...c]),new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),"777000");let l,u;var g=n(3522);function p(e,t){return e.reduce(((e,n)=>(e[n[t]]=n,e)),{})}function f(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}var h=n(8960);function m(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function _(e){const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:a,classType:i,getBytes:o,...r}=e;return r}function y(e,t,n){return''.replace("{{path}}",function(e){let t="M";const n=e.length;for(let s=0;s=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[n-128-64]:(n>=128?t+=",":n>=64&&(t+="-"),t+=String(63&n))}return t+="z",t}(e)).replace("{{width}}",String(t)).replace("{{height}}",String(n))}const b={w:100,h:100};function w(e,t){if(!e||!e.length)return;const n=e.find((e=>e instanceof g.Api.PhotoStrippedSize));if(!n)return;const s=e.filter((e=>e instanceof g.Api.PhotoSize)),{w:a,h:i}=s.length?s[s.length-1]:b,{bytes:o}=n;return{dataUri:m(t&&"image/jpeg"!==t?o:(0,h.strippedPhotoToJpg)(o),void 0,t),width:a,height:i}}function C(e){const t=e.sizes.filter((e=>e instanceof g.Api.PhotoSize||e instanceof g.Api.PhotoSizeProgressive)).map(v);return{id:String(e.id),thumbnail:w(e.sizes),sizes:t}}function v(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}const I={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{},webDocuments:{}},A="application/x-tgsticker";function S(e){if(e instanceof g.Api.DocumentEmpty)return;const t=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeSticker)),n=e.mimeType===A&&e.attributes.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(!t&&!n)return;const s=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeImageSize)),a=t&&t.stickerset instanceof g.Api.InputStickerSetID?t.stickerset:void 0,i=null==t?void 0:t.alt,o=e.mimeType===A,r=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoCachedSize)),c=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoPathSize)),d=r?function(e){const{w:t,h:n,bytes:s}=e;return{dataUri:m(s,void 0,"image/webp"),width:t,height:n}}(r):c&&s?function(e,t){const{w:n,h:s}=t;return{dataUri:`data:image/svg+xml;utf8,${y(e.bytes,n,s)}`,width:n,height:s}}(c,s):void 0,{w:l,h:u}=r||s||{};return{id:String(e.id),stickerSetId:a?String(a.id):"MEMOJI_STICKER",stickerSetAccessHash:a&&String(a.accessHash),emoji:i,isAnimated:o,width:l,height:u,thumbnail:d}}function P(e){const{archived:t,animated:n,installedDate:s,id:a,accessHash:i,title:o,thumbs:r,count:c,shortName:d}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(a),accessHash:String(i),title:o,hasThumbnail:Boolean(null==r?void 0:r.length),count:c,shortName:d}}function M(e){const t=P(e.set),n=e instanceof g.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach((e=>{if(e instanceof g.Api.Document){const n=S(e);n&&(t.covers.push(n),I.documents[String(e.id)]=e)}})),t}function k(e,t){let n=0;const s=new Array(t),a=e.length/t,i=e[0],o=e[e.length-1];for(let l=0;l{e instanceof g.Api.User&&e.photo?H(e):(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&e.photo&&function(e,t=!1){const n=V(e.id,e instanceof g.Api.Chat?"chat":"channel");t&&I.chats[n]||(I.chats[n]=e)}(e)}))}function K(e){return String.fromCharCode(...e)}function z(e){return F.from(e,"binary")}function j(e){return"number"==typeof e?function(e){return e>0?"user":e<=-1e9?"channel":"chat"}(e):e.startsWith("-")?e.length>=11?"channel":"chat":"user"}function W(e){const t=j(e);return"user"===t?new g.Api.PeerUser({userId:le(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:le(e,"channel")}):new g.Api.PeerChat({chatId:le(e,"chat")})}function $(e,t){const n=j(e);return"user"===n?new g.Api.InputPeerUser({userId:le(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:le(e,"channel"),accessHash:U()(t)}):new g.Api.InputPeerChat({chatId:le(e,"chat")})}function J(e){const t=j(e);let n;var s;if("user"===t){if(n=null===(s=I.users[e])||void 0===s?void 0:s.accessHash,!n)return}else if("channel"===t){var a;if(n=null===(a=I.chats[e])||void 0===a?void 0:a.accessHash,!n)return}return $(e,String(n))}function Q(e,t){const n=j(e);return"user"===n?new g.Api.InputUser({userId:le(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputChannel({channelId:le(e,"channel"),accessHash:U()(t)}):le(e,"chat")}function X(e,t){return new g.Api.InputStickerSetID({id:U()(e),accessHash:U()(t)})}function Z(e){const t=I.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function Y(e){const t=Z(e);if(t)return new g.Api.InputMediaDocument({id:t})}function ee(){return(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(8),!0,!0)}function te(e,t,n){return new g.Api.Message({id:e,peerId:W(t),fromId:W(t),media:n.media})}function ne(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?I.users[i]:void 0;switch(t){case D.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case D.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case D.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case D.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case D.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case D.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case D.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case D.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case D.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case D.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case D.MentionName:return new g.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new g.Api.InputUser({userId:U()(i),accessHash:o.accessHash})});default:return new g.Api.MessageEntityUnknown({offset:n,length:s})}}function se(e){const{media:t}=e;return!!t&&(t instanceof g.Api.MessageMediaPhoto||t instanceof g.Api.MessageMediaDocument||t instanceof g.Api.MessageMediaWebPage&&t.webpage instanceof g.Api.WebPage&&(t.webpage.photo instanceof g.Api.Photo||t.webpage.document instanceof g.Api.Document&&t.webpage.document.mimeType.startsWith("video")))}function ae({phone:e,firstName:t,lastName:n}){return new g.Api.InputPhoneContact({clientId:U()(1),phone:e,firstName:t,lastName:n})}function ie(e,t=0){return new g.Api.ChatBannedRights({...e,untilDate:t})}function oe(e){return new g.Api.ChatAdminRights(e)}function re(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function ce(e){switch(e){case"phoneNumber":return new g.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new g.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new g.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new g.Api.InputPrivacyKeyForwards;case"chatInvite":return new g.Api.InputPrivacyKeyChatInvite}}function de(e){switch(e){case"spam":return new g.Api.InputReportReasonSpam;case"violence":return new g.Api.InputReportReasonViolence;case"childAbuse":return new g.Api.InputReportReasonChildAbuse;case"pornography":return new g.Api.InputReportReasonPornography;case"copyright":return new g.Api.InputReportReasonCopyright;case"fake":return new g.Api.InputReportReasonFake;case"geoIrrelevant":return new g.Api.InputReportReasonGeoIrrelevant;case"other":return new g.Api.InputReportReasonOther}}function le(e,t){return"number"==typeof e?U()(Math.abs(e)):"user"===t?U()(e):U()(e.slice(1))}function ue(e){return new g.Api.InputGroupCall({id:U()(e.id),accessHash:U()(e.accessHash)})}const ge="temp";let pe,fe=1e9;function he(e){const{fromId:t,message:n,entities:s,startParam:a,channelPost:i,chatInvite:o,chatInviteHash:r,randomId:c}=e,d=t?N(t):void 0,l=o?o instanceof g.Api.ChatInvite?o.title:o.chat instanceof g.Api.ChatEmpty?void 0:o.chat.title:void 0;return{randomId:K(c),isBot:!!t&&B(t),text:Ie(n,s),expiresAt:Math.round(Date.now()/1e3)+3e5,...d&&{chatId:d},...r&&{chatInviteHash:r},...o&&{chatInviteTitle:l},...a&&{startParam:a},...i&&{channelPostId:i}}}function me(e){const t=L(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return _e(t,e)}function _e(e,t){const n=t.fromId?N(t.fromId):void 0,s=t.peerId?N(t.peerId):void 0,a=!n&&e===pe,i=t.out&&!t.post||a&&!t.fwdFrom,o=ve(t),r=t.action&&function(e,t,n,s,a){if(e instanceof g.Api.MessageActionEmpty)return;let i,o,r,c;const d=[];let l,u="other";const p="users"in e?e.users&&e.users.map((e=>V(e,"user"))):"userId"in e&&[V(e.userId,"user")]||[];let f;if(e instanceof g.Api.MessageActionChatCreate)c="Notification.CreatedChatWithTitle",d.push("%action_origin%",e.title),u="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(c="Channel.MessageTitleUpdated",d.push(e.title)):(c="Notification.ChangedGroupName",d.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?c="Channel.MessagePhotoUpdated":(c="Notification.ChangedGroupPhoto",d.push("%action_origin%"));else if(e instanceof g.Api.MessageActionChatDeletePhoto)c=s?"Channel.MessagePhotoRemoved":"Group.MessagePhotoRemoved";else if(e instanceof g.Api.MessageActionChatAddUser)!t||p.includes(t)?(c="Notification.JoinedChat",d.push("%target_user%")):(c="Notification.Invited",d.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||p.includes(t)?(c="Notification.LeftChat",d.push("%target_user%")):(c="Notification.Kicked",d.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)c="Notification.JoinedGroupByLink",d.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)c="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)f=N(e),c="Migrated to %target_chat%",d.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)f=N(e),c="Migrated from %target_chat%",d.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)c="Chat.Service.Group.UpdatedPinnedMessage1",d.push("%action_origin%","%message%");else if(e instanceof g.Api.MessageActionHistoryClear)c="HistoryCleared",u="historyClear";else if(e instanceof g.Api.MessageActionPhoneCall){const t=Boolean(e.duration);if(c=[t?"ChatList.Service":"Chat",e.video?"VideoCall":"Call",a?t?"outgoing":"Outgoing":t?"incoming":"Incoming"].join("."),t){const t=Math.max(Math.round(e.duration/60),1);d.push(`${t} min${t>1?"s":""}`)}}else if(e instanceof g.Api.MessageActionInviteToGroupCall)c="Notification.VoiceChatInvitation",i={id:e.call.id.toString(),accessHash:e.call.accessHash.toString()},d.push("%action_origin%","%target_user%");else if(e instanceof g.Api.MessageActionContactSignUp)c="Notification.Joined",d.push("%action_origin%"),u="contactSignUp";else if(e instanceof g.Api.MessageActionPaymentSent)o=Number(e.totalAmount),r=e.currency,c="PaymentSuccessfullyPaid",n&&p.push(n),d.push("%payment_amount%","%target_user%","%product%");else if(e instanceof g.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);c="Notification.VoiceChatEnded",d.push(`${t} min${t>1?"s":""}`)}else c="Notification.VoiceChatStartedChannel",i={id:e.call.id.toString(),accessHash:e.call.accessHash.toString()};else e instanceof g.Api.MessageActionBotAllowed?(c="Chat.Service.BotPermissionAllowed",d.push(e.domain)):e instanceof g.Api.MessageActionCustomAction?c=e.message:e instanceof g.Api.MessageActionChatJoinedByRequest?(c="ChatService.UserJoinedGroupByRequest",d.push("%action_origin%")):c="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(q(e.photo),l=C(e.photo)),{text:c,type:u,targetUserIds:p,targetChatId:f,photo:l,amount:o,currency:r,translationValues:d,call:i}}(t.action,n,s,Boolean(t.post),i);r&&(o.action=r);const{replyToMsgId:c,replyToTopId:d,replyToPeerId:l}=t.replyTo||{},u=t.editDate&&!t.editHide,{inlineButtons:p,keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m}=function(e){const{id:t,replyMarkup:n,media:s}=e;if(!n)return s instanceof g.Api.MessageMediaWebPage&&s.webpage instanceof g.Api.WebPage&&"telegram_message"===s.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:s.webpage.url}]]}:void 0;if(!(n instanceof g.Api.ReplyKeyboardMarkup||n instanceof g.Api.ReplyInlineMarkup))return;const a=n.rows.map((({buttons:e})=>e.map((e=>{let n,a,{text:i}=e;return e instanceof g.Api.KeyboardButton?(n="command",a=i):e instanceof g.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof g.Api.KeyboardButtonCallback?(n="callback",a=K(e.data)):e instanceof g.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof g.Api.KeyboardButtonRequestPhone?n="requestSelfContact":e instanceof g.Api.KeyboardButtonBuy?(s instanceof g.Api.MessageMediaInvoice&&s.receiptMsgId&&(i="PaymentReceipt",a=s.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:i,messageId:t,value:a}}))));return{[n instanceof g.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a,...n instanceof g.Api.ReplyKeyboardMarkup&&{keyboardPlaceholder:n.placeholder,isKeyboardSingleUse:n.singleUse}}}(t)||{},_=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&N(e.savedFromPeer),s=e.fromId&&N(e.fromId);return{date:e.date,isChannelPost:Boolean(e.channelPost),channelPostId:e.channelPost,isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,a),{replies:y,mediaUnread:b,postAuthor:w}=t,v=t.groupedId&&String(t.groupedId),I=Boolean(v)&&!(o.document||o.audio),A=t.replyMarkup instanceof g.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:i,content:o,date:t.date,senderId:n||t.out&&t.post&&pe||e,views:t.views,isFromScheduled:t.fromScheduled,reactions:t.reactions&&ye(t.reactions),...c&&{replyToMessageId:c},...l&&{replyToChatId:N(l)},...d&&{replyToTopMessageId:d},..._&&{forwardInfo:_},...u&&{isEdited:u,editDate:t.editDate},...b&&{isMediaUnread:b},...t.mentioned&&b&&{hasUnreadMention:!0},...t.mentioned&&{isMentioned:!0},...v&&{groupedId:v,isInAlbum:I},inlineButtons:p,...f&&{keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m},...A&&{shouldHideKeyboardButtons:A},...t.viaBotId&&{viaBotId:V(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Be(y,t.id,e)},...w&&{adminTitle:w},...t.noforwards&&{isProtected:!0}}}function ye(e){const{recentReactons:t,results:n,canSeeList:s}=e;return{canSeeList:s,results:n.map(be),recentReactions:null==t?void 0:t.map(we)}}function be(e){const{chosen:t,count:n,reaction:s}=e;return{isChosen:t,count:n,reaction:s}}function we(e){const{userId:t,reaction:n}=e;return{userId:V(t,"user"),reaction:n}}function Ce(e){const{selectAnimation:t,staticIcon:n,reaction:s,title:a,inactive:i,aroundAnimation:o,centerIcon:r}=e;return{selectAnimation:Me(t),staticIcon:Me(n),aroundAnimation:o?Me(o):void 0,centerIcon:r?Me(r):void 0,reaction:s,title:a,isInactive:i}}function ve(e){var t;let n={};return e.media&&(n={...Se(e.media)}),!e.message||n.sticker||n.poll||n.contact||null!==(t=n.video)&&void 0!==t&&t.isRound||(n={...n,text:Ie(e.message,e.entities)}),n}function Ie(e,t){return null!=t&&t.some((e=>e instanceof g.Api.MessageEntitySpoiler))?{text:"The message is not supported on this version of Telegram."}:{text:e,...t&&{entities:t.map(Te)}}}function Ae(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?Ie(t,n):void 0,replyingToId:s,date:a}}function Se(e){if("ttlSeconds"in e&&e.ttlSeconds)return;const t=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document)return S(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(e instanceof g.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof g.Api.Photo)return C(e.photo)}(e);if(n)return{photo:n};const s=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document instanceof g.Api.Document&&e.document.mimeType.startsWith("video"))return Pe(e.document)}(e);if(s)return{video:s};const a=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||t.voice)return;const n=e.document.thumbs&&e.document.thumbs.filter((e=>e instanceof g.Api.PhotoSize)).map((e=>v(e)));return{id:String(e.document.id),fileName:Ee(e.document,"audio"),thumbnailSizes:n,...f(e.document,["size","mimeType"]),...f(t,["duration","performer","title"])}}(e);if(a)return{audio:a};const i=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||!t.voice)return;const{duration:n,waveform:s}=t;return{id:String(e.document.id),duration:n,waveform:s?Array.from(s):void 0}}(e);if(i)return{voice:i};const o=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document)return Me(e.document)}(e);if(o)return{document:o};const r=function(e){if(!(e instanceof g.Api.MessageMediaContact))return;const{firstName:t,lastName:n,phoneNumber:s,userId:a}=e;return{firstName:t,lastName:n,phoneNumber:s,userId:V(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return ke(e.poll,e.results)}(e);if(c)return{poll:c};const d=Ue(e);if(d)return{webPage:d};const l=function(e){if(e instanceof g.Api.MessageMediaInvoice)return function(e){const{description:t,title:n,photo:s,test:a,totalAmount:i,currency:o,receiptMsgId:r}=e;return{text:t,title:n,photoUrl:null==s?void 0:s.url,receiptMsgId:r,amount:Number(i),currency:o,isTest:a}}(e)}(e);return l?{invoice:l}:void 0}function Pe(e){if(e instanceof g.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:s,size:a,attributes:i}=e;if("video/quicktime"===n&&!self.isMovSupported)return;const o=i.find((e=>e instanceof g.Api.DocumentAttributeVideo));if(!o)return;const r=i.find((e=>e instanceof g.Api.DocumentAttributeAnimated)),{duration:c,w:d,h:l,supportsStreaming:u=!1,roundMessage:p=!1}=o;return{id:String(t),mimeType:n,duration:c,fileName:Ee(e,"video"),width:d,height:l,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function Me(e){if(!(e instanceof g.Api.Document))return;const{id:t,size:n,mimeType:s,date:a,thumbs:i,attributes:o}=e,d=i&&w(i);let l,u;const p=i&&i.find((e=>e instanceof g.Api.PhotoSize));if(p)if(u={width:p.w,height:p.h},r.has(s)){l="photo";const e=o.find((e=>e instanceof g.Api.DocumentAttributeImageSize));if(e){const{w:t,h:n}=e;u={width:t,height:n}}}else c.has(s)&&(l="video");return{id:String(t),size:n,mimeType:s,timestamp:a,fileName:Ee(e),thumbnail:d,mediaType:l,mediaSize:u}}function ke(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:K(e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:Re(t)}}function Re(e){const{results:t,totalVoters:n,recentVoters:s,solution:a,solutionEntities:i}=e,o=t&&t.map((({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:K(e),votersCount:s})));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>V(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(Te)}}}function Ue(e){if(!(e instanceof g.Api.MessageMediaWebPage&&e.webpage instanceof g.Api.WebPage))return;const{id:t,photo:n,document:s}=e.webpage;let a;return s instanceof g.Api.Document&&s.mimeType.startsWith("video/")&&(a=Pe(s)),{id:Number(t),...f(e.webpage,["url","displayUrl","type","siteName","title","description","duration"]),photo:n instanceof g.Api.Photo?C(n):void 0,document:!a&&s?Me(s):void 0,video:a}}function Ee(e,t="file"){const{mimeType:n,attributes:s}=e,a=s.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(a)return a.fileName;const i=n.split("/")[1];return`${t}${String(e.id)}.${i}`}function De(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function Te(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,...e instanceof g.Api.MessageEntityMentionName&&{userId:V(e.userId,"user")},..."url"in e&&{url:e.url}}}function Be(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=V(s,"channel");return"-777"!==c?{threadId:t,...n!==c?{chatId:c,originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:i,lastReadInboxMessageId:o,...r&&{recentReplierIds:r.map(N)}}:void 0}const xe=e=>Math.floor(Date.now()/1e3)+e;function Ve(e,t=!1){const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&je(e.photo),i=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:i,...s&&{accessHash:s},...a&&{avatarHash:a},...(e instanceof g.Api.Channel||e instanceof g.Api.User)&&{username:e.username},..."verified"in e&&{isVerified:e.verified},..."callActive"in e&&{isCallActive:e.callActive},..."callNotEmpty"in e&&{isCallNotEmpty:e.callNotEmpty},...(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&{isProtected:Boolean("noforwards"in e&&e.noforwards)},...t&&{isSupport:!0},...Fe(e),..."creator"in e&&{isCreator:e.creator},...Le(e),...Oe(e)}}function Ne(e,t,n){const{peer:s,folderId:a,unreadMark:i,unreadCount:o,unreadMentionsCount:r,notifySettings:{silent:c,muteUntil:d},readOutboxMaxId:l,readInboxMaxId:u,draft:p}=e,f=c||"number"==typeof d&&xe(n)"all"===e));return t?f(t,["reason","text"]):void 0}(e.restrictionReason):void 0;n&&Object.assign(t,{isRestricted:!0,restrictionReason:n})}return e instanceof g.Api.Chat&&Object.assign(t,{isNotJoined:e.left,isRestricted:e.kicked}),e instanceof g.Api.Channel&&Object.assign(t,{isNotJoined:e.left}),t}function Oe(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:N(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function qe(e,t=!1,n=!1){if(e instanceof g.Api.Chat||e instanceof g.Api.Channel||e instanceof g.Api.User||n&&(e instanceof g.Api.ChatForbidden||e instanceof g.Api.ChannelForbidden))return{id:V(e.id,e instanceof g.Api.User?"user":"chat"),type:He(e),title:e instanceof g.Api.User?ze(e):e.title,...Ve(e,t)}}function He(e){return e instanceof g.Api.User||e instanceof g.Api.UserEmpty?"chatTypePrivate":e instanceof g.Api.Chat||e instanceof g.Api.ChatForbidden||e instanceof g.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function Ge(e){return B(e)?`user${e.userId}`:x(e)?`chat${e.chatId}`:`chat${e.channelId}`}function Ke(e,t){return B(e)?ze(t):t.title}function ze(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function je(e){if("photoId"in e)return String(e.photoId)}function We(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?N(e.peer):V(e.userId,"user"),inviterId:"inviterId"in e?V(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?V(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?V(e.promotedBy,"user"):void 0,bannedRights:"bannedRights"in e?_(e.bannedRights):void 0,adminRights:"adminRights"in e?_(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof g.Api.ChannelParticipantAdmin||e instanceof g.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof g.Api.ChannelParticipantCreator||e instanceof g.Api.ChatParticipantCreator)&&{isOwner:!0}}}function $e(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(We).filter(Boolean):void 0}function Je(e,t){let n,s="";if(!(e.action instanceof g.Api.SendMessageCancelAction)){if(e.action instanceof g.Api.SendMessageTypingAction)s="lng_user_typing";else if(e.action instanceof g.Api.SendMessageRecordVideoAction)s="lng_send_action_record_video";else if(e.action instanceof g.Api.SendMessageUploadVideoAction)s="lng_send_action_upload_video";else if(e.action instanceof g.Api.SendMessageRecordAudioAction)s="lng_send_action_record_audio";else if(e.action instanceof g.Api.SendMessageUploadAudioAction)s="lng_send_action_upload_audio";else if(e.action instanceof g.Api.SendMessageUploadPhotoAction)s="lng_send_action_upload_photo";else if(e.action instanceof g.Api.SendMessageUploadDocumentAction)s="lng_send_action_upload_file";else if(e.action instanceof g.Api.SendMessageGeoLocationAction)s="selecting a location to share";else if(e.action instanceof g.Api.SendMessageChooseContactAction)s="selecting a contact to share";else if(e.action instanceof g.Api.SendMessageGamePlayAction)s="lng_playing_game";else if(e.action instanceof g.Api.SendMessageRecordRoundAction)s="lng_send_action_record_round";else if(e.action instanceof g.Api.SendMessageUploadRoundAction)s="lng_send_action_upload_round";else if(e.action instanceof g.Api.SendMessageChooseStickerAction)s="lng_send_action_choose_sticker";else{if(e.action instanceof g.Api.SpeakingInGroupCallAction)return;if(e.action instanceof g.Api.SendMessageEmojiInteractionSeen)s="lng_user_action_watching_animations",n=e.action.emoticon;else if(e.action instanceof g.Api.SendMessageEmojiInteraction)return}return{action:s,...n&&{emoji:n},...!(e instanceof g.Api.UpdateUserTyping)&&{userId:N(e.fromId)},timestamp:Date.now()+1e3*t}}}function Qe(e){return{...(t=e,n=["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"],n.reduce(((e,n)=>(t[n]&&(e[n]=t[n]),e)),{})),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(N).filter(Boolean),includedChatIds:e.includePeers.map(N).filter(Boolean),excludedChatIds:e.excludePeers.map(N).filter(Boolean)};var t,n}function Xe({filter:e,description:t}){return{...Qe(e),description:t}}function Ze(e){return e.reduce(((e,t)=>{const n=V(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function Ye(e){const{revoked:t,date:n,expireDate:s,link:a,permanent:i,startDate:o,usage:r,usageLimit:c,requested:d,requestNeeded:l,title:u}=e;return{isRevoked:t,date:n,expireDate:s,link:a,isPermanent:i,startDate:o,usage:r,usageLimit:c,isRequestNeeded:l,requested:d,title:u}}function et(e){const{fullUser:{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i},users:o}=e,r=tt(o[0]);return{...r,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:st(r.id,a)}}}}function tt(e){if(!(e instanceof g.Api.User))return;const{id:t,firstName:n,lastName:s}=e,a=e.photo instanceof g.Api.UserProfilePhoto?String(e.photo.photoId):void 0,i=(o=e).bot?"userTypeBot":o.deleted?"userTypeDeleted":"userTypeRegular";var o;return{id:V(t,"user"),isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:i,...n&&{firstName:n},..."userTypeBot"===i&&{canBeInvitedToGroup:!e.botNochats},...s&&{lastName:s},username:e.username||"",phoneNumber:e.phone||"",noStatus:!e.status,...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a},...e.bot&&e.botInlinePlaceholder&&{botPlaceholder:e.botInlinePlaceholder}}}function nt(e){return!e||e instanceof g.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof g.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof g.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof g.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof g.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}function st(e,t){return t.commands.map((({command:t,description:n})=>({botId:e,command:t,description:n})))}function at(e){const t={},n=[];return e.forEach((e=>{const s=tt(e);s&&(n.push(s),"status"in e&&(t[s.id]=nt(e.status)))})),{users:n,userStatusesById:t}}function it(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=Me(e.document);return n?{slug:t,document:n}:void 0}function ot(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...f(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function rt(e){let t,n,s,a,i;return e.forEach((e=>{e instanceof g.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof g.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof g.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof g.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof g.Api.PrivacyValueAllowUsers?n=e.users.map((e=>V(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>V(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>V(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>V(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function ct(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:N(t),isMuted:s||"number"==typeof a&&xe(n)(e[t.key]=lt(t.value),e)),{})}function ut(e){const{self:t,min:n,about:s,date:a,versioned:i,canSelfUnmute:o,justJoined:r,left:c,muted:d,mutedByYou:l,source:u,volume:g,volumeByAdmin:p,videoJoined:f,peer:h,video:m,presentation:_,raiseHandRating:y}=e;return{isSelf:t,isMin:n,canSelfUnmute:o,isLeft:c,isMuted:d,isMutedByMe:l,hasJustJoined:r,isVolumeByAdmin:p,isVersioned:i,isVideoJoined:f,about:s,source:u,raiseHandRating:null==y?void 0:y.toString(),volume:g,date:new Date(a),isUser:B(h),id:N(h),video:m?gt(m):void 0,presentation:_?gt(_):void 0}}function gt(e){const{audioSource:t,endpoint:n,paused:s,sourceGroups:a}=e;return{audioSource:t,endpoint:n,isPaused:s,sourceGroups:a.map(pt)}}function pt(e){return{semantics:e.semantics,sources:e.sources}}function ft(e){const{id:t,accessHash:n}=e;if(e instanceof g.Api.GroupCallDiscarded)return{connectionState:"discarded",id:t.toString(),accessHash:n.toString(),participantsCount:0,version:0,participants:{}};const{version:s,participantsCount:a,streamDcId:i,scheduleDate:o,canChangeJoinMuted:r,joinMuted:c,canStartVideo:d,scheduleStartSubscribed:l}=e;return{connectionState:"disconnected",isLoaded:!0,id:t.toString(),accessHash:n.toString(),version:s,participantsCount:a,streamDcId:i,scheduleDate:o,canChangeJoinMuted:r,joinMuted:c,canStartVideo:d,scheduleStartSubscribed:l,participants:{}}}let ht;const mt=new Set;let _t=0,yt=!1;function bt(e){e.filter((e=>e instanceof g.Api.User)).map(tt).forEach((e=>{e&&ht({"@type":"updateUser",id:e.id,user:e})})),e.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>qe(e))).forEach((e=>{e&&ht({"@type":"updateChat",id:e.id,chat:e})}))}function wt(e,t){if(e instanceof g.connection.UpdateServerTimeOffset)_t=e.timeOffset;else if(e instanceof g.connection.UpdateConnectionState){let t;switch(e.state){case g.connection.UpdateConnectionState.disconnected:t="connectionStateConnecting";break;case g.connection.UpdateConnectionState.broken:t="connectionStateBroken";break;case g.connection.UpdateConnectionState.connected:default:t="connectionStateReady"}ht({"@type":"updateConnectionState",connectionState:t})}else if(e instanceof g.Api.UpdateNewMessage||e instanceof g.Api.UpdateNewScheduledMessage||e instanceof g.Api.UpdateNewChannelMessage||e instanceof g.Api.UpdateShortChatMessage||e instanceof g.Api.UpdateShortMessage){let t,s;if(e instanceof g.Api.UpdateShortChatMessage)t=_e(V((i=e).chatId,"chat"),{...i,fromId:W(V(i.fromId,"user"))});else if(e instanceof g.Api.UpdateShortMessage)t=function(e){return _e(V(e.userId,"user"),{...e,fromId:W(e.out?pe:V(e.userId,"user"))})}(e);else{var n;if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&se(e.message)&&O(e.message),t=me(e.message),s="replyMarkup"in e.message&&(null===(n=e.message)||void 0===n?void 0:n.replyMarkup)instanceof g.Api.ReplyKeyboardForceReply&&(!e.message.replyMarkup.selective||t.isMentioned)}const a=e._entities;if(a&&(G(a),bt(a)),e instanceof g.Api.UpdateNewScheduledMessage?ht({"@type":mt.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):ht({"@type":mt.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t,shouldForceReply:s}),e.message instanceof g.Api.MessageService){const{action:n}=e.message;if(n instanceof g.Api.MessageActionChatEditTitle)ht({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof g.Api.MessageActionChatEditPhoto){const s=function(e){if(e instanceof g.Api.PhotoEmpty)return new g.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new g.Api.ChatPhoto({dcId:t,photoId:n})}(n.photo),a=je(s),i=L(e.message);I.chats[i]&&(I.chats[i].photo=s),q(n.photo),a&&ht({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof g.Api.Photo&&{newProfilePhoto:C(n.photo)}})}else if(n instanceof g.Api.MessageActionChatDeletePhoto){const n=L(e.message);I.chats[n]&&(I.chats[n].photo=new g.Api.ChatPhotoEmpty),ht({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof g.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some((e=>e instanceof g.Api.User&&!!e.self&&e.id===n.userId))&&(ht({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),ht({"@type":"updateChatLeave",id:t.chatId})):n instanceof g.Api.MessageActionChatAddUser?e._entities&&e._entities.some((e=>e instanceof g.Api.User&&!!e.self&&n.users.includes(e.id)))&&ht({"@type":"updateChatJoin",id:t.chatId}):n instanceof g.Api.MessageActionGroupCall&&!n.duration&&n.call&&ht({"@type":"updateGroupCallChatId",chatId:t.chatId,call:{id:n.call.id.toString(),accessHash:n.call.accessHash.toString()}})}}else if(e instanceof g.Api.UpdateEditMessage||e instanceof g.Api.UpdateEditChannelMessage){if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&se(e.message)&&O(e.message);const t=me(e.message);ht({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateMessageReactions)ht({"@type":"updateMessageReactions",id:e.msgId,chatId:N(e.peer),reactions:ye(e.reactions)});else if(e instanceof g.Api.UpdateDeleteMessages)ht({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)ht({"@type":"deleteScheduledMessages",ids:e.messages,chatId:N(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=V(e.channelId,"channel"),n=e.messages,s=n.filter((e=>I.messages[`${t}-${e}`])),a=n.filter((e=>!I.messages[`${t}-${e}`])),i=n.map((e=>{const n=I.messages[`${t}-${e}`];return n&&n instanceof g.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0})).filter(Boolean);s.length&&ht({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&ht({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{ht({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification)if(e.popup)ht({"@type":"error",error:{message:e.message}});else{const t=function(e,t){const n=fe++,s=ve(e);return{id:n,chatId:d,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+_t);se(e)&&O(te(t.id,t.chatId,e)),ht({"@type":"updateServiceNotification",message:t})}else if((t instanceof g.Api.messages.SendMessage||t instanceof g.Api.messages.SendMedia||t instanceof g.Api.messages.SendMultiMedia||t instanceof g.Api.messages.ForwardMessages)&&(e instanceof g.Api.UpdateMessageID||e instanceof g.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const s=n&&I.localMessages[String(n)];if(!s)throw new Error("Local message not found");let a;if(e instanceof g.Api.UpdateShortSentMessage){s.content.text&&e.entities&&(a={text:Ie(s.content.text.text,e.entities)}),e.media&&(a={...a,...Se(e.media)});const t=te(e.id,s.chatId,e);se(t)&&O(t)}mt.add(e.id);const i="date"in e&&1e3*e.datee instanceof g.Api.DialogPeer)).map((e=>N(e.peer))):[];ht({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof g.Api.UpdateFolderPeers)e.folderPeers.forEach((e=>{const{folderId:t,peer:n}=e;ht({"@type":"updateChatListType",id:N(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Qe(n):void 0;ht({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)ht({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=$e(e.participants);ht({"@type":"updateChatMembers",id:V(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=We(f(e,["userId","inviterId","date"]));ht({"@type":"updateChatMembers",id:V(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)ht({"@type":"updateChatMembers",id:V(e.chatId,"chat"),deletedMemberId:V(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?N(e.peer):V(e.channelId,"channel");ht({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)ht({"@type":"updateNotifyExceptions",...ct(e.notifySettings,e.peer.peer,_t)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?V(e.userId,"user"):V(e.chatId,"chat");e.action instanceof g.Api.SendMessageEmojiInteraction?ht({"@type":"updateStartEmojiInteraction",id:t,emoji:e.action.emoticon,messageId:e.action.msgId,interaction:(a=JSON.parse(e.action.interaction.data),{timestamps:a.a.map((e=>e.t))})}):ht({"@type":"updateChatTypingStatus",id:t,typingStatus:Je(e,_t)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=V(e.channelId,"channel");ht({"@type":"updateChatTypingStatus",id:t,typingStatus:Je(e,_t)})}else if(e instanceof g.Api.UpdateChannel){const{_entities:n}=e;if(!n)return;const s=n.find((e=>e instanceof g.Api.Channel||e instanceof g.Api.ChannelForbidden));if(s instanceof g.Api.Channel){if(yt)return void(yt=!1);t instanceof g.Api.messages.ToggleNoForwards&&(yt=!0,setTimeout((()=>{yt=!1}),2e3));const n=qe(s);n&&(ht({"@type":"updateChat",id:n.id,chat:n}),ht({"@type":n.isNotJoined?"updateChatLeave":"updateChatJoin",id:V(e.channelId,"channel")}))}else if(s instanceof g.Api.ChannelForbidden){const t=V(e.channelId,"channel");ht({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),ht({"@type":"updateChatLeave",id:t})}else 0===n.length&&ht({"@type":"resetMessages",id:V(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)ht({"@type":"updateChat",id:N(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)ht({"@type":"updateChat",id:N(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)ht({"@type":"updateUserStatus",userId:V(e.userId,"user"),status:nt(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=V(e.userId,"user"),n=I.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);ht({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=V(t,"user"),a=je(n);I.users[s]&&(I.users[s].photo=n),ht({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;ht({"@type":"updateUser",id:V(t,"user"),user:{phoneNumber:n}})}else if(e instanceof g.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;null!=t&&t.length&&(t.filter((e=>e instanceof g.Api.User&&!e.contact)).forEach((e=>{ht({"@type":"deleteContact",id:V(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(tt).forEach((e=>{e&&ht({"@type":"updateUser",id:e.id,user:e})})))}else if(e instanceof g.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:a}}=e,i="NotifyUsers"===a?"contact":"NotifyChats"===a?"group":"NotifyBroadcasts"===a?"broadcast":void 0;if(!i)return;ht({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*_t<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)ht({"@type":"updatePeerBlocked",id:N(e.peerId),isBlocked:e.blocked});else if(e instanceof g.Api.UpdatePrivacy){const t=function(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}(e.key);t&&ht({"@type":"updatePrivacy",key:t,rules:rt(e.rules)})}else if(e instanceof g.Api.UpdateDraftMessage)ht({"@type":"draftMessage",chatId:N(e.peer),...Ae(e.draft)});else if(e instanceof g.Api.UpdateContactsReset)ht({"@type":"updateResetContactList"});else if(e instanceof g.Api.UpdateFavedStickers)ht({"@type":"updateFavoriteStickers"});else if(e instanceof g.Api.UpdateGroupCall)ht({"@type":"updateGroupCall",call:ft(e.call)});else if(e instanceof g.Api.UpdateGroupCallConnection)ht({"@type":"updateGroupCallConnection",data:JSON.parse(e.params.data),presentation:Boolean(e.presentation)});else if(e instanceof g.Api.UpdateGroupCallParticipants){const t=e._entities;t&&(G(t),bt(t)),ht({"@type":"updateGroupCallParticipants",groupCallId:(s=e.call,s.id.toString()),participants:e.participants.map(ut)})}var s,a,i}const Ct={PHONE_NUMBER_INVALID:"Invalid phone number.",PHONE_CODE_INVALID:"Invalid code.",PASSWORD_HASH_INVALID:"Incorrect password.",PHONE_PASSWORD_FLOOD:"Limit exceeded. Please try again later.",PHONE_NUMBER_BANNED:"This phone number is banned."},vt={};let It;function At(){return It(Ut("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{vt.resolve=e,vt.reject=t}))}function St(e=!1){return It({...Ut("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{vt.resolve=e,vt.reject=t}))}function Pt(e){return It({...Ut("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{vt.resolve=e}))}function Mt(){return It(Ut("authorizationStateWaitRegistration")),new Promise((e=>{vt.resolve=e}))}function kt(e){return It({...Ut("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{vt.reject=t}))}function Rt(e){let t;if(e instanceof g.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?`${n} hours`:"an hour")}else t=Ct[e.message];t||(t="Unexpected Error"),It({"@type":"updateAuthorizationError",message:t})}function Ut(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function Et(e){vt.resolve&&vt.resolve(e)}function Dt(e){vt.resolve&&vt.resolve(e)}function Tt(e){vt.resolve&&vt.resolve(e)}function Bt(e){const{firstName:t,lastName:n}=e;vt.resolve&&vt.resolve([t,n])}function xt(){vt.reject&&vt.reject(new Error("RESTART_AUTH"))}function Vt(){vt.reject&&vt.reject(new Error("RESTART_AUTH_WITH_QR"))}var Nt=n(9832);const Ft=self.caches;let Lt;async function Ot(e,t,n,s=!1){if(Ft)try{const a=new Request(t.replace(/:/g,"_")),i=await Ft.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Lt.Text:return await o.text();case Lt.Blob:{if(t.startsWith("avatar")&&r&&r.startsWith("text"))return;const e=await o.blob(),n=!e.type||!s&&e.type.includes("html");let a=e.type||r;return n&&a?(s||(a=a.replace(/html/gi,"")),new Blob([e],{type:a})):e}case Lt.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function qt(e,t,n){if(Ft)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),a=new Request(t.replace(/:/g,"_")),i=new Response(s),o=await Ft.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Ht(e){try{if(!Ft)return;return await Ft.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(Lt||(Lt={}));const Gt=new Set(["msg","sticker","gif","wallpaper","photo","webDocument","document"]);function Kt(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce(((e,t)=>e+t.toString(16)),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}Nt.Logger.setLevel("warn");const zt={build:e=>e};let jt,Wt,$t=!1;async function Jt(){await Yt(new g.Api.auth.LogOut),await Wt.destroy()}async function Qt(){await Wt.disconnect()}function Xt(e){jt({"@type":"updateSession",sessionData:e})}function Zt(e){e instanceof g.connection.UpdateConnectionState?$t=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await Yt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&jt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&jt({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function Yt(e,t=!1,n=!1,s=!1){if($t)try{const n=await Wt.invoke(e);return s||function(e,t){let n,s;t instanceof g.Api.UpdatesCombined||t instanceof g.Api.Updates?n=t:"object"==typeof t&&"updates"in t&&(t.updates instanceof g.Api.Updates||t.updates instanceof g.Api.UpdatesCombined)?n=t.updates:(t instanceof g.Api.UpdateShortMessage||t instanceof g.Api.UpdateShortChatMessage||t instanceof g.Api.UpdateShort||t instanceof g.Api.UpdateShortSentMessage)&&(s=t),n?(function(e){const t=[...e.users,...e.chats];e.updates.forEach((e=>{t&&(e._entities=t)}))}(n),n.updates.forEach((t=>{wt(t,e)}))):s&&wt(s,e)}(e,n),t?n&&!0:n}catch(t){if(n)throw t;return void function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof g.Api.messages.SendMessage||t instanceof g.Api.messages.SendMedia||t instanceof g.Api.messages.SendMultiMedia),{message:s}=e;jt({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}(t,e)}}function en(e,t){return async function({url:e,mediaFormat:t,start:n,end:a,isHtmlAllowed:i},o,r,c){const{data:d,mimeType:l,fullSize:u}=await async function(e,t,n,s,a,i,o,r){const c=e.startsWith("webDocument")?e.match(/(webDocument):(.+)/):e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file|document)([-\d\w./]+)(?::\d+)?(\?size=\w+)?/);if(!c)return;if("file"===c[1]){const e=await fetch(c[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d;const l=c[2],u=c[3]?c[3].replace("?size=",""):void 0;let p;switch(d="avatar"===c[1]||"profile"===c[1]?j(l):c[1],d){case"channel":case"chat":p=I.chats[l];break;case"user":p=I.users[l];break;case"msg":p=I.messages[l];break;case"sticker":case"gif":case"wallpaper":p=I.documents[l];break;case"photo":p=I.photos[l];break;case"stickerSet":p=I.stickerSets[l];break;case"webDocument":p=I.webDocuments[l];break;case"document":p=I.documents[l]}if(p){if(Gt.has(d)){o===T.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(p,{sizeType:u,start:a,end:i,progressCallback:s,workers:16});let n,c;return p instanceof g.Api.Message?(n=function(e,t){if(e&&e.media)return e.media instanceof g.Api.MessageMediaPhoto?"image/jpeg":e.media instanceof g.Api.MessageMediaDocument&&e.media.document instanceof g.Api.Document?t?e.media.document.attributes.some((e=>e instanceof g.Api.DocumentAttributeSticker))?"image/webp":"image/jpeg":e.media.document.mimeType:e.media instanceof g.Api.MessageMediaWebPage&&e.media.webpage instanceof g.Api.WebPage&&e.media.webpage.document instanceof g.Api.Document?e.media.webpage.document.mimeType:void 0}(p,u),p.media instanceof g.Api.MessageMediaDocument&&p.media.document instanceof g.Api.Document&&(c=p.media.document.size),p.media instanceof g.Api.MessageMediaWebPage&&p.media.webpage instanceof g.Api.WebPage&&p.media.webpage.document instanceof g.Api.Document&&(c=p.media.webpage.document.size)):p instanceof g.Api.Photo?n="image/jpeg":"sticker"===d&&u?n="image/webp":"webDocument"===d?n=p.mimeType:(n=p.mimeType,c=p.size),!r&&n&&(n=n.replace(/html/gi,"")),{mimeType:n,data:e,fullSize:c}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(p);return{mimeType:o===T.Lottie?"application/x-tgsticker":Kt(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:Kt(e),data:e}}}}(e,o,r,c,n,a,t,i)||{};if(!d)return;const p=await async function(e,t,n){switch(t){case T.BlobUrl:case T.Lottie:return new Blob([e],{type:n});case T.Progressive:return e.buffer}}(d,t,l);if(!p)return;const f=t!==T.Progressive&&(t!==T.BlobUrl||p.size<=524288);return s&&f&&qt(e.startsWith("avatar")?"tt-media-avatars":"tt-media",e,p),{prepared:t===T.Progressive?"":(h=p,h instanceof Blob?URL.createObjectURL(h):h),arrayBuffer:t===T.Progressive?p:void 0,mimeType:l,fullSize:u};var h}(e,Wt,$t,t)}function tn(e,t){return Wt.uploadFile({file:e,onProgress:t,workers:16})}function nn(e){return Wt.updateTwoFaSettings(e)}async function sn(){const e=await Yt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}));if(!(e&&e.users[0]instanceof g.Api.User))return;const t=e.users[0];I.users[V(t.id,"user")]=t;const n=et(e);var s;s=n.id,pe=s,function(e){It({"@type":"updateCurrentUser",currentUser:e})}(n)}const an=2**31-1;let on;async function rn({limit:e,offsetDate:t,archived:n,withPinned:s,serverTimeOffset:a,lastLocalServiceMessage:i}){const o=await Yt(new g.Api.messages.GetDialogs({offsetPeer:new g.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?1:void 0,...s&&{excludePinned:!0}})),r=s?await Yt(new g.Api.messages.GetPinnedDialogs({folderId:n?1:void 0})):void 0;if(!o||o instanceof g.Api.messages.DialogsNotModified)return;r&&jn(r),jn(o);const c=p((r?r.messages:[]).concat(o.messages).map(me).filter(Boolean),"chatId"),l={...r&&zn(r),...zn(o)},u=[],f={},h={},m=(r?r.dialogs:[]).concat(o.dialogs),_=[];m.forEach((e=>{if(!(e instanceof g.Api.Dialog)||!n&&1===e.folderId||n&&1!==e.folderId)return;const t=Ne(e,l[Ge(e.peer)],a);if(t.id===d&&i&&(!c[t.id]||i.date>c[t.id].date)?t.lastMessage=i:t.lastMessage=c[t.id],t.isListed=!0,u.push(t),s&&e.pinned&&_.push(t.id),e.draft){const{formattedText:n,replyingToId:s}=Ae(e.draft)||{};n&&(f[t.id]=n),s&&(h[t.id]=s)}}));const y=u.map((e=>e.id)),{users:b,userStatusesById:w}=at(((null==r?void 0:r.users)||[]).concat(o.users));let C;return C=o instanceof g.Api.messages.DialogsSlice?o.count:y.length,{chatIds:y,chats:u,users:b,userStatusesById:w,draftsById:f,replyingToById:h,orderedPinnedIds:s?_:void 0,totalChatCount:C}}function cn(e){const{id:t,accessHash:n,adminRights:s}=e;return Q(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await Yt(new g.Api.channels.GetFullChannel({channel:Q(e,t)}));if(!(a&&a.fullChat instanceof g.Api.ChannelFull))return;const{about:i,onlineCount:o,exportedInvite:r,slowmodeSeconds:c,slowmodeNextSendDate:d,migratedFromChatId:l,migratedFromMaxId:u,canViewParticipants:p,linkedChatId:f,hiddenPrehistory:h,call:m,botInfo:_,availableReactions:y,defaultSendAs:b}=a.fullChat,w=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:C,users:v}=p&&await Fn(e,t)||{},{members:I,users:A}=p&&n&&await Fn(e,t,"kicked")||{},{members:S,users:P}=p&&n&&await Fn(e,t,"admin")||{},M=_?Ze(_):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){jn(a);const[,e]=a.chats,t=qe(e,void 0,!0);t&&on({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:w,slowMode:c?{seconds:c,nextSendDate:d}:void 0,migratedFrom:l?{chatId:V(l,"chat"),maxMessageId:u}:void 0,canViewMembers:p,isPreHistoryHidden:h,members:C,kickedMembers:I,adminMembers:S,groupCallId:m?String(m.id):void 0,linkedChatId:f?V(f,"chat"):void 0,botCommands:M,enabledReactions:y,sendAsId:b?N(b):void 0},users:[...v||[],...A||[],...P||[]],groupCall:m?{chatId:e,isLoaded:!1,id:m.id.toString(),accessHash:null==m?void 0:m.accessHash.toString(),participants:{},version:0,participantsCount:0,connectionState:"disconnected"}:void 0}}(t,n,s):async function(e){const t=await Yt(new g.Api.messages.GetFullChat({chatId:Q(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;jn(t);const{about:n,participants:s,exportedInvite:a,botInfo:i,call:o,availableReactions:r}=t.fullChat,c=$e(s),d=c?c.filter((({isAdmin:e,isOwner:t})=>e||t)):void 0;return{fullInfo:{about:n,members:c,adminMembers:d,canViewMembers:!0,botCommands:i?Ze(i):void 0,...a&&{inviteLink:a.link},groupCallId:null==o?void 0:o.id.toString(),enabledReactions:r},users:t.users.map(tt).filter(Boolean),groupCall:o?{chatId:e,isLoaded:!1,id:o.id.toString(),accessHash:o.accessHash.toString(),connectionState:"disconnected",participantsCount:0,version:0,participants:{}}:void 0}}(t)}async function dn({query:e}){const t=await Yt(new g.Api.contacts.Search({q:e}));if(!t)return;jn(t);const n=t.myResults.map(N),s=t.chats.concat(t.users).map((e=>qe(e))).filter(Boolean),a=t.users.map(tt).filter((e=>!!e&&!e.isSelf));return{localChats:s.filter((e=>n.includes(e.id))),localUsers:a.filter((e=>n.includes(e.id))),globalChats:s.filter((e=>!n.includes(e.id))),globalUsers:a.filter((e=>!n.includes(e.id)))}}async function ln({type:e,user:t}){let n;if("self"===e||"user"===e){const s=await Yt(new g.Api.users.GetUsers({id:["user"===e&&t?Q(t.id,t.accessHash):new g.Api.InputUserSelf]}));if(!s||!s.length)return;[n]=s}else if("support"===e){const e=await Yt(new g.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const s=qe(n,"support"===e);if(s)return on({"@type":"updateChat",id:s.id,chat:s}),{chatId:s.id}}async function un({chat:e,serverTimeOffset:t,lastLocalMessage:n,noLastMessage:s}){const{id:a,accessHash:i}=e,o=await Yt(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:$(a,i)})]}));if(!o)return;const r=o.dialogs[0];if(!(r&&r instanceof g.Api.Dialog))return;const c=zn(o)[Ge(r.peer)];if(!c)return;jn(o);const d=me(o.messages[0]),l=n&&(!d||n.date>d.date)?n:d;on({"@type":"updateChat",id:a,chat:{...Ne(r,c,t),...!s&&{lastMessage:l}}})}function gn({chat:e,text:t,entities:n,replyToMsgId:s}){return Yt(new g.Api.messages.SaveDraft({peer:$(e.id,e.accessHash),message:t,...n&&{entities:n.map(ne)},replyToMsgId:s}))}function pn(e){return Yt(new g.Api.messages.SaveDraft({peer:$(e.id,e.accessHash),message:""}))}async function fn({chat:e,isMuted:t,serverTimeOffset:n}){await Yt(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:$(e.id,e.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:t?an:0})})),on({"@type":"updateNotifyExceptions",chatId:e.id,isMuted:t}),un({chat:e,serverTimeOffset:n,noLastMessage:!0})}async function hn({title:e,about:t="",users:n},s=!1){const a=await Yt(new g.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}));if(!(a instanceof g.Api.Updates))return;const i=a.chats[0];if(!(i&&i instanceof g.Api.Channel))return;const o=qe(i);if(null!=n&&n.length)try{await Yt(new g.Api.channels.InviteToChannel({channel:Q(o.id,o.accessHash),users:n.map((({id:e,accessHash:t})=>Q(e,t)))}),void 0,s)}catch(e){}return o}function mn({channelId:e,accessHash:t}){return Yt(new g.Api.channels.JoinChannel({channel:Q(e,t)}),!0)}function _n({chat:e,user:t}){if("chatTypeBasicGroup"===e.type)return Yt(new g.Api.messages.DeleteChatUser({chatId:Q(e.id,e.accessHash),userId:Q(t.id,t.accessHash)}),!0)}function yn({chatId:e}){return Yt(new g.Api.messages.DeleteChat({chatId:Q(e)}),!0)}function bn({channelId:e,accessHash:t}){return Yt(new g.Api.channels.LeaveChannel({channel:Q(e,t)}),!0)}function wn({channelId:e,accessHash:t}){return Yt(new g.Api.channels.DeleteChannel({channel:Q(e,t)}),!0)}async function Cn({title:e,users:t}){const n=await Yt(new g.Api.messages.CreateChat({title:e,users:t.map((({id:e,accessHash:t})=>Q(e,t)))}),void 0,!0);if(!(n instanceof g.Api.Updates))return;const s=n.chats[0];return s&&s instanceof g.Api.Chat?qe(s):void 0}async function vn({chatId:e,accessHash:t,photo:n}){const s=await tn(n),a=Q(e,t);return Yt(a instanceof g.Api.InputChannel?new g.Api.channels.EditPhoto({channel:a,photo:new g.Api.InputChatUploadedPhoto({file:s})}):new g.Api.messages.EditChatPhoto({chatId:a,photo:new g.Api.InputChatUploadedPhoto({file:s})}),!0)}async function In({chat:e,shouldBePinned:t}){const{id:n,accessHash:s}=e;await Yt(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:$(n,s)}),pinned:t||void 0}))&&on({"@type":"updateChatPinned",id:e.id,isPinned:t})}function An({chat:e,folderId:t}){const{id:n,accessHash:s}=e;return Yt(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:$(n,s),folderId:t})]}),!0)}async function Sn(){const e=await Yt(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(Qe),"id"),orderedIds:e.map((({id:e})=>e))}}async function Pn(){const e=await Yt(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(Xe)}async function Mn({id:e,folderUpdate:t}){const n=function(e){const{emoticon:t,contacts:n,nonContacts:s,groups:a,channels:i,bots:o,excludeArchived:r,excludeMuted:c,excludeRead:d,pinnedChatIds:l,includedChatIds:u,excludedChatIds:p}=e,f=l?l.map(J).filter(Boolean):[],h=u?u.map(J).filter(Boolean):[],m=p?p.map(J).filter(Boolean):[];return new g.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:a||void 0,bots:o||void 0,excludeArchived:r||void 0,excludeMuted:c||void 0,excludeRead:d||void 0,broadcasts:i||void 0,pinnedPeers:f,includePeers:h,excludePeers:m})}(t);await Yt(new g.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&on({"@type":"updateChatFolder",id:e,folder:t})}async function kn(e){const t=await Yt(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await Pn();t&&on({"@type":"updateChatFolder",id:e,folder:void 0}),n&&on({"@type":"updateRecommendedChatFolders",folders:n})}async function Rn({chat:e,hasUnreadMark:t}){const{id:n,accessHash:s}=e;await Yt(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:$(n,s)}),unread:t||void 0}))&&on({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function Un(e){const t=await Yt(new g.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:s}=t,a=s.length?qe(s[0]):qe(n[0]);return a?(jn(t),a):void 0}function En({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=Q(n,s);return Yt(new g.Api.channels.TogglePreHistoryHidden({channel:a,enabled:t}),!0)}function Dn({chat:e,bannedRights:t}){const{id:n,accessHash:s}=e,a=$(n,s);return Yt(new g.Api.messages.EditChatDefaultBannedRights({peer:a,bannedRights:ie(t)}),!0)}function Tn({chat:e,user:t,bannedRights:n,untilDate:s}){const a=Q(e.id,e.accessHash),i=$(t.id,t.accessHash);return Yt(new g.Api.channels.EditBanned({channel:a,participant:i,bannedRights:ie(n,s)}),!0)}function Bn({chat:e,user:t,adminRights:n,customTitle:s=""}){const a=Q(e.id,e.accessHash),i=Q(t.id,t.accessHash);return Yt(new g.Api.channels.EditAdmin({channel:a,userId:i,adminRights:oe(n),rank:s}),!0)}async function xn(e,t){const n=Q(e.id,e.accessHash);await Yt(n instanceof g.Api.InputChannel?new g.Api.channels.EditTitle({channel:n,title:t}):new g.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function Vn(e,t){await Yt(new g.Api.messages.EditChatAbout({peer:$(e.id,e.accessHash),about:t}))&&on({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function Nn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=Q(n,s);return Yt(new g.Api.channels.ToggleSignatures({channel:a,enabled:t}),!0)}async function Fn(e,t,n="recent",s){let a;switch(n){case"kicked":a=new g.Api.ChannelParticipantsKicked({q:""});break;case"admin":a=new g.Api.ChannelParticipantsAdmins;break;default:a=new g.Api.ChannelParticipantsRecent}const i=await Yt(new g.Api.channels.GetParticipants({channel:Q(e,t),filter:a,offset:s,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return jn(i),{members:$e(i),users:i.users.map(tt).filter(Boolean)}}async function Ln(){const e=await Yt(new g.Api.channels.GetGroupsForDiscussion);if(e)return jn(e),e.chats.map((e=>qe(e)))}function On({channel:e,chat:t}){return Yt(new g.Api.channels.SetDiscussionGroup({broadcast:$(e.id,e.accessHash),group:t?$(t.id,t.accessHash):new g.Api.InputChannelEmpty}),!0)}async function qn(e){const t=await Yt(new g.Api.messages.MigrateChat({chatId:Q(e.id)}));if(t&&t instanceof g.Api.Updates)return jn(t),qe(t.chats[1])}async function Hn(e){const t=await Yt(new g.Api.messages.CheckChatInvite({hash:e}));if(!t)return;let n;if(t instanceof g.Api.ChatInvite){const{photo:n,participantsCount:s,title:a,channel:i,requestNeeded:o,about:r}=t;n instanceof g.Api.Photo&&q(t.photo),on({"@type":"showInvite",data:{title:a,about:r,hash:e,participantsCount:s,isChannel:i,isRequestNeeded:o,...n instanceof g.Api.Photo&&{photo:C(n)}}})}else n=qe(t.chat),n&&on({"@type":"updateChat",id:n.id,chat:n});return n?{chatId:n.id}:void 0}async function Gn(e,t,n=!1){try{return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?await Yt(new g.Api.channels.InviteToChannel({channel:Q(e.id,e.accessHash),users:t.map((e=>Q(e.id,e.accessHash)))}),!0,n):await Promise.all(t.map((t=>Yt(new g.Api.messages.AddChatUser({chatId:Q(e.id),userId:Q(t.id,t.accessHash)}),!0,n))))}catch(e){return}}function Kn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?Tn({chat:e,user:t,bannedRights:{viewMessages:!0,sendMessages:!0,sendMedia:!0,sendStickers:!0,sendGifs:!0,sendGames:!0,sendInline:!0,embedLinks:!0,sendPolls:!0,changeInfo:!0,inviteUsers:!0,pinMessages:!0},untilDate:an}):Yt(new g.Api.messages.DeleteChatUser({chatId:Q(e.id),userId:Q(t.id,t.accessHash)}),!0)}function zn(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function jn(e){"users"in e&&G(e.users),"chats"in e&&G(e.chats),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&se(e)&&O(e)}))}async function Wn({peer:e,admin:t,limit:n=0,isRevoked:s}){const a=await Yt(new g.Api.messages.GetExportedChatInvites({peer:$(e.id,e.accessHash),adminId:Q(t.id,t.accessHash),limit:n,revoked:s||void 0}));if(a)return a.invites.map(Ye)}async function $n({peer:e,isRevoked:t,link:n,expireDate:s,usageLimit:a,isRequestNeeded:i,title:o}){const r=await Yt(new g.Api.messages.EditExportedChatInvite({link:n,peer:$(e.id,e.accessHash),expireDate:s,usageLimit:i?void 0:a,requestNeeded:i,title:o,revoked:t||void 0}));if(r){if(r instanceof g.Api.messages.ExportedChatInvite){const e=Ye(r.invite);return{oldInvite:e,newInvite:e}}if(r instanceof g.Api.messages.ExportedChatInviteReplaced)return{oldInvite:Ye(r.invite),newInvite:Ye(r.newInvite)}}}async function Jn({peer:e,expireDate:t,usageLimit:n,isRequestNeeded:s,title:a}){const i=await Yt(new g.Api.messages.ExportChatInvite({peer:$(e.id,e.accessHash),expireDate:t,usageLimit:s?void 0:n,requestNeeded:s||void 0,title:a}));if(i)return Ye(i)}async function Qn({hash:e}){const t=await Yt(new g.Api.messages.ImportChatInvite({hash:e}));if(t instanceof g.Api.Updates&&t.chats.length)return qe(t.chats[0])}function Xn({chat:e,enabledReactions:t}){return Yt(new g.Api.messages.SetChatAvailableReactions({peer:$(e.id,e.accessHash),availableReactions:t}),!0)}function Zn({chat:e,isProtected:t}){const{id:n,accessHash:s}=e;return Yt(new g.Api.messages.ToggleNoForwards({peer:$(n,s),enabled:t}),!0)}function Yn(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...s}=n;super(e,{type:t}),Yn(this,"name",void 0),Object.assign(this,s)}else super(e),Yn(this,"name",void 0);this.name=t}});var es=n(8764).Buffer;let ts;async function ns({chat:e,threadId:t,...n}){const s=-1===t?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let a;try{a=await Yt(new s({peer:$(e.id,e.accessHash),...-1!==t&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&ts({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified||!a.messages)return;Rs(a);const i=a.messages.map(me).filter(Boolean),o=a.users.map(tt).filter(Boolean),r=a.chats.map((e=>qe(e))).filter(Boolean),c=i.map((({threadInfo:e})=>e)).filter(Boolean);return{messages:i,users:o,chats:r,threadInfos:c}}async function ss({chat:e,messageId:t}){const n="channel"===j(e.id);let s;try{s=await Yt(n?new g.Api.channels.GetMessages({channel:Q(e.id,e.accessHash),id:[new g.Api.InputMessageID({id:t})]}):new g.Api.messages.GetMessages({id:[new g.Api.InputMessageID({id:t})]}),void 0,!0)}catch(e){const{message:t}=e;"CHANNEL_PRIVATE"!==t&&ts({"@type":"error",error:{message:t,isSlowMode:!1,hasErrorKey:!0}})}if(!s||s instanceof g.Api.messages.MessagesNotModified)return;const a=s.messages[0];if(!a)return;if(a instanceof g.Api.MessageEmpty)return"MESSAGE_DELETED";const i=a&&me(a);return i?(a instanceof g.Api.Message&&O(a),{message:i,users:s.users.map(tt).filter(Boolean)}):void 0}let as=Promise.resolve();function is({chat:e,text:t,entities:n,replyingTo:s,attachment:a,sticker:i,gif:o,poll:r,contact:c,isSilent:d,scheduledAt:l,groupedId:u,noWebPage:p,sendAs:f,serverTimeOffset:h},m){const _=function(e,t,n,s,a,i,o,r,c,d,l,u,g=0){const p=fe++,f=a&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:a,size:i}=e;if(e.quick){const{width:o,height:r,duration:c}=e.quick;return a.startsWith("image/")?{photo:{id:ge,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:ge,mimeType:a,duration:c||0,fileName:t,width:o,height:r,blobUrl:n,...s&&{thumbnail:{width:o,height:r,dataUri:s}},size:i}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=k(n,63);return{voice:{id:ge,duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{id:ge,mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}(a),h="chatTypeChannel"===e.type;return{id:p,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...i&&{sticker:i},...o&&{video:o},...r&&De(r,p),...c&&{contact:c}},date:l||Math.round(Date.now()/1e3)+g,isOutgoing:!h,senderId:(null==u?void 0:u.id)||pe,...s&&{replyToMessageId:s},...d&&{groupedId:d,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...l&&{isScheduled:!0}}}(e,t,n,s,a,i,o,r,c,u,l,f,h);ts({"@type":_.isScheduled?"newScheduledMessage":"newMessage",id:_.id,chatId:e.id,message:_}),setTimeout((()=>{ts({"@type":_.isScheduled?"updateScheduledMessage":"updateMessage",id:_.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const y=ee();if(I.localMessages[String(y)]=_,u)return function({chat:e,text:t,entities:n,replyingTo:s,attachment:a,groupedId:i,isSilent:o,scheduledAt:r,sendAs:c},d,l,u){let p=-1;os[i]||(os[i]={counter:0,singleMediaByIndex:{}}),p=os[i].counter++;const f=as;return as=(async()=>{let h;try{h=await ds(l,a,u)}catch(e){return os[i].counter--,void await f}const m=await async function(e,t){const n=await Yt(new g.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof g.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof g.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:s}}=n;return new g.Api.InputMediaPhoto({id:new g.Api.InputPhoto({id:e,accessHash:t,fileReference:s})})}if(n instanceof g.Api.MessageMediaDocument&&n.document&&n.document instanceof g.Api.Document){const{document:{id:e,accessHash:t,fileReference:s}}=n;return new g.Api.InputMediaDocument({id:new g.Api.InputDocument({id:e,accessHash:t,fileReference:s})})}}($(e.id,e.accessHash),h);if(await f,!m)return void os[i].counter--;if(os[i].singleMediaByIndex[p]=new g.Api.InputSingleMedia({media:m,randomId:d,message:t||"",entities:n?n.map(ne):void 0}),Object.keys(os[i].singleMediaByIndex).length{let u;if(a)try{u=await ds(_,a,m)}catch(e){return void await b}else i?u=Y(i):o?u=Y(o):r?u=function(e,t){const{summary:n,quiz:s}=e,a=new g.Api.Poll({id:t,publicVoters:n.isPublic,question:n.question,answers:n.answers.map((({text:e,option:t})=>new g.Api.PollAnswer({text:e,option:z(t)}))),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map(z),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(ne):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(r,y):c&&(u=new g.Api.InputMediaContact({phoneNumber:c.phoneNumber,firstName:c.firstName,lastName:c.lastName,vcard:""}));await b;const h=u?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await Yt(new h({clearDraft:!0,message:t||"",entities:n?n.map(ne):void 0,peer:$(e.id,e.accessHash),randomId:y,...d&&{silent:d},...l&&{scheduleDate:l},...s&&{replyToMsgId:s},...u&&{media:u},...p&&{noWebpage:p},...f&&{sendAs:$(f.id,f.accessHash)}}),!0)})(),as}const os={};async function rs({chat:e,message:t,text:n,entities:s,noWebPage:a,serverTimeOffset:i}){const o=1e3*t.date>Date.now()+1e3*i,r={content:{...t.content,...n&&{text:{text:n,entities:s}}}};ts({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:r}),I.localMessages[t.id]={...t,...r};const c=s&&s.map(ne);await Yt(new g.Api.messages.EditMessage({message:n||"",entities:c,peer:$(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function cs({chat:e,message:t,scheduledAt:n}){await Yt(new g.Api.messages.EditMessage({peer:$(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function ds(e,t,n){const{filename:s,blobUrl:a,mimeType:i,quick:o,voice:d}=t,l=await async function(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}(a,s),u=t=>{n.isCanceled?u.isCanceled=!0:n(t,e.id)},p=await tn(l,u),f=[new g.Api.DocumentAttributeFilename({fileName:s})];if(o){if(r.has(i))return new g.Api.InputMediaUploadedPhoto({file:p});if(c.has(i)){const{width:e,height:t,duration:n}=o;void 0!==n&&f.push(new g.Api.DocumentAttributeVideo({duration:n,w:e,h:t,supportsStreaming:!0}))}}if(d){const{duration:e,waveform:t}=d,{data:n}=k(t,63);f.push(new g.Api.DocumentAttributeAudio({voice:!0,duration:e,waveform:es.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function ls({chat:e,messageId:t,isUnpin:n,isOneSide:s,isSilent:a}){await Yt(new g.Api.messages.UpdatePinnedMessage({peer:$(e.id,e.accessHash),id:t,...n&&{unpin:!0},...s&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function us({chat:e}){await Yt(new g.Api.messages.UnpinAllMessages({peer:$(e.id,e.accessHash)}),!0)}async function gs({chat:e,messageIds:t,shouldDeleteForAll:n}){const s="channel"===j(e.id);await Yt(s?new g.Api.channels.DeleteMessages({channel:Q(e.id,e.accessHash),id:t}):new g.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&ts({"@type":"deleteMessages",ids:t,...s&&{chatId:e.id}})}async function ps({chat:e,messageIds:t}){await Yt(new g.Api.messages.DeleteScheduledMessages({peer:$(e.id,e.accessHash),id:t}))&&ts({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function fs({chat:e,shouldDeleteForAll:t,maxId:n}){const s="channel"===j(e.id);await Yt(s?new g.Api.channels.DeleteHistory({channel:Q(e.id,e.accessHash),maxId:n}):new g.Api.messages.DeleteHistory({peer:$(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&ts({"@type":"deleteHistory",chatId:e.id})}async function hs({peer:e,messageIds:t,reason:n,description:s}){return await Yt(new g.Api.messages.Report({peer:$(e.id,e.accessHash),id:t,reason:de(n),message:s}))}async function ms({peer:e,threadId:t,action:n}){const s=function(e){switch(e.type){case"cancel":return new g.Api.SendMessageCancelAction;case"typing":return new g.Api.SendMessageTypingAction;case"recordAudio":return new g.Api.SendMessageRecordAudioAction;case"chooseSticker":return new g.Api.SendMessageChooseStickerAction}}(n);if(s)return await Yt(new g.Api.messages.SetTyping({peer:$(e.id,e.accessHash),topMsgId:t,action:s}))}async function _s({chat:e,threadId:t,maxId:n,serverTimeOffset:s}){const a="channel"===j(e.id);a&&-1===t?await Yt(new g.Api.channels.ReadHistory({channel:Q(e.id,e.accessHash),maxId:n})):a?await Yt(new g.Api.messages.ReadDiscussion({peer:$(e.id,e.accessHash),msgId:t,readMaxId:n})):await Yt(new g.Api.messages.ReadHistory({peer:$(e.id,e.accessHash),maxId:n})),-1===t?un({chat:e,serverTimeOffset:s,noLastMessage:!0}):bs({chat:e,threadId:t})}async function ys({chat:e,messageIds:t}){const n="channel"===j(e.id);await Yt(n?new g.Api.channels.ReadMessageContents({channel:Q(e.id,e.accessHash),id:t}):new g.Api.messages.ReadMessageContents({id:t})),ts({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function bs({chat:e,threadId:t}){const[n,s]=await Promise.all([Yt(new g.Api.messages.GetDiscussionMessage({peer:$(e.id,e.accessHash),msgId:t})),Yt(new g.Api.messages.GetReplies({peer:$(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=L(n.messages[0]);return a?(ts({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{threadId:t,topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:s instanceof g.Api.messages.ChannelMessages?s.count:void 0},firstMessageId:s&&"messages"in s&&s.messages.length?s.messages[0].id:void 0}),n.chats.map((e=>qe(e))).filter(Boolean).forEach((e=>{ts({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:a}):void 0}async function ws({chatOrUser:e,type:t,query:n,topMessageId:s,minDate:a,maxDate:i,...o}){let r;switch(t){case"media":r=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":r=new g.Api.InputMessagesFilterDocument;break;case"links":r=new g.Api.InputMessagesFilterUrl;break;case"audio":r=new g.Api.InputMessagesFilterMusic;break;case"voice":r=new g.Api.InputMessagesFilterRoundVoice;break;case"profilePhoto":r=new g.Api.InputMessagesFilterChatPhotos;break;case"text":default:r=new g.Api.InputMessagesFilterEmpty}const c=await Yt(new g.Api.messages.Search({peer:$(e.id,e.accessHash),filter:r,q:n||"",topMsgId:s,minDate:a,maxDate:i,...o}));if(!c||c instanceof g.Api.messages.MessagesNotModified||!c.messages)return;Rs(c);const d=c.messages.map(me).filter(Boolean),l=c.users.map(tt).filter(Boolean);let u,p=d.length;return(c instanceof g.Api.messages.MessagesSlice||c instanceof g.Api.messages.ChannelMessages)&&(p=c.count,d.length&&(u=d[d.length-1].id)),{messages:d,users:l,totalCount:p,nextOffsetId:u}}async function Cs({query:e,offsetRate:t=0,limit:n,type:s="text",minDate:a,maxDate:i}){let o;switch(s){case"media":o=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":o=new g.Api.InputMessagesFilterDocument;break;case"links":o=new g.Api.InputMessagesFilterUrl;break;case"audio":o=new g.Api.InputMessagesFilterMusic;break;case"voice":o=new g.Api.InputMessagesFilterRoundVoice;break;case"text":default:if(!(e||i&&a))return;o=new g.Api.InputMessagesFilterEmpty}const r=await Yt(new g.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new g.Api.InputPeerEmpty,limit:n,filter:o,folderId:0,minDate:a,maxDate:i}));if(!r||r instanceof g.Api.messages.MessagesNotModified||!r.messages)return;Rs({chats:r.chats,users:r.users,messages:r.messages});const c=r.chats.map((e=>qe(e))).filter(Boolean),d=r.users.map(tt).filter(Boolean),l=r.messages.map(me).filter(Boolean);let u,p=l.length;return(r instanceof g.Api.messages.MessagesSlice||r instanceof g.Api.messages.ChannelMessages)&&(p=r.count,l.length&&(u=l[l.length-1].id)),{messages:l,users:d,chats:c,totalCount:p,nextRate:"nextRate"in r&&r.nextRate?r.nextRate:u}}async function vs({message:e}){const t=await Yt(new g.Api.messages.GetWebPagePreview({message:e}));return t&&Ue(t)}async function Is({chat:e,messageId:t,options:n}){const{id:s,accessHash:a}=e;await Yt(new g.Api.messages.SendVote({peer:$(s,a),msgId:t,options:n.map(z)}),!0)}async function As({chat:e,messageId:t,option:n,offset:s,limit:a,shouldResetVoters:i}){const{id:o,accessHash:r}=e,c=await Yt(new g.Api.messages.GetPollVotes({peer:$(o,r),id:t,...n&&{option:z(n)},...s&&{offset:s},...a&&{limit:a}}));if(!c)return;Rs({chats:[],users:c.users,messages:[]});const d=c.users.map(tt).filter(Boolean),l=c.votes.map((e=>({userId:e.userId,date:e.date})));return{count:c.count,votes:l,users:d,nextOffset:c.nextOffset,shouldResetVoters:i}}async function Ss({fromChat:e,toChat:t,messages:n,serverTimeOffset:s,isSilent:a,scheduledAt:i,sendAs:o}){const r=n.map((({id:e})=>e)),c=n.map(ee);n.forEach(((e,n)=>{const a=function(e,t,n,s){const a=fe++,{content:i,chatId:o,id:r,senderId:c,groupedId:d,isInAlbum:l}=t,u=i.audio,g=e.id===pe&&(o!==e.id||t.forwardInfo)&&!u;return{id:a,chatId:e.id,content:i,date:s||Math.round(Date.now()/1e3)+n,isOutgoing:!g&&"chatTypeChannel"!==e.type,senderId:pe,sendingState:"messageSendingStatePending",groupedId:d,isInAlbum:l,...c!==pe&&!u&&{forwardInfo:{date:t.date,isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(t,e,s,i);I.localMessages[String(c[n])]=a,ts({"@type":a.isScheduled?"newScheduledMessage":"newMessage",id:a.id,chatId:t.id,message:a})})),await Yt(new g.Api.messages.ForwardMessages({fromPeer:$(e.id,e.accessHash),toPeer:$(t.id,t.accessHash),randomId:c,id:r,...a&&{sil2ent:a},...i&&{scheduleDate:i},...o&&{sendAs:$(o.id,o.accessHash)}}),!0)}async function Ps({chat:e,timestamp:t}){const n=await Yt(new g.Api.messages.GetHistory({peer:$(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof g.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function Ms({chat:e}){const{id:t,accessHash:n}=e,s=await Yt(new g.Api.messages.GetScheduledHistory({peer:$(t,n)}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages)return Rs(s),{messages:s.messages.map(me).filter(Boolean)}}async function ks({chat:e,ids:t}){const{id:n,accessHash:s}=e;await Yt(new g.Api.messages.SendScheduledMessages({peer:$(n,s),id:t}),!0)}function Rs(e){G(e.users),G(e.chats),e.messages.forEach((e=>{(e instanceof g.Api.Message&&se(e)||e instanceof g.Api.MessageService&&function(e){return"photo"in e.action&&e.action.photo instanceof g.Api.Photo}(e))&&O(e)}))}async function Us({chat:e}){const t=await Yt(new g.Api.messages.Search({peer:$(e.id,e.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(t&&!(t instanceof g.Api.messages.MessagesNotModified)&&t.messages)return Rs(t),{messages:t.messages.map(me).filter(Boolean),users:t.users.map(tt).filter(Boolean),chats:t.chats.map((e=>qe(e))).filter(Boolean)}}async function Es({chat:e,messageId:t}){const n=await Yt(new g.Api.messages.GetMessageReadParticipants({peer:$(e.id,e.accessHash),msgId:t}));return n?n.map(String):void 0}async function Ds({chat:e}){const t=await Yt(new g.Api.channels.GetSendAs({peer:$(e.id,e.accessHash)}));if(t)return G(t.users),G(t.chats),{users:t.users.map(tt).filter(Boolean),chats:t.chats.map((e=>qe(e))).filter(Boolean),ids:t.peers.map(N)}}function Ts({sendAs:e,chat:t}){return Yt(new g.Api.messages.SaveDefaultSendAs({peer:$(t.id,t.accessHash),sendAs:$(e.id,e.accessHash)}))}async function Bs({chat:e}){const t=await Yt(new g.Api.channels.GetSponsoredMessages({channel:$(e.id,e.accessHash)}));if(t&&t.messages.length)return Rs(t),{messages:t.messages.map(he).filter(Boolean),users:t.users.map(tt).filter(Boolean),chats:t.chats.map((e=>qe(e))).filter(Boolean)}}async function xs({chat:e,random:t}){await Yt(new g.Api.channels.ViewSponsoredMessage({channel:$(e.id,e.accessHash),randomId:z(t)}))}let Vs,Ns,Fs,Ls;async function Os({id:e,accessHash:t}){const n=Q(e,t);if(!(n instanceof g.Api.InputUser))return;const s=await Yt(new g.Api.users.GetFullUser({id:n}));if(!s)return;const a=et(s);Vs({"@type":"updateUser",id:e,user:{fullInfo:a.fullInfo}})}async function qs(e,t,n){const s=await Yt(new g.Api.messages.GetCommonChats({userId:Q(e,t),maxId:n?le(n,j(n)):void 0,limit:100}));if(!s)return;Qs(s);const a=[],i=[];return s.chats.forEach((e=>{const t=qe(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function Hs(){const e=await Yt(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function Gs(){const e=await Yt(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(tt).filter((e=>!!e&&!e.isSelf));return{ids:t.map((({id:e})=>e)),users:t}}async function Ks(){const e=await Yt(new g.Api.contacts.GetContacts({hash:U()("0")}));if(e&&!(e instanceof g.Api.contacts.ContactsNotModified))return e.users.forEach((e=>{e instanceof g.Api.User&&(I.users[V(e.id,"user")]=e)})),{users:e.users.map(tt).filter(Boolean),chats:e.users.map((e=>qe(e))).filter(Boolean)}}async function zs({users:e}){const t=await Yt(new g.Api.users.GetUsers({id:e.map((({id:e,accessHash:t})=>$(e,t)))}));if(t&&t.length)return t.forEach((e=>{e instanceof g.Api.User&&(I.users[V(e.id,"user")]=e)})),at(t)}function js({phone:e,firstName:t,lastName:n}){return Yt(new g.Api.contacts.ImportContacts({contacts:[ae({phone:e||"",firstName:t||"",lastName:n||""})]}),!0)}function Ws({id:e,accessHash:t,phoneNumber:n="",firstName:s="",lastName:a=""}){return Yt(new g.Api.contacts.AddContact({id:Q(e,t),firstName:s,lastName:a,phone:n}),!0)}async function $s({id:e,accessHash:t}){const n=Q(e,t);n instanceof g.Api.InputUser&&await Yt(new g.Api.contacts.DeleteContacts({id:[n]}))&&Vs({"@type":"deleteContact",id:e})}async function Js(e,t){if(e){const{id:t,accessHash:n}=e,s=await Yt(new g.Api.photos.GetUserPhotos({userId:Q(t,n),limit:40,offset:0,maxId:U()("0")}));if(!s)return;return Qs(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(C)}}const n=await ws({chatOrUser:t,type:"profilePhoto",limit:40});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map((e=>e.content.action.photo)).filter(Boolean),users:a}}function Qs(e){"chats"in e&&G(e.chats),"photos"in e&&e.photos.forEach(q)}async function Xs({hash:e="0"}){const t=await Yt(new g.Api.messages.GetAllStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.AllStickersNotModified))return t.sets.forEach((e=>{var t;null!==(t=e.thumbs)&&void 0!==t&&t.length&&(I.stickerSets[String(e.id)]=e)})),{hash:String(t.hash),sets:t.sets.map(P)}}async function Zs({hash:e="0"}){const t=await Yt(new g.Api.messages.GetRecentStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(t.hash),stickers:ga(t.stickers.slice(0,20))}}async function Ys({hash:e="0"}){const t=await Yt(new g.Api.messages.GetFavedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(t.hash),stickers:ga(t.stickers)}}async function ea({hash:e="0"}){const t=await Yt(new g.Api.messages.GetFeaturedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FeaturedStickersNotModified))return{hash:String(t.hash),sets:t.sets.map(M)}}async function ta({sticker:e,unfave:t}){const n=new g.Api.messages.FaveSticker({id:Z(e),unfave:t});await Yt(n)&&Ns({"@type":"updateFavoriteStickers"})}async function na({stickerSetShortName:e,stickerSetId:t,accessHash:n}){const s=await Yt(new g.Api.messages.GetStickerSet({stickerset:t?X(t,n):(a=e,new g.Api.InputStickerSetShortName({shortName:a}))}));var a,i;if(s instanceof g.Api.messages.StickerSet)return{set:P(s.set),stickers:ga(s.documents),packs:(i=s.packs,i.reduce(((e,{emoticon:t,documents:n})=>(e[t]=n.map((e=>S(I.documents[String(e)]))).filter(Boolean),e)),{}))}}async function sa(){const e=await Yt(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e instanceof g.Api.messages.StickerSet)return{set:P(e.set),stickers:ga(e.documents)}}async function aa(){const e=await Yt(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmojiAnimations}));if(e instanceof g.Api.messages.StickerSet)return{set:P(e.set),stickers:ga(e.documents)}}async function ia({query:e,hash:t="0"}){const n=await Yt(new g.Api.messages.SearchStickerSets({q:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.FoundStickerSetsNotModified))return{hash:String(n.hash),sets:n.sets.map(M)}}async function oa({hash:e="0"}){const t=await Yt(new g.Api.messages.GetSavedGifs({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(t.hash),gifs:pa(t.gifs)}}async function ra({stickerSetId:e,accessHash:t}){await Yt(new g.Api.messages.InstallStickerSet({stickerset:X(e,t)}))&&Ns({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function ca({stickerSetId:e,accessHash:t}){await Yt(new g.Api.messages.UninstallStickerSet({stickerset:X(e,t)}))&&Ns({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function da({query:e,offset:t=""}){if(!Fs){const e=await Yt(new g.Api.help.GetConfig);if(!e)return;const t=await Yt(new g.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof g.Api.User))return;Fs=new g.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await Yt(new g.Api.messages.GetInlineBotResults({bot:Fs,peer:new g.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map((e=>{if(e instanceof g.Api.BotInlineMediaResult)return e.document})).filter(Boolean);return{nextOffset:n.nextOffset,gifs:pa(s)}}async function la({emoji:e,hash:t="0"}){const n=await Yt(new g.Api.messages.GetStickers({emoticon:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.StickersNotModified))return{stickers:ga(n.stickers),hash:String(n.hash)}}async function ua({language:e,fromVersion:t}){const n=await Yt(new g.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce(((e,t)=>(e[t.keyword]=t.emoticons,e)),{})}}function ga(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=S(e);if(t)return I.documents[String(e.id)]=e,t}})).filter(Boolean)}function pa(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=Pe(e);if(t)return I.documents[String(e.id)]=e,t}})).filter(Boolean)}function fa({username:e}){return Yt(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:e}))}async function ha({chat:e,username:t}){await Yt(new g.Api.channels.UpdateUsername({channel:Q(e.id,e.accessHash),username:t}))&&Ls({"@type":"updateChat",id:e.id,chat:{username:t}})}async function ma({chat:e,usageLimit:t,expireDate:n}){const s=await Yt(new g.Api.messages.ExportChatInvite({peer:$(e.id,e.accessHash),usageLimit:t,expireDate:n}));if(s)return Ls({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:s.link}}),s.link}const _a={EMAIL_UNCONFIRMED:"Email unconfirmed",EMAIL_HASH_EXPIRED:"Email hash expired",NEW_SALT_INVALID:"The new salt is invalid",NEW_SETTINGS_INVALID:"The new password settings are invalid",CODE_INVALID:"Invalid Code",PASSWORD_HASH_INVALID:"Invalid Password"},ya={};let ba,wa;async function Ca(){const e=await Yt(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function va(e){return ba({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{ya.resolve=e,ya.reject=t}))}async function Ia(e){try{return await nn({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return ka(e),!1}}async function Aa(e){try{return await nn({currentPassword:e}),!0}catch(e){return ka(e),!1}}async function Sa(e,t,n,s){try{return await nn({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:va,onEmailCodeError:ka}),!0}catch(e){return ka(e),!1}}async function Pa(e,t){try{return await nn({currentPassword:e,newPassword:e,email:t,emailCodeCallback:va,onEmailCodeError:ka}),!0}catch(e){return ka(e),!1}}function Ma(e){ya.resolve(e)}function ka(e){let t;if(e instanceof g.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?`${n} hours`:"an hour")}else t=_a[e.message];t||(t="Unexpected Error"),ba({"@type":"updateTwoFaError",message:t})}async function Ra({call:e}){const t=await Yt(new g.Api.phone.GetGroupCall({call:ue(e)}));if(!t)return;G(t.users),G(t.chats);const n=t.users.map(tt).filter(Boolean),s=t.chats.map((e=>qe(e))).filter(Boolean);return{groupCall:ft(t.call),users:n,chats:s}}function Ua({call:e}){return Yt(new g.Api.phone.DiscardGroupCall({call:ue(e)}),!0)}function Ea({call:e,participant:t,muted:n,presentationPaused:s,videoStopped:a,videoPaused:i,volume:o,raiseHand:r}){return Yt(new g.Api.phone.EditGroupCallParticipant({call:ue(e),participant:$(t.id,t.accessHash),...void 0!==a&&{videoStopped:a},...void 0!==i&&{videoPaused:i},...void 0!==n&&{muted:n},...void 0!==s&&{presentationPaused:s},...void 0!==r&&{raiseHand:r},...void 0!==o&&{volume:o}}),!0)}function Da({groupCall:e,title:t}){return Yt(new g.Api.phone.EditGroupCallTitle({title:t,call:ue(e)}),!0)}async function Ta({call:e,canSelfUnmute:t}){const n=await Yt(new g.Api.phone.ExportGroupCallInvite({canSelfUnmute:t||void 0,call:ue(e)}));if(n)return n.link}async function Ba({call:e,offset:t}){const n=await Yt(new g.Api.phone.GetGroupParticipants({call:ue(e),ids:[],sources:[],offset:t||"",limit:100}));if(!n)return;G(n.users),G(n.chats);const s=n.users.map(tt).filter(Boolean),a=n.chats.map((e=>qe(e))).filter(Boolean);return wa({"@type":"updateGroupCallParticipants",groupCallId:e.id,participants:n.participants.map(ut),nextOffset:n.nextOffset}),{users:s,chats:a}}function xa({call:e}){return Yt(new g.Api.phone.LeaveGroupCall({call:ue(e)}),!0)}async function Va({call:e,inviteHash:t,params:n}){const s=await Yt(new g.Api.phone.JoinGroupCall({call:ue(e),joinAs:new g.Api.InputPeerSelf,muted:!0,videoStopped:!0,params:new g.Api.DataJSON({data:JSON.stringify(n)}),inviteHash:t}));if(s&&s instanceof g.Api.Updates){const e=s.updates.find((e=>e instanceof g.Api.UpdateGroupCall));if(!(e instanceof g.Api.UpdateGroupCall))return;return ft(e.call)}}async function Na({peer:e}){const t=(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(4),!0,!0).toJSNumber(),n=await Yt(new g.Api.phone.CreateGroupCall({peer:$(e.id,e.accessHash),randomId:t}));if(n&&n instanceof g.Api.Updates){const e=n.updates[0];if(e instanceof g.Api.UpdateGroupCall)return ft(e.call)}}function Fa({call:e,params:t}){return Yt(new g.Api.phone.JoinGroupCallPresentation({call:ue(e),params:new g.Api.DataJSON({data:JSON.stringify(t)})}),!0)}function La({call:e,subscribed:t}){return Yt(new g.Api.phone.ToggleGroupCallStartSubscription({call:ue(e),subscribed:t}),!0)}function Oa({call:e}){return Yt(new g.Api.phone.LeaveGroupCallPresentation({call:ue(e)}),!0)}var qa=n(8764).Buffer;function Ha(e){const{emojies_sounds:t}=e;return Object.keys(t).reduce(((e,n)=>{const s=t[n];return I.documents[s.id]=new g.Api.Document({id:U()(s.id),accessHash:U()(s.access_hash),dcId:1,mimeType:"audio/ogg",fileReference:qa.from(atob(s.file_reference_base64.replace(/-/g,"+").replace(/_/g,"/")))}),e[n]=s.id,e}),{})}const Ga=["ar","fa","id","ko","uz"];function Ka({firstName:e,lastName:t,about:n}){return Yt(new g.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}),!0)}function za(e){return Yt(new g.Api.account.CheckUsername({username:e}))}function ja(e){return Yt(new g.Api.account.UpdateUsername({username:e}),!0)}async function Wa(e){const t=await tn(e);return Yt(new g.Api.photos.UploadProfilePhoto({file:t}),!0)}async function $a(e){const t=await tn(e);await Yt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function Ja(){const e=await Yt(new g.Api.account.GetWallPapers({hash:U()("0")}));if(!e||e instanceof g.Api.account.WallPapersNotModified)return;const t=e.wallpapers.filter((e=>e instanceof g.Api.WallPaper&&e.document instanceof g.Api.Document&&!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return t.forEach((e=>{I.documents[String(e.document.id)]=e.document})),{wallpapers:t.map(it).filter(Boolean)}}async function Qa(e){const t=await tn(e),n=await Yt(new g.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new g.Api.WallPaperSettings}));if(!(n&&n instanceof g.Api.WallPaper))return;const s=it(n);return s?(I.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function Xa(){const e=await Yt(new g.Api.contacts.GetBlocked({limit:100}));if(e)return yi(e),{users:e.users.map(tt).filter(Boolean),chats:e.chats.map((e=>qe(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>N(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function Za(e,t){return Yt(new g.Api.contacts.Block({id:$(e,t)}))}function Ya(e,t){return Yt(new g.Api.contacts.Unblock({id:$(e,t)}))}async function ei(){const e=await Yt(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map(ot)}function ti(e){return Yt(new g.Api.account.ResetAuthorization({hash:U()(e)}))}function ni(){return Yt(new g.Api.auth.ResetAuthorizations)}async function si({serverTimeOffset:e}){const t=await Yt(new g.Api.account.GetNotifyExceptions({compareSound:!0}),void 0,void 0,!0);if(t instanceof g.Api.Updates||t instanceof g.Api.UpdatesCombined)return yi(t),t.updates.reduce(((t,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(t.push(ct(n.notifySettings,n.peer.peer,e)),t):t),[])}async function ai({serverTimeOffset:e}){const[t,n,s,a]=await Promise.all([Yt(new g.Api.account.GetContactSignUpNotification),Yt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),Yt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),Yt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyBroadcasts}))]);if(!n||!s||!a)return!1;const{silent:i,muteUntil:o,showPreviews:r}=n,{silent:c,muteUntil:d,showPreviews:l}=s,{silent:u,muteUntil:p,showPreviews:f}=a;return{hasContactJoinedNotifications:!t,hasPrivateChatsNotifications:!(i||"number"==typeof o&&xe(e)Yt(new g.Api.langpack.GetLangPack({langPack:e,langCode:Ga.includes(t)?`${t}-raw`:t})))))).filter(Boolean).map((e=>p(e.strings.map(_),"key")));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function di({langPack:e,langCode:t,keys:n}){const s=await Yt(new g.Api.langpack.GetStrings({langPack:e,langCode:Ga.includes(t)?`${t}-raw`:t,keys:n}));if(s)return s.map(_)}async function li(e){const t=ce(e),n=await Yt(new g.Api.account.GetPrivacy({key:t}));if(n)return yi(n),rt(n.rules)}function ui(e){const t=Wt.session.getAuthKey().getKey();return Yt(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function gi(e){return Yt(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function pi(e,t){const n=ce(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((({id:e,accessHash:t})=>Q(e,t)))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((({id:e})=>Q(e)))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((({id:e,accessHash:t})=>Q(e,t)))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((({id:e})=>Q(e)))})),t.visibility){case"everybody":s.push(new g.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new g.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new g.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new g.Api.InputPrivacyValueDisallowAll)}const a=await Yt(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return yi(a),rt(a.rules)}async function fi(e){await Yt(new g.Api.account.UpdateStatus({offline:!e}))}async function hi(){const e=await Yt(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function mi(e){return Yt(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}async function _i(){const e=await Yt(new g.Api.help.GetAppConfig);if(e)return function(e){const t=lt(e);return{emojiSounds:Ha(t),defaultReaction:t.reactions_default}}(e)}function yi(e){G(e.users),G(e.chats)}async function bi({langCode:e="en"}){const t=await Yt(new g.Api.help.GetCountriesList({langCode:e}));if(t instanceof g.Api.help.CountriesList)return n=t.countries,{phoneCodes:(s=n.filter((e=>!e.hidden)).map((e=>e.countryCodes.map((t=>dt(e,t))))),s.reduce(((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e)),[])).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName))),general:n.filter((e=>!e.hidden)).map((e=>dt(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var n,s}function wi(e){return e?f(e,["url","mimeType"]):void 0}async function Ci({chatId:e,accessHash:t,messageId:n,data:s}){const a=await Yt(new g.Api.messages.GetBotCallbackAnswer({peer:$(e,t),msgId:n,data:z(s)}));return a?_(a):void 0}async function vi(){const e=await Yt(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(tt).filter(Boolean);return{ids:t.map((({id:e})=>e)),users:t}}async function Ii({username:e}){const t=await Yt(new g.Api.contacts.ResolveUsername({username:e}));if(t&&t.users[0]instanceof g.Api.User&&t.users[0].bot&&t.users[0].botInlinePlaceholder)return H(t.users[0]),{user:tt(t.users[0]),chat:qe(t.users[0])}}async function Ai({bot:e,chat:t,query:n,offset:s=""}){const a=await Yt(new g.Api.messages.GetInlineBotResults({bot:$(e.id,e.accessHash),peer:$(t.id,t.accessHash),query:n,offset:s}));var i,o,r,c,d;if(a)return G(a.users),{isGallery:Boolean(a.gallery),help:e.botPlaceholder,nextOffset:(c=e.username,d=a.nextOffset,"gif"===c&&"0"===d?"":d),switchPm:(r=a.switchPm,r?f(r,["text","startParam"]):void 0),users:a.users.map(tt).filter(Boolean),results:(i=String(a.queryId),o=a.results,o.map((e=>{return e instanceof g.Api.BotInlineMediaResult?(e.document instanceof g.Api.Document&&(t=e.document,I.documents[String(t.id)]=t),e.photo instanceof g.Api.Photo&&(n=e.photo,I.photos[String(n.id)]=n),function(e,t){const{id:n,type:s,title:a,description:i,photo:o,document:r}=e;return{id:n,queryId:t,type:s,title:a,description:i,..."sticker"===s&&r instanceof g.Api.Document&&{sticker:S(r)},...o instanceof g.Api.Photo&&{photo:C(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:Pe(r)},..."video"===s&&r instanceof g.Api.Document&&{thumbnail:w(r.thumbs)}}}(e,i)):(e.thumb&&(s=e.thumb,I.webDocuments[s.url]=s),function(e,t){const{id:n,type:s,title:a,description:i,url:o,thumb:r}=e;return{id:n,queryId:t,type:s,title:a,description:i,url:o,webThumbnail:wi(r)}}(e,i));var t,n,s})))}}async function Si({chat:e,resultId:t,queryId:n,replyingTo:s,sendAs:a}){const i=ee();await Yt(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:i,queryId:U()(n),peer:$(e.id,e.accessHash),id:t,...s&&{replyToMsgId:s},...a&&{sendAs:$(a.id,a.accessHash)}}),!0)}async function Pi({bot:e,startParam:t}){const n=ee();await Yt(new g.Api.messages.StartBot({bot:$(e.id,e.accessHash),peer:$(e.id,e.accessHash),randomId:n,startParam:t}),!0)}function Mi(e){if(e)return Object.values(e).map((e=>({id:e.id,title:e.title,amount:e.prices.reduce(((e,t)=>e+Number(t.amount.value)),0),prices:e.prices.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)})))})))}async function ki({chat:e,messageId:t,requestInfo:n,shouldSave:s}){const a=await Yt(new g.Api.payments.ValidateRequestedInfo({peer:$(e.id,e.accessHash),msgId:t,save:s||void 0,info:re(n)}));if(!a)return;const{id:i,shippingOptions:o}=a;return i?{id:i,shippingOptions:Mi(o)}:void 0}function Ri({chat:e,messageId:t,formId:n,requestedInfoId:s,shippingOptionId:a,credentials:i}){return Yt(new g.Api.payments.SendPaymentForm({formId:U()(n),peer:$(e.id,e.accessHash),msgId:t,requestedInfoId:s,shippingOptionId:a,credentials:new g.Api.InputPaymentCredentials({save:i.save,data:new g.Api.DataJSON({data:JSON.stringify(i.data)})})}),!0)}async function Ui({chat:e,messageId:t}){const n=await Yt(new g.Api.payments.GetPaymentForm({peer:$(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{formId:t,canSaveCredentials:n,passwordMissing:s,providerId:a,nativeProvider:i,nativeParams:o,savedInfo:r,invoice:c}=e,{test:d,nameRequested:l,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:y}=c,b=y.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)}))),w=o?JSON.parse(o.data):{};return{canSaveCredentials:n,passwordMissing:s,formId:String(t),providerId:String(a),nativeProvider:i,savedInfo:r,invoice:{test:d,nameRequested:l,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:b},nativeParams:{needCardholderName:w.need_cardholder_name,needCountry:w.need_country,needZip:w.need_zip,publishableKey:w.publishable_key}}}(n)}async function Ei(e,t){const n=await Yt(new g.Api.payments.GetPaymentReceipt({peer:$(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{invoice:t,info:n,shipping:s,currency:a,totalAmount:i,credentialsTitle:o}=e,{shippingAddress:r,phone:c,name:d}=n||{},{prices:l}=t,u=l.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)})));let g,p;return s&&(g=s.prices.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)}))),p=s.title),{currency:a,prices:u,info:{shippingAddress:r,phone:c,name:d},totalAmount:Number(i.value),credentialsTitle:o,shippingPrices:g,shippingMethod:p}}(n)}function Di({chat:e,emoticon:t}){return Yt(new g.Api.messages.SetTyping({peer:$(e.id,e.accessHash),action:new g.Api.SendMessageEmojiInteractionSeen({emoticon:t})}))}function Ti({chat:e,emoticon:t,messageId:n,timestamps:s}){return Yt(new g.Api.messages.SetTyping({peer:$(e.id,e.accessHash),action:new g.Api.SendMessageEmojiInteraction({emoticon:t,msgId:n,interaction:new g.Api.DataJSON({data:JSON.stringify({v:1,a:s.map((e=>({t:e,i:1})))})})})}))}async function Bi(){const e=await Yt(new g.Api.messages.GetAvailableReactions({}));if(e&&!(e instanceof g.Api.messages.AvailableReactionsNotModified))return e.reactions.forEach((e=>{e.staticIcon instanceof g.Api.Document&&(I.documents[String(e.staticIcon.id)]=e.staticIcon),e.selectAnimation instanceof g.Api.Document&&(I.documents[String(e.selectAnimation.id)]=e.selectAnimation),e.aroundAnimation instanceof g.Api.Document&&(I.documents[String(e.aroundAnimation.id)]=e.aroundAnimation),e.centerIcon instanceof g.Api.Document&&(I.documents[String(e.centerIcon.id)]=e.centerIcon)})),e.reactions.map(Ce)}function xi({chat:e,messageId:t,reaction:n}){return Yt(new g.Api.messages.SendReaction({...n&&{reaction:n},peer:$(e.id,e.accessHash),msgId:t}),!0)}function Vi({ids:e,chat:t}){return Yt(new g.Api.messages.GetMessagesReactions({id:e,peer:$(t.id,t.accessHash)}),!0)}async function Ni({chat:e,messageId:t,reaction:n,offset:s}){const a=await Yt(new g.Api.messages.GetMessageReactionsList({peer:$(e.id,e.accessHash),id:t,...n&&{reaction:n},limit:100,...s&&{offset:s}}));if(!a)return;G(a.users);const{nextOffset:i,reactions:o,count:r}=a;return{users:a.users.map(tt).filter(Boolean),nextOffset:i,reactions:o.map(we),count:r}}function Fi({reaction:e}){return Yt(new g.Api.messages.SetDefaultReaction({reaction:e}))}let Li;async function Oi(e,t){Li=e,function(e){ht=e}(zi),function(e){It=e}(zi),function(e){on=e}(zi),function(e){ts=e}(zi),function(e){Vs=e}(zi),function(e){Ns=e}(zi),function(e){Ls=e}(zi),function(e){ba=e}(zi),function(e){wa=e}(zi),await async function(e,t){jt=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o}=t,r=new g.sessions.CallbackSession(a,Xt);self.isMovSupported=o,Wt=new g.TelegramClient(r,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.30.10 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),Wt.addEventHandler(Zt,zt),Wt.addEventHandler(wt,zt);try{try{await Wt.start({phoneNumber:At,phoneCode:St,password:Pt,firstAndLastNames:Mt,qrCode:kt,onError:Rt,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if("Disconnect"!==e.message)return void jt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}It(Ut("authorizationStateReady")),Xt(r.getSessionData()),jt({"@type":"updateApiReady"}),sn()}catch(e){throw e}}(zi,t)}const qi=function(e,t){let n,s=!1;return(...a)=>{n=a,s||(s=!0,e((()=>{s=!1,t(...n)})))}}((function(e,t=!1){l?t?u.push(e):l.push(e):(l=t?[]:[e],u=t?[e]:[],Promise.resolve().then((()=>{const e=l,t=u;l=void 0,u=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}),(function(e){if(!Ki||e!==Gi)return;const t=Ki;Ki=void 0,t.forEach(Li)}));let Hi,Gi,Ki;function zi(e){Ki?Ki.push(e):Ki=[e],Hi&&!o.has(e["@type"])||(Hi=function(e,t,n=!0){let s,a,i;return(...o)=>{a=!0,i=o,s||(n&&(a=!1,e(...i)),s=self.setInterval((()=>{if(!a)return self.clearInterval(s),void(s=void 0);a=!1,e(...i)}),t))}}(qi,i,!0),Gi=Math.random()),Hi(Gi)}self.onerror=e=>{console.error(e),$i({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),$i({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const ji=new Map;function Wi(e){$i({type:"update",update:e})}function $i(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await Oi(Wi,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:s}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];$i({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};ji.set(e,t),s.push(t)}const t=await function(e,...t){return a[e](...t)}(n,...s),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&$i({type:"methodResponse",messageId:e,response:t},i)}catch(t){e&&$i({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&ji.delete(e);break}case"cancelProgress":{const e=ji.get(t.messageId);e&&(e.isCanceled=!0);break}case"ping":$i({type:"methodResponse",messageId:t.messageId})}}},9618:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(6842);function o(e,t=!0,n=!1){let i=s.from(e);const o=i.length;t&&(i=i.reverse());let r=a(i.toString("hex"),16);return n&&Math.floor(r.toString("2").length/8)>=o&&(r=r.subtract(a(2).pow(a(8*o)))),r}function r(e,t=8){const n=a(e),i=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),s.isBuffer(e)||(e=s.from(e));let t=-1;for(let n=0;n>>8}return(-1^t)>>>0},generateRandomBytes:d,generateKeyDataFromNonce:async function(e,t){e=r(e,16),t=r(t,32);const[n,a,i]=await Promise.all([l(s.concat([t,e])),l(s.concat([e,t])),l(s.concat([t,t]))]);return{key:s.concat([n,a.slice(0,12)]),iv:s.concat([a.slice(12,20),i,t.slice(0,4)])}},sha1:l,sha256:function(e){const t=i.createHash("sha256");return t.update(e),t.digest()},bigIntMod:function(e,t){return e.remainder(t).add(t).remainder(t)},modExp:function(e,t,n){e=e.remainder(n);let s=a.one,i=e;for(;t.greater(a.zero);){const e=t.remainder(a(2));t=t.divide(a(2)),e.eq(a.one)&&(s=s.multiply(i),s=s.remainder(n)),i=i.multiply(i),i=i.remainder(n)}return s},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise((t=>setTimeout(t,e))),getByteArray:function(e,t=!1){const n=e.toString(2).length,s=Math.floor((n+8-1)/8);return c(a(e),s,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const t=s.alloc(4*e.length);for(let n=0;n{e=t})),resolve:e}}}},9674:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),{constructors:i}=n(7404),{readBigIntFromBuffer:o,readBufferFromBigInt:r,sha256:c,bigIntMod:d,modExp:l,generateRandomBytes:u}=n(9618),g=n(6842);function p(e,t){if(!s.from([199,28,174,185,198,177,201,4,142,108,82,47,112,241,63,115,152,13,64,35,142,62,33,193,73,52,208,55,86,61,147,15,72,25,138,10,167,193,64,88,34,148,147,210,37,48,244,219,250,51,111,110,10,201,37,19,149,67,174,212,76,206,124,55,32,253,81,246,148,88,112,90,198,140,212,254,107,107,19,171,220,151,70,81,41,105,50,132,84,241,143,175,140,89,95,100,36,119,254,150,187,42,148,29,91,205,29,74,200,204,73,136,7,8,250,155,55,142,60,79,58,144,96,190,230,124,249,164,164,166,149,129,16,81,144,126,22,39,83,181,107,15,107,65,13,186,116,216,168,75,42,20,179,20,78,14,241,40,71,84,253,23,237,149,13,89,101,180,185,221,70,88,45,177,23,141,22,156,107,196,101,176,214,255,156,163,146,143,239,91,154,228,228,24,252,21,232,62,190,160,248,127,169,255,94,237,112,5,13,237,40,73,244,123,249,89,217,86,133,12,233,41,133,31,13,129,21,246,53,177,5,238,46,78,21,208,75,36,84,191,111,79,173,240,52,177,4,3,17,156,216,227,185,47,204,91]).equals(e)||![3,4,5,7].includes(t))throw new Error("Changing passwords unsupported")}function f(e){return s.concat([s.alloc(256-e.length),e])}function h(e){return r(e,256,!1)}function m(e,t){const n=t.subtract(e);return!(n.lesser(a(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function _(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=u(256),t=o(e,!1),n=l(a(b),t,g);if(m(n,g)){const e=h(n),i=o(await c(s.concat([e,A])),!1);if(i.greater(a(0)))return[t,e,i]}}})(),E=d(w.subtract(M),g);if(!m(E,g))throw new Error("bad gB");const D=U.multiply(C),T=k.add(D),B=l(E,T,g),[x,V,N,F,L]=await Promise.all([c(h(B)),c(v),c(I),c(n.salt1),c(n.salt2)]),O=await c(s.concat([_(V,N),F,L,R,A,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:O})},computeDigest:async function(e,t){try{p(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return h(l(a(e.g),o(await y(e,t),!1),o(e.p,!1)))}}},8960:(e,t,n)=>{var s=n(8764).Buffer;const{constructors:a}=n(7404),i=s.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),o=s.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error(`Invalid message type: ${e.constructor.name}`)}},getInputPeer:function e(t,n=!0,s=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof a.User){if(t.isSelf&&n)return new a.InputPeerSelf;if(void 0===t.accessHash&&s)throw new Error("User without accessHash or min info cannot be input");return new a.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof a.Chat||t instanceof a.ChatEmpty||t instanceof a.ChatForbidden)return new a.InputPeerChat({chatId:t.id});if(t instanceof a.Channel){if(void 0===t.accessHash&&s)throw new TypeError("Channel without accessHash or min info cannot be input");return new a.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof a.ChannelForbidden?new a.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof a.InputUser?new a.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof a.InputChannel?new a.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof a.UserEmpty?new a.InputPeerEmpty:t instanceof a.UserFull?e(t.user):t instanceof a.ChatFull?new a.InputPeerChat({chatId:t.id}):t instanceof a.PeerChat?new a.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof a.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof a.Chat||e instanceof a.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=2097152e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const t=s.from(i);return t[164]=e[1],t[166]=e[2],s.concat([t,e.slice(3),o])},getDC:function(e,t=!1){switch(e){case 1:return{id:1,ipAddress:`zws1${t?"-1":""}.web.telegram.org`,port:443};case 2:return{id:2,ipAddress:`zws2${t?"-1":""}.web.telegram.org`,port:443};case 3:return{id:3,ipAddress:`zws3${t?"-1":""}.web.telegram.org`,port:443};case 4:return{id:4,ipAddress:`zws4${t?"-1":""}.web.telegram.org`,port:443};case 5:return{id:5,ipAddress:`zws5${t?"-1":""}.web.telegram.org`,port:443};default:throw new Error(`Cannot find the DC with the ID of ${e}`)}}}},1472:e=>{e.exports="0.0.2"},243:(e,t,n)=>{"use strict";n.r(t),n.d(t,{updateTwoFaSettings:()=>l});var s=n(7150),a=n.n(s),i=n(9618),o=n(9674),r=n(7873),c=n.n(r),d=n(8764).Buffer;async function l(e,{isCheckPassword:t,currentPassword:n,newPassword:s,hint:r="",email:l,emailCodeCallback:u,onEmailCodeError:g}){if(!s&&!n)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(l&&(!u||!g))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await e.invoke(new(a().account.GetPassword));p.newAlgo instanceof a().PasswordKdfAlgoUnknown||(p.newAlgo.salt1=d.concat([p.newAlgo.salt1,(0,i.generateRandomBytes)(32)])),!p.hasPassword&&n&&(n=void 0);const f=n?await(0,o.computeCheck)(p,n):new(a().InputCheckPasswordEmpty);if(t)await e.invoke(new(a().auth.CheckPassword)({password:f}));else try{await e.invoke(new(a().account.UpdatePasswordSettings)({password:f,newSettings:new(a().account.PasswordInputSettings)({newAlgo:p.newAlgo,newPasswordHash:s?await(0,o.computeDigest)(p.newAlgo,s):d.alloc(0),hint:r,email:l,newSecureSettings:void 0})}))}catch(t){if(!(t instanceof c().EmailUnconfirmedError))throw t;for(;;)try{const n=await u(t.codeLength);if(!n)throw new Error("Code is empty");await e.invoke(new(a().account.ConfirmPasswordEmail)({code:n}));break}catch(e){g(e)}}}},8742:(e,t,n)=>{var s=n(8764).Buffer;const a=n(7435),i=n(6748),{sleep:o}=n(9618),r=n(7873),c=n(3995),d=n(9618),l=n(8960),u=n(9270),{LAYER:g}=n(845),{constructors:p,requests:f}=n(7404),h=n(4046),{ConnectionTCPObfuscated:m}=n(2986),{authFlow:_,checkAuthorization:y}=n(1545),{downloadFile:b}=n(2288),{uploadFile:w}=n(4766),{updateTwoFaSettings:C}=n(243),v=131072,I=["w","y","d","x","c","m","b","a","s"];class A{constructor(e,t,n,s=A.DEFAULT_OPTIONS){if(!t||!n)throw Error('Your API ID or Hash are invalid. Please read "Requirements" on README.md');const o={...A.DEFAULT_OPTIONS,...s};if(this.apiId=t,this.apiHash=n,this._useIPV6=o.useIPV6,"string"==typeof o.baseLogger?this._log=new i:this._log=o.baseLogger,"string"!=typeof e&&e){if(!(e instanceof u))throw new Error("The given session must be str or a session instance")}else try{throw new Error("not implemented")}catch(t){e=new c}this.floodSleepLimit=o.floodSleepLimit,this._eventBuilders=[],this._phoneCodeHash={},this.session=e,this.apiId=parseInt(t,10),this.apiHash=n,this._requestRetries=o.requestRetries,this._connectionRetries=o.connectionRetries,this._retryDelay=o.retryDelay||0,o.proxy&&this._log.warn("proxies are not supported"),this._proxy=o.proxy,this._timeout=o.timeout,this._autoReconnect=o.autoReconnect,this._connection=o.connection,this._floodWaitedRequests={},this._initWith=e=>new f.InvokeWithLayer({layer:g,query:new f.InitConnection({apiId:this.apiId,deviceModel:o.deviceModel||a.type().toString()||"Unknown",systemVersion:o.systemVersion||a.release().toString()||"1.0",appVersion:o.appVersion||"1.0",langCode:o.langCode,langPack:"",systemLangCode:o.systemLangCode,query:e,proxy:void 0})}),this._args=o,this._config=void 0,this.phoneCodeHashes=[],this._exportedSenderPromises={},this._exportedSenderReleaseTimeouts={},this._additionalDcsDisabled=o.additionalDcsDisabled,this._loopStarted=!1,this._isSwitchingDc=!1,this._destroyed=!1}async connect(){await this._initSession(),void 0===this._sender&&(this._sender=new h(this.session.getAuthKey(),{logger:this._log,dcId:this.session.dcId,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),updateCallback:this._handleUpdate.bind(this),isMainSender:!0})),this._sender.userDisconnected=!1,this._sender._user_connected=!1,this._sender.isReconnecting=!1,this._sender._disconnected=!0;const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log,this._args.testServers);await this._sender.connect(e)?(this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new f.help.GetConfig({}))),this._loopStarted||(this._updateLoop(),this._loopStarted=!0),this._isSwitchingDc=!1):this._loopStarted||(this._updateLoop(),this._loopStarted=!0)}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"zws2.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;!this._destroyed;)if(await d.sleep(3e3),!this._sender.isReconnecting&&!this._isSwitchingDc){try{await k((()=>{return e=this._sender.send(new f.PingDelayDisconnect({pingId:d.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),disconnectDelay:6e4})),5e3,Promise.race([e,d.sleep(5e3).then((()=>Promise.reject(new Error("TIMEOUT"))))]);var e}),3,100)}catch(e){if(console.warn(e),this._sender.isReconnecting||this._isSwitchingDc)continue;await this.disconnect(),await this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new f.updates.GetState)}catch(e){}}await this.disconnect()}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._exportedSenderPromises).map((e=>e&&e.then((e=>{if(e)return e.disconnect()}))))),this._exportedSenderPromises={}}async destroy(){this._destroyed=!0;try{await this.disconnect()}catch(e){}this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info(`Reconnecting to new data center ${e}`);const t=l.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),this._isSwitchingDc=!0,await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}async _cleanupExportedSender(e){this.session.dcId!==e&&this.session.setAuthKey(void 0,e);const t=await this._exportedSenderPromises[e];this._exportedSenderPromises[e]=void 0,await t.disconnect()}async _connectSender(e,t){const n=l.getDC(t,!!e.authKey.getKey());for(;;)try{if(await e.connect(new this._connection(n.ipAddress,n.port,t,this._log,this._args.testServers)),this.session.dcId!==t&&!e._authenticated){this._log.info(`Exporting authorization for data center ${n.ipAddress}`);const s=await this.invoke(new f.auth.ExportAuthorization({dcId:t})),a=this._initWith(new f.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await e.send(a),e._authenticated=!0}return e.dcId=t,e.userDisconnected=!1,e}catch(t){console.error(t),await d.sleep(1e3),await e.disconnect()}}async _borrowExportedSender(e,t,n){if(this._additionalDcsDisabled)return;let s;this._exportedSenderPromises[e]&&!t||(this._exportedSenderPromises[e]=this._connectSender(n||this._createExportedSender(e),e));try{if(s=await this._exportedSenderPromises[e],!s.isConnected())return s.isConnecting?(await d.sleep(1e3),this._borrowExportedSender(e,!1,s)):this._borrowExportedSender(e,!0,s)}catch(t){return console.error(t),this._borrowExportedSender(e,!0)}return this._exportedSenderReleaseTimeouts[e]&&(clearTimeout(this._exportedSenderReleaseTimeouts[e]),this._exportedSenderReleaseTimeouts[e]=void 0),this._exportedSenderReleaseTimeouts[e]=setTimeout((()=>{this._exportedSenderReleaseTimeouts[e]=void 0,s.disconnect()}),3e4),s}_createExportedSender(e){return new h(this.session.getAuthKey(e),{logger:this._log,dcId:e,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),isMainSender:e===this.session.dcId,onConnectionBreak:this._cleanupExportedSender.bind(this)})}getSender(e){return e?this._borrowExportedSender(e):Promise.resolve(this._sender)}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof p.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof p.MessageMediaWebPage&&n.webpage instanceof p.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof p.MessageMediaPhoto||n instanceof p.Photo?this._downloadPhoto(n,t):n instanceof p.MessageMediaDocument||n instanceof p.Document?this._downloadDocument(n,t):n instanceof p.MessageMediaContact?this._downloadContact(n,t):n instanceof p.WebDocument||n instanceof p.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,a,i;if([765557111,3316604308,524706233,3566872215].includes(e.SUBCLASS_OF_ID)){if(!e.photo){if(!e.chatPhoto)return;return this._downloadPhoto(e.chatPhoto,{sizeType:n})}s=e.photo}else s=e;if(s instanceof p.UserProfilePhoto||s instanceof p.ChatPhoto)return a=s.dcId,i=new p.InputPeerPhotoFileLocation({peer:l.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(i,{dcId:a})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new p.InputStickerSetThumb({stickerset:new p.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=I.indexOf(t);se.type===I[s])),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof p.PhotoStrippedSize?l.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof p.MessageMediaPhoto&&(e=e.photo),!(e instanceof p.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof p.PhotoSizeEmpty?void 0:n instanceof p.PhotoCachedSize||n instanceof p.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new p.InputPhotoFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n.type}),{dcId:e.dcId,fileSize:n.size,progressCallback:t.progressCallback})}_downloadDocument(e,t){if(e instanceof p.MessageMediaDocument&&(e=e.document),!(e instanceof p.Document))return;let n;if(t.sizeType){if(n=e.thumbs?this._pickFileSize(e.thumbs,t.sizeType):void 0,!n&&e.mimeType.startsWith("video/"))return;if(n&&(n instanceof p.PhotoCachedSize||n instanceof p.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new p.InputDocumentFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n?n.type:""}),{fileSize:n?n.size:e.size,progressCallback:t.progressCallback,start:t.start,end:t.end,dcId:e.dcId,workers:t.workers})}_downloadContact(e,t){throw new Error("not implemented")}async _downloadWebDocument(e){try{const t=[];let n=0;for(;;){const s=new f.upload.GetWebFile({location:new p.InputWebFileLocation({url:e.url,accessHash:e.accessHash}),offset:n,limit:v}),a=await this._borrowExportedSender(4),i=await a.send(s);if(n+=131072,!i.bytes.length)break;if(t.push(i.bytes),i.bytes.length{"use strict";n.r(t),n.d(t,{authFlow:()=>l,checkAuthorization:()=>u});var s=n(7150),a=n.n(s),i=n(8960),o=n.n(i),r=n(9618),c=n(9674);const d="phoneNumber";async function l(e,t,n){let s;if("botAuthToken"in n)s=await async function(e,t,n){const{apiId:s,apiHash:i}=t,{botAuthToken:o}=n,{user:r}=await e.invoke(new(a().auth.ImportBotAuthorization)({apiId:s,apiHash:i,botAuthToken:o}));return r}(e,t,n);else{const{initialMethod:a=d}=n;s="phoneNumber"===a?await g(e,t,n):await p(e,t,n)}e._log.info("Signed in successfully as",o().getDisplayName(s))}async function u(e){try{return await e.invoke(new(a().updates.GetState)),!0}catch(e){if("Disconnect"===e.message)throw e;return!1}}async function g(e,t,n){let s,i,o,r=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return p(e,t,n);throw s}else s=n.phoneNumber;const a=await f(e,t,s,n.forceSMS);if(i=a.phoneCodeHash,r=a.isCodeViaApp,"string"!=typeof i)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,d=!1;for(;;)try{try{o=await n.phoneCode(r)}catch(s){if("RESTART_AUTH"===s.message)return g(e,t,n)}if(!o)throw new Error("Code is empty");const l=await e.invoke(new(a().auth.SignIn)({phoneNumber:s,phoneCodeHash:i,phoneCode:o}));if(l instanceof a().auth.AuthorizationSignUpRequired){d=!0,c=l.termsOfService;break}return l.user}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);n.onError(t)}if(d)for(;;)try{const[t,o]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:r}=await e.invoke(new(a().auth.SignUp)({phoneNumber:s,phoneCodeHash:i,firstName:t,lastName:o}));return c&&await e.invoke(new(a().help.AcceptTermsOfService)({id:c.id})),r}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),g(e,t,n)}async function p(e,t,n){let s=!1;const i=(async()=>{for(;!s;){const t=await e.invoke(new(a().auth.ExportLoginToken)({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(!(t instanceof a().auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:i}=t;await Promise.race([n.qrCode({token:s,expires:i}),(0,r.sleep)(3e4)])}})(),o=new Promise((t=>{e.addEventHandler((e=>{e instanceof a().UpdateLoginToken&&t()}),{build:e=>e})}));try{await Promise.race([o,i])}catch(s){if("RESTART_AUTH"===s.message)return await g(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new(a().auth.ExportLoginToken)({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(t instanceof a().auth.LoginTokenSuccess&&t.authorization instanceof a().auth.Authorization)return t.authorization.user;if(t instanceof a().auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new(a().auth.ImportLoginToken)({token:t.token}));if(n instanceof a().auth.LoginTokenSuccess&&n.authorization instanceof a().auth.Authorization)return n.authorization.user}}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);throw t}throw void 0}async function f(e,t,n,s=!1){try{const{apiId:i,apiHash:o}=t,r=await e.invoke(new(a().auth.SendCode)({phoneNumber:n,apiId:i,apiHash:o,settings:new(a().CodeSettings)}));if(!s||r.type instanceof a().auth.SentCodeTypeSms)return{phoneCodeHash:r.phoneCodeHash,isCodeViaApp:r.type instanceof a().auth.SentCodeTypeApp};const c=await e.invoke(new(a().auth.ResendCode)({phoneNumber:n,phoneCodeHash:r.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof a().auth.SentCodeTypeApp}}catch(a){if("AUTH_RESTART"===a.message)return f(e,t,n,s);throw a}}async function h(e,t,n){for(;;)try{const t=await e.invoke(new(a().account.GetPassword)),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const i=await(0,c.computeCheck)(t,s),{user:o}=await e.invoke(new(a().auth.CheckPassword)({password:i}));return o}catch(e){n.onError(e)}}},2288:(e,t,n)=>{"use strict";n.r(t),n.d(t,{downloadFile:()=>p});var s=n(7150),a=n.n(s),i=n(8960),o=n(9618),r=n(7873),c=n.n(r),d=n(8764).Buffer;function l(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const u=1048576;class g{constructor(e){this.maxWorkers=e,l(this,"deferred",void 0),l(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=(0,o.createDeferred)(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function p(e,t,n){let{partSizeKb:s,end:r}=n;const{fileSize:l,workers:p=1}=n,{dcId:f,progressCallback:h,start:m=0}=n;r=r&&r{for(;;){let d;try{d=await e.getSender(f);const o=await d.send(new(a().upload.GetFile)({location:t,offset:i,limit:n,precise:s||void 0}));if(h){if(h.isCanceled)throw new Error("USER_CANCELED");I+=1/y,h(I)}return!r&&o.bytes.lengthr)break}const A=(await Promise.all(w)).filter(Boolean),S=r?r+1-m:void 0;return d.concat(A,S)}},4766:(e,t,n)=>{"use strict";n.r(t),n.d(t,{uploadFile:()=>l});var s=n(7150),a=n.n(s),i=n(9618),o=n(8960),r=n(7873),c=n.n(r),d=n(8764).Buffer;async function l(e,t){const{file:n,onProgress:s}=t;let{workers:r}=t;const{name:l,size:u}=n,g=(0,i.readBigIntFromBuffer)((0,i.generateRandomBytes)(8),!0,!0),p=u>10485760,f=1024*(0,o.getAppropriatedPartSize)(u),h=Math.floor((u+f-1)/f),m=d.from(await function(e){return new Response(e).arrayBuffer()}(n));await e.getSender(e.session.dcId),r&&u||(r=1),r>=h&&(r=h);let _=0;s&&s(_);for(let t=0;th&&(o=h);for(let r=t;r{for(;;){let o;try{o=await e.getSender(e.session.dcId),await o.send(p?new(a().upload.SaveBigFilePart)({fileId:g,filePart:t,fileTotalParts:h,bytes:n}):new(a().upload.SaveFilePart)({fileId:g,filePart:t,bytes:n}))}catch(e){if(o&&!o.isConnected()){await(0,i.sleep)(1e3);continue}if(e instanceof c().FloodWaitError){await(0,i.sleep)(1e3*e.seconds);continue}throw e}if(s){if(s.isCanceled)throw new Error("USER_CANCELED");_+=1/h,s(_)}break}})(r,t))}await Promise.all(n)}return p?new(a().InputFileBig)({id:g,parts:h,name:l}):new(a().InputFile)({id:g,parts:h,name:l,md5Checksum:""})}},3302:(e,t,n)=>{var s=n(8764).Buffer;const{sha1:a,toSignedLittleBuffer:i,readBufferFromBigInt:o,readBigIntFromBuffer:r}=n(9618),c=n(5544),{sleep:d}=n(9618);class l{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new c(t);this.auxHash=n.readLong(!1),n.read(4),this.keyId=n.readLong(!1)}async setKey(e){if(!e)return this._key=void 0,this.auxHash=void 0,this.keyId=void 0,void(this._hash=void 0);if(e instanceof l)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await a(this._key);const t=new c(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await d(20)}getKey(){return this._key}async calcNewNonceHash(e,t){e=i(e,32);const n=s.alloc(1);n.writeUInt8(t,0);const c=s.concat([e,s.concat([n,o(this.auxHash,8,!0)])]),d=(await a(c)).slice(4,20);return r(d,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=l},5830:(e,t,n)=>{var s=n(8764).Buffer;const a=n(6842);e.exports=class{constructor(e,t){if(!s.isBuffer(e)||!s.isBuffer(t)||16!==t.length)throw new Error("Key and iv need to be a buffer");this.cipher=a.createCipheriv("AES-256-CTR",e,t)}encrypt(e){return s.from(this.cipher.update(e))}}},9636:(e,t,n)=>{const s=n(4736),{modExp:a}=n(9618);class i{static gcd(e,t){for(;t.neq(s.zero);){const n=t;t=e.remainder(t),e=n}return e}static factorize(e){if(e.remainder(2).equals(s.zero))return{p:s(2),q:e.divide(s(2))};let t=s.randBetween(s(1),e.minus(1));const n=s.randBetween(s(1),e.minus(1)),o=s.randBetween(s(1),e.minus(1));let r,c=s.one,d=s.one,l=s.one,u=s.zero,g=s.zero;for(;c.eq(s.one);){u=t;for(let i=0;s(i).lesser(d);i++)t=a(t,s(2),e).add(n).remainder(e);for(r=s.zero;r.lesser(d)&&c.eq(s.one);){g=t;const p=s.min(o,d.minus(r));for(let i=0;s(i).lesser(p);i++)t=a(t,s(2),e).add(n).remainder(e),l=l.multiply(u.minus(t).abs()).remainder(e);c=i.gcd(l,e),r=r.add(o)}d=d.multiply(2)}if(c.eq(e))for(;g=a(g,s(2),e).add(n).remainder(e),c=i.gcd(u.minus(g).abs(),e),!c.greater(1););const p=c;return l=e.divide(c),p{var s=n(8764).Buffer;const{IGE:a}=n(8136),i=n(9618);e.exports=class{constructor(e,t){this.ige=new a(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const t=e.length%16;return t&&(e=s.concat([e,i.generateRandomBytes(16-t)])),i.convertToLittle(this.ige.encrypt(e))}}},4121:(e,t,n)=>{"use strict";function s(e){const t=new Uint8Array(4*e.length);let n=0;for(let s=0;s>>24,t[n++]=a>>16&255,t[n++]=a>>8&255,t[n++]=255&a}return t.buffer}function a(e){return e.buffer}function i(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;es,i2abBig:()=>a,ab2iLow:()=>i,ab2iBig:()=>o,isBigEndian:()=>r,i2ab:()=>c,ab2i:()=>d});const r=1===new Uint8Array(new Uint32Array([16909060]))[0],c=r?a:s,d=r?o:i},6842:(e,t,n)=>{var s=n(8764).Buffer;const a=n(8136).default,{i2ab:i,ab2i:o}=n(4121),{getWords:r}=n(7760);class c{constructor(e){this.setBytes(e)}setBytes(e){e=s.from(e),this._counter=e}increment(){for(let e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}}}class d{constructor(e,t){t instanceof c||(t=new c(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new a(r(e))}update(e){return this.encrypt(e)}encrypt(e){const t=s.from(e);for(let e=0;e{"use strict";function s(e,t){return e.charCodeAt(t)<<24^e.charCodeAt(t+1)<<16^e.charCodeAt(t+2)<<8^e.charCodeAt(t+3)}function a(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(let t=e.length%4;t<=4;t++)e+="\0x00";const t=new Uint32Array(e.length/4);for(let n=0;ns,getWords:()=>a,xor:()=>i})},8187:e=>{class t extends Error{constructor(){super("The read operation was cancelled.")}}class n extends Error{constructor(e,t){super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${e}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${t.length}`),"undefined"!=typeof alert&&alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${e}`),this.invalidConstructorId=e,this.remaining=t}}class s extends Error{constructor(e,t){super(`Invalid checksum (${e} when ${t} was expected). This packet should be skipped.`),this.checksum=e,this.validChecksum=t}}class a extends Error{constructor(e){let t;4===e.length?(t=-e.readInt32LE(0),super(`Invalid response buffer (HTTP code ${t})`)):super(`Invalid response buffer (too short ${e})`),this.code=t,this.payload=e}}class i extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=` Caused by ${e.className}`,super(n),this.message=n,this.code=t}}var r,c,d;d={16:"msg_id too low (most likely, client time is wrong it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted).",17:"msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",32:"msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno).",33:"msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",48:"Incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it).",64:"Invalid container."},(c="ErrorMessages")in(r=o)?Object.defineProperty(r,c,{value:d,enumerable:!0,configurable:!0,writable:!0}):r[c]=d,e.exports={ReadCancelledError:t,TypeNotFoundError:n,InvalidChecksumError:s,InvalidBufferError:a,SecurityError:i,CdnFileTamperedError:class extends i{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},6952:e=>{function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class n extends Error{constructor(e,t,s){super("RPCError {0}: {1}{2}".replace("{0}",s).replace("{1}",e).replace("{2}",n._fmtRequest(t))),this.code=s,this.message=e}static _fmtRequest(e){return e?` (caused by ${e.className})`:""}}e.exports={RPCError:n,InvalidDCError:class extends n{constructor(e,t,n){super(t,e,n),this.code=n||303,this.message=t||"ERROR_SEE_OTHER"}},BadRequestError:class extends n{constructor(...e){super(...e),t(this,"code",400),t(this,"message","BAD_REQUEST")}},UnauthorizedError:class extends n{constructor(...e){super(...e),t(this,"code",401),t(this,"message","UNAUTHORIZED")}},ForbiddenError:class extends n{constructor(...e){super(...e),t(this,"code",403),t(this,"message","FORBIDDEN")}},NotFoundError:class extends n{constructor(...e){super(...e),t(this,"code",404),t(this,"message","NOT_FOUND")}},AuthKeyError:class extends n{constructor(...e){super(...e),t(this,"code",406),t(this,"message","AUTH_KEY")}},FloodError:class extends n{constructor(...e){super(...e),t(this,"code",420),t(this,"message","FLOOD")}},ServerError:class extends n{constructor(...e){super(...e),t(this,"code",500),t(this,"message","INTERNAL")}},TimedOutError:class extends n{constructor(...e){super(...e),t(this,"code",503),t(this,"message","Timeout")}}}},5651:(e,t,n)=>{const{RPCError:s,InvalidDCError:a,FloodError:i,BadRequestError:o}=n(6952);class r extends a{constructor(e){const t=Number(e.capture||0);super(`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class c extends a{constructor(e){const t=Number(e.capture||0);super(`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class d extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`,this.seconds=t}}class l extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`,this.seconds=t}}class u extends i{constructor(e){super(`Message failed to be sent.${s._fmtRequest(e.request)}`),this.message=`Message failed to be sent.${s._fmtRequest(e.request)}`}}class g extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`,this.seconds=t}}class p extends a{constructor(e){const t=Number(e.capture||0);super(`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`),this.message=`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class f extends a{constructor(e){const t=Number(e.capture||0);super(`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class h extends o{constructor(e){const t=Number(e.capture||0);super(`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`),this.message=`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`,this.codeLength=t}}const m=[[/FILE_MIGRATE_(\d+)/,p],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,g],[/FLOOD_WAIT_(\d+)/,l],[/MSG_WAIT_(.*)/,u],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,d],[/USER_MIGRATE_(\d+)/,r],[/NETWORK_MIGRATE_(\d+)/,f],[/EMAIL_UNCONFIRMED_(\d+)/,h]];e.exports={rpcErrorRe:m,FileMigrateError:p,FloodTestPhoneWaitError:g,FloodWaitError:l,PhoneMigrateError:c,SlowModeWaitError:d,UserMigrateError:r,NetworkMigrateError:f,MsgWaitError:u,EmailUnconfirmedError:h}},7873:(e,t,n)=>{const{RPCError:s}=n(6952),{rpcErrorRe:a}=n(5651),i=n(8187),o=n(6952),r=n(5651);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of a){const a=e.errorMessage.match(n);if(a)return new s({request:t,capture:2===a.length?parseInt(a[1],10):void 0})}return new s(e.errorMessage,t)},...i,...o,...r}},6316:()=>{},3903:(e,t,n)=>{const{EventBuilder:s}=n(663);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},663:e=>{e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},3182:(e,t,n)=>{const s=n(6316),a=n(3903);class i extends Error{}e.exports={NewMessage:s,StopPropagation:i,Raw:a}},6151:e=>{e.exports=class{constructor(){this._queue=[],this.canGet=new Promise((e=>{this.resolveGet=e})),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise((e=>{this.resolvePush=e}))}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise((e=>{this.resolveGet=e})),e}}},5544:(e,t,n)=>{const{TypeNotFoundError:s}=n(8187),{coreObjects:a}=n(2058),{tlobjects:i}=n(845),{readBigIntFromBuffer:o}=n(9618);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return o(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error(`Invalid boolean code ${e.toString("16")}`)}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=i[e];if(void 0===t){if(2574415285===e)return!0;if(3162085175===e)return!1;if(481674261===e){const e=[],t=this.readInt();for(let n=0;n{var s=n(8764).Buffer;e.exports=class{constructor(e){this._stream=e}write(e){this._stream=s.concat([this._stream,e])}getValue(){return this._stream}}},6748:e=>{let t;class n{constructor(e){t||(t=e||"debug"),this.isBrowser="undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs,this.isBrowser?this.colors={start:"%c",warn:"color : #ff00ff",info:"color : #ffff00",debug:"color : #00ffff",error:"color : #ff0000",end:""}:this.colors={start:"[2m",warn:"[35m",info:"[33m",debug:"[36m",error:"[31m",end:"[0m"},this.messageFormat="[%t] [%l] - [%m]"}static setLevel(e){t=e}canSend(e){return n.levels.indexOf(t)>=n.levels.indexOf(e)}warn(e){"debug"===t&&console.error((new Error).stack),this._log("warn",e,this.colors.warn)}info(e){this._log("info",e,this.colors.info)}debug(e){this._log("debug",e,this.colors.debug)}error(e){"debug"===t&&console.error((new Error).stack),this._log("error",e,this.colors.error)}format(e,t){return this.messageFormat.replace("%t",(new Date).toISOString()).replace("%l",t.toUpperCase()).replace("%m",e)}_log(e,n,s){t&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(n,e),s):console.log(s+this.format(n,e)+this.colors.end))}}var s,a,i;i=["error","warn","info","debug"],(a="levels")in(s=n)?Object.defineProperty(s,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[a]=i,e.exports=n},6411:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3254),i=n(355),o=n(6472),r=["messages.SendMessage","messages.SendMedia","messages.SendMultiMedia","messages.ForwardMessages","messages.SendInlineBotResult"];e.exports=class{constructor(e,t){this._state=e,this._queue=[],this._pendingStates=[],this._ready=new Promise((e=>{this.setReady=e})),this._log=t}values(){return this._queue}append(e){if(e&&r.includes(e.request.className))for(let t=this._queue.length-1;t>=0;t--)if(r.includes(this._queue[t].request.className)){e.after=this._queue[t];break}this._queue.push(e),this.setReady(!0),e&&1658238041!==e.request.CONSTRUCTOR_ID&&(this._pendingStates.push(e),e.promise.catch((()=>{})).finally((()=>{this._pendingStates=this._pendingStates.filter((t=>t!==e))})))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise((e=>{this.setReady=e})),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,t=new o(s.alloc(0));const n=[];let r=0;for(;this._queue.length&&n.length<=a.MAXIMUM_LENGTH;){const e=this._queue.shift();if(r+=e.data.length+i.SIZE_OVERHEAD,r<=a.MAXIMUM_SIZE){let s;e.after&&(s=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(t,e.data,"request"===e.request.classType,s),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),n.push(e)}else{if(n.length){this._queue.unshift(e);break}this._log.warn(`Message payload for ${e.request.className||e.request.constructor.name} is too long ${e.data.length} and cannot be sent`),e.reject("Request Payload is too big"),r=0}}if(n.length){if(n.length>1){const i=s.alloc(8);i.writeUInt32LE(a.CONSTRUCTOR_ID,0),i.writeInt32LE(n.length,4),e=s.concat([i,t.getValue()]),t=new o(s.alloc(0));const r=await this._state.writeDataAsMessage(t,e,!1);for(const e of n)e.containerId=r}return e=t.getValue(),{batch:n,data:e}}}rejectAll(){this._pendingStates.forEach((e=>{e.reject(new Error("Disconnect"))}))}}},7214:(e,t,n)=>{var s=n(8764).Buffer;const{Mutex:a}=n(8125),i=new a,o=n(5840).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(e){this.client=void 0,this.closed=!0,this.disconnectedCallback=e}async readExactly(e){let t=s.alloc(0);for(;;){const n=await this.read(e);if(t=s.concat([t,n]),!(e-=n.length))return t}}async read(e){if(this.closed)throw r;if(await this.canRead,this.closed)throw r;const t=this.stream.slice(0,e);return this.stream=this.stream.slice(e),0===this.stream.length&&(this.canRead=new Promise((e=>{this.resolveRead=e}))),t}async readAll(){if(this.closed||!await this.canRead)throw r;const e=this.stream;return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),e}getWebSocketLink(e,t,n){return 443===t?`wss://${e}:${t}/apiws${n?"_test":""}`:`ws://${e}:${t}/apiws${n?"_test":""}`}connect(e,t,n=!1){return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),this.closed=!1,this.website=this.getWebSocketLink(t,e,n),this.client=new o(this.website,"binary"),new Promise(((e,n)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{console.error("WebSocket error",e),n(e)},this.client.onclose=e=>{const{code:n,reason:s,wasClean:a}=e;1e3!==n&&console.error(`Socket ${t} closed. Code: ${n}, reason: ${s}, was clean: ${a}`),this.resolveRead(!1),this.closed=!0,this.disconnectedCallback&&this.disconnectedCallback()},self.addEventListener("offline",(async()=>{await this.close(),this.resolveRead(!1)}))}))}write(e){if(this.closed)throw r;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}receive(){this.client.onmessage=async e=>{await i.runExclusive((async()=>{const t=e.data instanceof ArrayBuffer?s.from(e.data):s.from(await new Response(e.data).arrayBuffer());this.stream=s.concat([this.stream,t]),this.resolveRead(!0)}))}}}},9832:(e,t,n)=>{const s=n(6748),a=n(6472),i=n(5544),o=n(7214),r=n(6411),c=n(6151);e.exports={BinaryWriter:a,BinaryReader:i,MessagePacker:r,AsyncQueue:c,Logger:s,PromisedWebSockets:o}},3522:(e,t,n)=>{const s=n(7150),a=n(8742),i=n(8415),o=n(7404),r=n(1472),c=n(3182),d=n(8960),l=n(7873),u=n(5886),g=n(9832),p=n(9618);e.exports={Api:s,TelegramClient:a,sessions:u,connection:i,extensions:g,tl:o,version:r,events:c,utils:d,errors:l,helpers:p}},9870:(e,t,n)=>{"use strict";n.r(t),n.d(t,{doAuthentication:()=>_});var s=n(7150),a=n.n(s),i=n(7873),o=n(4736),r=n.n(o);n(9618),n(8764).Buffer;const c=[{fingerprint:r()("-3414540481677951611"),n:r()("29379598170669337022986177149456128565388431120058863768162556424047512191330847455146576344487764408661701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531316010870401287642763009136156734339538042419388722777357134487746169093539093850251243897188928735903389451772730245253062963384108812842079887538976360465290946139638691491496062099570836476454855996319192747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323"),e:65537},{fingerprint:r()("-5595554452916591101"),n:r()("25342889448840415564971689590713473206898847759084779052582026594546022463853940585885215951168491965708222649399180603818074200620463776135424884632162512403163793083921641631564740959529419359595852941166848940585952337613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951323237820036543581047826906120927972487366805292115792231423684261262330394324750785450942589751755390156647751460719351439969059949569615302809050721500330239005077889855323917509948255722081644689442127297605422579707142646660768825302832201908302295573257427896031830742328565032949"),e:65537}],d=new Map;c.forEach((({fingerprint:e,...t})=>{d.set(e.toString(),t)}));var l=n(8764).Buffer;const u=n(4736),g=n(2608),p=n(3302),f=n(9636),h=n(9618),m=n(5544);async function _(e,t){let n=h.generateRandomBytes(16);const s=h.readBigIntFromBuffer(n,!1,!0),o=await e.send(new(a().ReqPqMulti)({nonce:s}));if(t.debug("Starting authKey generation step 1"),!(o instanceof a().ResPQ))throw new i.SecurityError(`Step 1 answer was ${o}`);if(o.nonce.neq(s))throw new i.SecurityError("Step 1 invalid nonce from server");const r=h.readBigIntFromBuffer(o.pq,!1,!0);t.debug("Finished authKey generation step 1");const{p:c,q:_}=f.factorize(r),y=h.getByteArray(c),b=h.getByteArray(_);n=h.generateRandomBytes(32);const w=h.readBigIntFromBuffer(n,!0,!0),C=new(a().PQInnerData)({pq:h.getByteArray(r),p:y,q:b,nonce:o.nonce,serverNonce:o.serverNonce,newNonce:w}).getBytes();if(C.length>144)throw new i.SecurityError("Step 1 invalid nonce from server");let v,I;for(const e of o.serverPublicKeyFingerprints)if(I=d.get(e.toString()),void 0!==I){v=e;break}if(void 0===v||void 0===I)throw new i.SecurityError("Step 2 could not find a valid key for fingerprints");const A=h.generateRandomBytes(192-C.length),S=l.concat([C,A]),P=l.from(S).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(l.concat([e,S])),s=l.concat([P,n]),a=new g(e,l.alloc(32)).encryptIge(s),i=h.bufferXor(e,await h.sha256(a)),o=l.concat([i,a]),r=h.readBigIntFromBuffer(o,!1,!1);if(r.greaterOrEquals(I.n)){t.debug("Aes key greater than RSA. retrying");continue}const c=h.modExp(r,u(I.e),I.n);M=h.readBufferFromBigInt(c,256,!1,!1);break}if(void 0===M)throw new i.SecurityError("Step 2 could create a secure encrypted key");t.debug("Step 2 : Generated a secure aes encrypted data");const k=await e.send(new(a().ReqDHParams)({nonce:o.nonce,serverNonce:o.serverNonce,p:y,q:b,publicKeyFingerprint:v,encryptedData:M}));if(!(k instanceof a().ServerDHParamsOk||k instanceof a().ServerDHParamsFail))throw new Error(`Step 2.1 answer was ${k}`);if(k.nonce.neq(o.nonce))throw new i.SecurityError("Step 2 invalid nonce from server");if(k.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 2 invalid server nonce from server");if(k instanceof a().ServerDHParamsFail){const e=await h.sha1(h.toSignedLittleBuffer(w,32).slice(4,20)),t=h.readBigIntFromBuffer(e,!0,!0);if(k.newNonceHash.neq(t))throw new i.SecurityError("Step 2 invalid DH fail nonce from server")}if(!(k instanceof a().ServerDHParamsOk))throw new Error(`Step 2.2 answer was ${k}`);t.debug("Finished authKey generation step 2"),t.debug("Starting authKey generation step 3");const{key:R,iv:U}=await h.generateKeyDataFromNonce(o.serverNonce,w);if(k.encryptedAnswer.length%16!=0)throw new i.SecurityError("Step 3 AES block size mismatch");const E=new g(R,U),D=E.decryptIge(k.encryptedAnswer),T=new m(D);T.read(20);const B=T.tgReadObject();if(!(B instanceof a().ServerDHInnerData))throw new Error(`Step 3 answer was ${B}`);if(B.nonce.neq(o.nonce))throw new i.SecurityError("Step 3 Invalid nonce in encrypted answer");if(B.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 3 Invalid server nonce in encrypted answer");const x=h.readBigIntFromBuffer(B.dhPrime,!1,!1),V=h.readBigIntFromBuffer(B.gA,!1,!1),N=B.serverTime-Math.floor((new Date).getTime()/1e3),F=h.readBigIntFromBuffer(h.generateRandomBytes(256),!1,!1),L=h.modExp(u(B.g),F,x),O=h.modExp(V,F,x),q=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(L,!1)}).getBytes(),H=l.concat([await h.sha1(q),q]),G=E.encryptIge(H),K=await e.send(new(a().SetClientDHParams)({nonce:o.nonce,serverNonce:o.serverNonce,encryptedData:G})),z=[a().DhGenOk,a().DhGenRetry,a().DhGenFail];if(!(K instanceof z[0]||K instanceof z[1]||K instanceof z[2]))throw new Error(`Step 3.1 answer was ${K}`);const{name:j}=K.constructor;if(K.nonce.neq(o.nonce))throw new i.SecurityError(`Step 3 invalid ${j} nonce from server`);if(K.serverNonce.neq(o.serverNonce))throw new i.SecurityError(`Step 3 invalid ${j} server nonce from server`);const W=new p;await W.setKey(h.getByteArray(O));const $=1+["DhGenOk","DhGenRetry","DhGenFail"].indexOf(K.className),J=await W.calcNewNonceHash(w,$);if(K[`newNonceHash${$}`].neq(J))throw new i.SecurityError("Step 3 invalid new nonce hash");if(!(K instanceof a().DhGenOk))throw new Error(`Step 3.2 answer was ${K}`);return t.debug("Finished authKey generation step 3"),{authKey:W,timeOffset:N}}},5585:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9109),o=n(5544),{InvalidBufferError:r}=n(8187),{toSignedLittleBuffer:c}=n(9618);e.exports=class{constructor(e,t){this._state=new i(e,t),this._connection=e}async send(e){let t=e.getBytes(),n=this._state._getNewMsgId();const i=c(n,8),d=s.alloc(4);d.writeInt32LE(t.length,0);const l=s.concat([s.concat([s.alloc(8),i,d]),t]);if(await this._connection.send(l),t=await this._connection.recv(),t.length<8)throw new r(t);const u=new o(t);if(u.readLong().neq(a(0)))throw new Error("Bad authKeyId");if(n=u.readLong(),n.eq(a(0)))throw new Error("Bad msgId");if(u.readInt()<=0)throw new Error("Bad length");return u.tgReadObject()}}},4046:(e,t,n)=>{const{RPCError:s}=n(7873),a=n(5585),i=n(9109),o=n(9618),r=n(3302),{doAuthentication:c}=n(9870),d=n(2301),l=n(3254),u=n(8963),g=n(4287),{MsgsAck:p,upload:f,MsgsStateInfo:h,Pong:m}=n(7404).constructors,_=n(6411),y=n(5544),{UpdateConnectionState:b,UpdateServerTimeOffset:w}=n(8415),{BadMessageError:C}=n(8187),{BadServerSalt:v,BadMsgNotification:I,MsgDetailedInfo:A,MsgNewDetailedInfo:S,NewSessionCreated:P,FutureSalts:M,MsgsStateReq:k,MsgResendReq:R,MsgsAllInfo:U}=n(7404).constructors,{SecurityError:E}=n(8187),{InvalidBufferError:D}=n(8187),{LogOut:T}=n(7404).requests.auth,{RPCMessageToError:B}=n(7873),{TypeNotFoundError:x}=n(8187);class V{constructor(e,t){const n={...V.DEFAULT_OPTIONS,...t};this._connection=void 0,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this.userDisconnected=!1,this._user_connected=!1,this.isReconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new r,this._state=new i(this.authKey,this._log),this._send_queue=new _(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[d.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[l.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[u.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[m.CONSTRUCTOR_ID]:this._handlePong.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[I.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[A.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[p.CONSTRUCTOR_ID]:this._handleAck.bind(this),[M.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[k.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[R.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[U.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this.isConnecting=!0,this._connection=e;for(let e=0;e=10&&this._last_acks.shift(),this._pending_ack.clear()}this._log.debug(`Waiting for messages to send...${this.isReconnecting}`);const e=await this._send_queue.get();if(this.isReconnecting)return;if(!e)continue;let{data:t}=e;const{batch:n}=e;this._log.debug(`Encrypting ${n.length} message(s) in ${t.length} bytes for sending`),t=await this._state.encryptMessageData(t);try{await this._connection.send(t)}catch(e){return this._log.error(e),void this._log.info("Connection closed while sending data")}for(const e of n)if(Array.isArray(e))for(const t of e)"request"===t.request.classType&&(this._pending_state[t.msgId]=t);else"request"===e.request.classType&&(this._pending_state[e.msgId]=e);this._log.debug("Encrypted messages put in a queue to be sent")}}async _recvLoop(){let e,t;for(;this._user_connected&&!this.isReconnecting;){this._log.debug("Receiving items from the network...");try{e=await this._connection.recv()}catch(e){return void(this.userDisconnected||(this._log.error(e),this._log.warn("Connection closed while receiving data"),this.reconnect()))}try{t=await this._state.decryptMessageData(e)}catch(e){if(e instanceof x){this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);continue}if(e instanceof E){this._log.warn(`Security error while unpacking a received message: ${e}`);continue}return e instanceof D?void(404===e.code?this._handleBadAuthKey():(this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`),this.reconnect())):(this._log.error("Unhandled error while receiving data"),this._log.error(e),void this.reconnect())}try{await this._processMessage(t)}catch(e){e instanceof s?"AUTH_KEY_UNREGISTERED"===e.message&&this._handleBadAuthKey(!0):(this._log.error("Unhandled error while receiving data"),this._log.error(e))}}}_handleBadAuthKey(e){e&&this._isMainSender||(this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`),this._isMainSender&&this._updateCallback?this._updateCallback(new b(b.broken)):!this._isMainSender&&this._onConnectionBreak&&this._onConnectionBreak(this._dcId))}async _processMessage(e){this._pending_ack.add(e.msgId),e.obj=await e.obj;let t=this._handlers[e.obj.CONSTRUCTOR_ID];t||(t=this._handleUpdate.bind(this)),await t(e)}_popStates(e){let t=this._pending_state[e];if(t)return this._pending_state[e].deferred.resolve(),delete this._pending_state[e],[t];const n=[];for(t of Object.values(this._pending_state))t.containerId&&t.containerId.equals(e)&&n.push(t.msgId);if(n.length){const e=[];for(const t of n)e.push(this._pending_state[t]),this._pending_state[t].deferred.resolve(),delete this._pending_state[t];return e}for(const t of this._last_acks)if(t.msgId===e)return[t];return[]}_handleRPCResult(e){const t=e.obj,n=this._pending_state[t.reqMsgId];if(n&&(n.deferred.resolve(),delete this._pending_state[t.reqMsgId]),this._log.debug(`Handling RPC result for message ${t.reqMsgId}`),!n)try{if(!(new y(t.body).tgReadObject()instanceof f.File))throw new x("Not an upload.File")}catch(e){if(this._log.error(e),e instanceof x)return void this._log.info(`Received response without parent request: ${t.body}`);throw e}if(t.error){const e=B(t.error,n.request);throw this._send_queue.append(new g(new p({msgIds:[n.msgId]}))),n.reject(e),e}try{const e=new y(t.body),s=n.request.readResult(e);n.resolve(s)}catch(e){throw n.reject(e),e}}async _handleContainer(e){this._log.debug("Handling container");for(const t of e.obj.messages)await this._processMessage(t)}async _handleGzipPacked(e){this._log.debug("Handling gzipped data");const t=new y(e.obj.data);e.obj=t.tgReadObject(),await this._processMessage(e)}_handleUpdate(e){2331323052===e.obj.SUBCLASS_OF_ID?(this._log.debug(`Handling update ${e.obj.className}`),this._updateCallback&&this._updateCallback(e.obj)):this._log.warn(`Note: ${e.obj.className} is not an update, not dispatching it`)}_handlePong(e){const t=e.obj,n=this._state.updateTimeOffset(e.msgId);this._updateCallback&&this._updateCallback(new w(n)),this._log.debug(`Handling pong for message ${t.msgId}`);const s=this._pending_state[t.msgId];this._pending_state[t.msgId].deferred.resolve(),delete this._pending_state[t.msgId],s&&s.resolve(t)}_handleBadServerSalt(e){const t=e.obj;this._log.debug(`Handling bad salt for message ${t.badMsgId}`),this._state.salt=t.newServerSalt;const n=this._popStates(t.badMsgId);this._send_queue.extend(n),this._log.debug(`${n.length} message(s) will be resent`)}_handleBadNotification(e){const t=e.obj,n=this._popStates(t.badMsgId);if(this._log.debug(`Handling bad msg ${JSON.stringify(t)}`),[16,17].includes(t.errorCode)){const t=this._state.updateTimeOffset(e.msgId);this._updateCallback&&this._updateCallback(new w(t)),this._log.info(`System clock is wrong, set time offset to ${t}s`)}else if(32===t.errorCode)this._state._sequence+=64;else{if(33!==t.errorCode){for(const e of n)e.reject(new C(e.request,t.errorCode));return}this._state._sequence-=16}this._send_queue.extend(n),this._log.debug(`${n.length} messages will be resent due to bad msg`)}_handleDetailedInfo(e){const t=e.obj.answerMsgId;this._log.debug(`Handling detailed info for message ${t}`),this._pending_ack.add(t)}_handleNewDetailedInfo(e){const t=e.obj.answerMsgId;this._log.debug(`Handling new detailed info for message ${t}`),this._pending_ack.add(t)}_handleNewSessionCreated(e){this._log.debug("Handling new session created"),this._state.salt=e.obj.serverSalt}_handleAck(e){const t=e.obj;this._log.debug(`Handling acknowledge for ${t.msgIds}`);for(const e of t.msgIds){const t=this._pending_state[e];t&&t.request instanceof T&&(this._pending_state[e].deferred.resolve(),delete this._pending_state[e],t.resolve(!0))}}_handleFutureSalts(e){this._log.debug(`Handling future salts for message ${e.msgId}`);const t=this._pending_state[e.msgId];t&&(this._pending_state[e].deferred.resolve(),delete this._pending_state[e],t.resolve(e.obj))}_handleStateForgotten(e){this._send_queue.append(new g(new h(e.msgId,String.fromCharCode(1).repeat(e.obj.msgIds))))}_handleMsgAll(e){}reconnect(){this._user_connected&&!this.isReconnecting&&(this.isReconnecting=!0,o.sleep(1e3).then((()=>{this._log.info("Started reconnecting"),this._reconnect()})))}async _reconnect(){this._log.debug("Closing current connection...");try{await this._disconnect()}catch(e){this._log.warn(e)}this._send_queue.append(void 0),this._state.reset();const e=new this._connection.constructor(this._connection._ip,this._connection._port,this._connection._dcId,this._connection._log,this._connection._testServers);await this.connect(e,!0),this.isReconnecting=!1;for(const e of Object.values(this._pending_state))e.deferred.resolve();this._pending_state={},this._autoReconnectCallback&&await this._autoReconnectCallback()}}var N,F,L;L={logger:void 0,retries:1/0,delay:2e3,autoReconnect:!0,connectTimeout:void 0,authKeyCallback:void 0,updateCallback:void 0,autoReconnectCallback:void 0,isMainSender:void 0,onConnectionBreak:void 0},(F="DEFAULT_OPTIONS")in(N=V)?Object.defineProperty(N,F,{value:L,enumerable:!0,configurable:!0,writable:!0}):N[F]=L,e.exports=V},9109:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9618),o=n(2608),r=n(5544),c=n(8963),{TLMessage:d}=n(2058),{SecurityError:l,InvalidBufferError:u}=n(8187),{InvokeAfterMsg:g}=n(7404).requests,{toSignedLittleBuffer:p}=n(9618);e.exports=class{constructor(e,t){this.authKey=e,this._log=t,this.timeOffset=0,this.salt=0,this.id=void 0,this._sequence=void 0,this._lastMsgId=void 0,this.msgIds=[],this.reset()}reset(){this.id=i.generateRandomLong(!0),this._sequence=0,this._lastMsgId=a(0),this.msgIds=[]}updateMessageId(e){e.msgId=this._getNewMsgId()}async _calcKey(e,t,n){const a=!0===n?0:8,[o,r]=await Promise.all([i.sha256(s.concat([t,e.slice(a,a+36)])),i.sha256(s.concat([e.slice(a+40,a+76),t]))]);return{key:s.concat([o.slice(0,8),r.slice(8,24),o.slice(24,32)]),iv:s.concat([r.slice(0,8),o.slice(8,24),r.slice(24,32)])}}async writeDataAsMessage(e,t,n,a){const i=this._getNewMsgId(),o=this._getSeqNo(n);let r;r=a?await c.gzipIfSmaller(n,new g(a,{getBytes:()=>t}).getBytes()):await c.gzipIfSmaller(n,t);const d=s.alloc(4);d.writeInt32LE(o,0);const l=s.alloc(4);l.writeInt32LE(r.length,0);const u=p(i,8);return e.write(s.concat([u,d,l])),e.write(r),i}async encryptMessageData(e){await this.authKey.waitForKey();const t=p(this.salt,8),n=p(this.id,8);e=s.concat([s.concat([t,n]),e]);const a=i.generateRandomBytes(i.mod(-(e.length+12),16)+12),r=(await i.sha256(s.concat([this.authKey.getKey().slice(88,120),e,a]))).slice(8,24),{iv:c,key:d}=await this._calcKey(this.authKey.getKey(),r,!0),l=i.readBufferFromBigInt(this.authKey.keyId,8);return s.concat([l,r,new o(d,c).encryptIge(s.concat([e,a]))])}async decryptMessageData(e){if(e.length<8)throw new u(e);if(e.length<0)throw new l("Server replied with negative length");if(e.length%4!=0)throw new l("Server replied with length not divisible by 4");if(i.readBigIntFromBuffer(e.slice(0,8)).neq(this.authKey.keyId))throw new l("Server replied with an invalid auth key");const t=e.slice(8,24),{iv:n,key:a}=await this._calcKey(this.authKey.getKey(),t,!1);e=new o(a,n).decryptIge(e.slice(24));const c=await i.sha256(s.concat([this.authKey.getKey().slice(96,128),e]));if(!t.equals(c.slice(8,24)))throw new l("Received msg_key doesn't match with expected one");const g=new r(e);if(g.readLong(),!g.readLong().eq(this.id))throw new l("Server replied with a wrong session ID");const p=g.readLong();if(this.msgIds.includes(p.toString()))throw new l("Duplicate msgIds");this.msgIds.length>500&&this.msgIds.shift(),this.msgIds.push(p.toString());const f=g.readInt(),h=g.readInt(),m=e.length-h;if(m<12||m>1024)throw new l("Server replied with the wrong message padding");const _=g.tgReadObject();return new d(p,f,_)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=a(Math.floor(e)).shiftLeft(a(32)).or(a(t).shiftLeft(a(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(a(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,s=Math.floor((new Date).getTime()/1e3),i=e.shiftRight(a(32));return this.timeOffset=i-s,this.timeOffset!==n&&(this._lastMsgId=a(0),this._log.debug(`Updated time offset (old offset ${n}, bad ${t}, good ${e}, new ${this.timeOffset})`)),this.timeOffset}_getSeqNo(e){if(e){const e=2*this._sequence+1;return this._sequence+=1,e}return 2*this._sequence}}},4287:(e,t,n)=>{const{createDeferred:s}=n(9618);e.exports=class{constructor(e,t,n={}){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.pending=n,this.deferred=s(),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}isReady(){const e=this.pending[this.after.id];return!e||e.deferred.promise}}},4353:(e,t,n)=>{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(7214),i=n(6151);class o{constructor(e,t,n,o,r){s(this,"PacketCodecClass",void 0),this._ip=e,this._port=t,this._dcId=n,this._log=o,this._testServers=r,this._connected=!1,this._sendTask=void 0,this._recvTask=void 0,this._codec=void 0,this._obfuscation=void 0,this._sendArray=new i,this._recvArray=new i,this.socket=new a(this.disconnectCallback.bind(this))}async disconnectCallback(){await this.disconnect(!0)}async _connect(){this._log.debug("Connecting"),this._codec=new this.PacketCodecClass(this),await this.socket.connect(this._port,this._ip,this._testServers),this._log.debug("Finished connecting"),await this._initConn()}async connect(){await this._connect(),this._connected=!0,this._sendTask||(this._sendTask=this._sendLoop()),this._recvTask=this._recvLoop()}async disconnect(e=!1){this._connected&&(this._connected=!1,this._recvArray.push(void 0),e||await this.socket.close())}async send(e){if(!this._connected)throw new Error("Not connected");await this._sendArray.push(e)}async recv(){for(;this._connected;){const e=await this._recvArray.pop();if(e)return e}throw new Error("Not connected")}async _sendLoop(){try{for(;this._connected;){const e=await this._sendArray.pop();if(!e)return void(this._sendTask=void 0);await this._send(e)}}catch(e){this._log.info("The server closed the connection while sending")}}async _recvLoop(){let e;for(;this._connected;){try{if(e=await this._recv(),!e)throw new Error("no data received")}catch(e){return this._log.info("connection closed"),void this.disconnect()}await this._recvArray.push(e)}}async _initConn(){this._codec.tag&&await this.socket.write(this._codec.tag)}_send(e){const t=this._codec.encodePacket(e);this.socket.write(t)}_recv(){return this._codec.readPacket(this.socket)}toString(){return`${this._ip}:${this._port}/${this.constructor.name.replace("Connection","")}`}}e.exports={Connection:o,PacketCodec:class{constructor(e){this._conn=e}encodePacket(e){throw new Error("Not Implemented")}readPacket(e){throw new Error("Not Implemented")}},ObfuscatedConnection:class extends o{constructor(...e){super(...e),s(this,"ObfuscatedIO",void 0)}_initConn(){this._obfuscation=new this.ObfuscatedIO(this),this.socket.write(this._obfuscation.header)}_send(e){this._obfuscation.write(this._codec.encodePacket(e))}_recv(){return this._codec.readPacket(this._obfuscation)}}}},6302:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(4736),{readBufferFromBigInt:o}=n(9618),{Connection:r,PacketCodec:c}=n(4353);class d extends c{constructor(e){super(e),this.tag=d.tag,this.obfuscateTag=d.obfuscateTag}encodePacket(e){let t=e.length>>2;if(t<127){const e=s.alloc(1);e.writeUInt8(t,0),t=e}else t=s.concat([s.from("7f","hex"),o(i(t),3)]);return s.concat([t,e])}async readPacket(e){let t=(await e.read(1))[0];return t>=127&&(t=s.concat([await e.read(3),s.alloc(1)]).readInt32LE(0)),e.read(t<<2)}}a(d,"tag",s.from("ef","hex")),a(d,"obfuscateTag",s.from("efefefef","hex")),e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),a(this,"PacketCodecClass",d)}},AbridgedPacketCodec:d}},5484:()=>{},2986:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{generateRandomBytes:i}=n(9618),{ObfuscatedConnection:o}=n(4353),{AbridgedPacketCodec:r}=n(6302),c=n(5830);class d{constructor(e){a(this,"header",void 0),this.connection=e.socket;const t=this.initHeader(e.PacketCodecClass);this.header=t.random,this._encrypt=t.encryptor,this._decrypt=t.decryptor}initHeader(e){const t=[s.from("50567247","hex"),s.from("474554","hex"),s.from("504f5354","hex"),s.from("eeeeeeee","hex")];let n;for(;;)if(n=i(64),239!==n[0]&&!n.slice(4,8).equals(s.alloc(4))){let e=!0;for(const s of t)if(s.equals(n.slice(0,4))){e=!1;break}if(e)break}n=n.toJSON().data;const a=s.from(n.slice(8,56)).reverse(),o=s.from(n.slice(8,40)),r=s.from(n.slice(40,56)),d=s.from(a.slice(0,32)),l=s.from(a.slice(32,48)),u=new c(o,r),g=new c(d,l);return n=s.concat([s.from(n.slice(0,56)),e.obfuscateTag,s.from(n.slice(60))]),n=s.concat([s.from(n.slice(0,56)),s.from(u.encrypt(n).slice(56,64)),s.from(n.slice(64))]),{random:n,encryptor:u,decryptor:g}}async read(e){const t=await this.connection.readExactly(e);return this._decrypt.encrypt(t)}write(e){this.connection.write(this._encrypt.encrypt(e))}}e.exports={ConnectionTCPObfuscated:class extends o{constructor(...e){super(...e),a(this,"ObfuscatedIO",d),a(this,"PacketCodecClass",r)}}}},417:(e,t,n)=>{const{Connection:s}=n(4353),{ConnectionTCPFull:a}=n(5484),{ConnectionTCPAbridged:i}=n(6302),{ConnectionTCPObfuscated:o}=n(2986);e.exports={Connection:s,ConnectionTCPFull:a,ConnectionTCPAbridged:i,ConnectionTCPObfuscated:o}},8415:(e,t,n)=>{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(5585),i=n(4046);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:r,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(417);e.exports={Connection:r,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:a,MTProtoSender:i,UpdateConnectionState:o,UpdateServerTimeOffset:class{constructor(e){this.timeOffset=e}}}},9270:e=>{e.exports=class{get dcId(){throw new Error("Not Implemented")}get serverAddress(){throw new Error("Not Implemented")}get port(){throw new Error("Not Implemented")}get authKey(){throw new Error("Not Implemented")}set authKey(e){throw new Error("Not Implemented")}setDC(e,t,n){throw new Error("Not implemented")}save(){throw new Error("Not Implemented")}delete(){throw new Error("Not Implemented")}}},926:(e,t,n)=>{const s=n(8753),a="GramJs";e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open(a)).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open(a),n=await t.match(e);return n?n.text():void 0}async _saveToCache(e){const t=new Request(this._storageKey),n=new Response(e);return(await self.caches.open(a)).put(t,n)}}},7:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(8960);e.exports=class extends a{constructor(e,t){super(),this._sessionData=e,this._callback=t,this._authKeys={}}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(!this._sessionData)return;const{mainDcId:e,keys:t,hashes:n}=this._sessionData,{ipAddress:a,port:r}=o.getDC(e);this.setDC(e,a,r,!0),await Promise.all(Object.keys(t).map((async e=>{const a="string"==typeof t[e]?s.from(t[e],"hex"):s.from(t[e]);if(n[e]){const t="string"==typeof n[e]?s.from(n[e],"hex"):s.from(n[e]);this._authKeys[e]=new i(a,t)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)})))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach((t=>{const n=this._authKeys[t];n&&n._key&&(e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex"))})),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}},5945:(e,t,n)=>{const s=n(1875),a=n(8753);e.exports=class extends a{_delete(){return s.del(`GramJs:${this._storageKey}`)}_fetchFromCache(){return s.get(`GramJs:${this._storageKey}`)}_saveToCache(e){return s.set(`GramJs:${this._storageKey}`,e)}}},1753:(e,t,n)=>{const s=n(8753);e.exports=class extends s{_delete(){return localStorage.removeItem(this._storageKey)}_fetchFromCache(){return localStorage.getItem(this._storageKey)}_saveToCache(e){return localStorage.setItem(this._storageKey,e)}}},3995:(e,t,n)=>{const s=n(9270);e.exports=class extends s{constructor(){super(),this._serverAddress=void 0,this._dcId=0,this._port=void 0,this._takeoutId=void 0,this._entities=new Set,this._updateStates={}}get dcId(){return this._dcId}get serverAddress(){return this._serverAddress}get port(){return this._port}get authKey(){return this._authKey}set authKey(e){this._authKey=e}setDC(e,t,n){this._dcId=0|e,this._serverAddress=t,this._port=n}}},8753:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(8960);e.exports=class extends a{constructor(e){super(),this._authKeys={},e&&e.startsWith("session:")?this._sessionString=e:e&&(this._storageKey=e)}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(this._sessionString)await this._loadFromSessionString();else if(this._storageKey)try{const e=await this._fetchFromCache(),{mainDcId:t,keys:n,hashes:a}=JSON.parse(e),{ipAddress:r,port:c}=o.getDC(t);this.setDC(t,r,c,!0),Object.keys(n).forEach((e=>{n[e]&&a[e]&&(this._authKeys[e]=new i(s.from(n[e].data),s.from(a[e].data)))}))}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey=`GramJs-session-${Date.now()}`),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach((n=>{const s=this._authKeys[n];s._key&&(t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash)})),t}async _loadFromSessionString(){const[,e,t]=this._sessionString.split(":"),n=Number(e),{ipAddress:a,port:r}=o.getDC(n);this.setDC(n,a,r);const c=new i;await c.setKey(s.from(t,"hex"),!0),this.setAuthKey(c,n)}async _updateStorage(){if(this._storageKey)try{await this._saveToCache(JSON.stringify(this.getSessionData()))}catch(e){console.warn("Failed to update session in storage"),console.warn(e)}}async delete(){try{return await this._delete()}catch(e){console.warn("Failed to delete session from storage"),console.warn(e)}}_delete(){throw new Error("Not Implemented")}_fetchFromCache(){throw new Error("Not Implemented")}_saveToCache(e){throw new Error("Not Implemented")}}},2433:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(5544);class r extends a{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new o(t);this._dcId=n.read(1).readUInt8(0);const s=n.read(2).readInt16BE(0);this._serverAddress=String(n.read(s)),this._port=n.read(2).readInt16BE(0),this._key=n.read(-1)}}static encode(e){return e.toString("base64")}static decode(e){return s.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=s.from([this.dcId]),t=s.from(this.serverAddress),n=s.alloc(2);n.writeInt16BE(t.length,0);const a=s.alloc(2);return a.writeInt16BE(this.port,0),"1"+r.encode(s.concat([e,n,t,a,this.authKey.getKey()]))}getAuthKey(e){if(!e||e===this.dcId)return this.authKey}setAuthKey(e,t){t&&t!==this.dcId||(this.authKey=e)}}e.exports=r},5886:(e,t,n)=>{const s=n(3995),a=n(2433),i=n(926),o=n(1753),r=n(5945),c=n(7);e.exports={Memory:s,StringSession:a,CacheApiSession:i,LocalStorageSession:o,IdbSession:r,CallbackSession:c}},845:(e,t,n)=>{const s=n(7150),a={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)a[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))a[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:137,tlobjects:a}},7150:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{parseTl:i,serializeBytes:o,serializeDate:r}=n(1436),{toSignedLittleBuffer:c}=n(9618),d=n(4779),l=n(8106),u="undefined"!=typeof self&&void 0!==self.localStorage,g="GramJs:apiCache";function p(e){const t=i(e,109),n=[],s=[];for(const e of t)e.isFunction?s.push(e):n.push(e);return[n,s]}function f(e,t){switch(t){case"int":{const t=s.alloc(4);return t.writeInt32LE(e,0),t}case"long":return c(e,8);case"int128":return c(e,16);case"int256":return c(e,32);case"double":{const t=s.alloc(8);return t.writeDoubleLE(e,0),t}case"string":return o(e);case"Bool":return e?s.from("b5757299","hex"):s.from("379779bc","hex");case"true":return s.alloc(0);case"bytes":return o(e);case"date":return r(e);default:return e.getBytes()}}function h(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let a=0;a{this[e]=t[e]}))}static fromReader(e){const t={};for(const n in c)if(c.hasOwnProperty(n)){const s=c[n];if(s.isFlag){if("true"===s.type){t[n]=Boolean(t.flags&1<f(t,c[e].type)))))}else if(c[e].flagIndicator)if(Object.values(c).some((e=>e.isFlag))){let e=0;for(const t in c)c[t].isFlag&&(!1===this[t]&&"true"===c[t].type||void 0===this[t]?e|=0:e|=1</);if(n){t.readInt();const e=[],s=t.readInt();if("int"===n[1])for(let n=0;n{"function"!=typeof t[e]&&n[e]?Object.assign(n[e],t[e]):n[e]=t[e]})),n}(m("constructor",e.constructors),m("request",e.requests))}()},4779:e=>{e.exports="boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#6592a1a7 id:long title:string = Chat;\nchannel#8261ac61 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#d18ee226 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?Vector = ChatFull;\nchannelFull#e13c3d20 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?Vector = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#38116ee0 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#33fb7bb8 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#a518110d flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#cf366521 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true id:long about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector