(()=>{var e,t,n={370:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>ut,clear:()=>ft,fetch:()=>gt,save:()=>pt});var a={};n.r(a),n.d(a,{addChatMembers:()=>hn,answerCallbackButton:()=>ha,blockContact:()=>js,checkChatUsername:()=>As,checkPassword:()=>Ds,checkUsername:()=>Ls,clearDraft:()=>Nt,clearPassword:()=>Ts,createChannel:()=>Lt,createGroupChat:()=>Wt,deleteChannel:()=>zt,deleteChat:()=>Gt,deleteChatFolder:()=>Yt,deleteChatMember:()=>mn,deleteChatUser:()=>Ht,deleteHistory:()=>Bn,deleteMessages:()=>Dn,deleteScheduledMessages:()=>Tn,deleteUser:()=>rs,destroy:()=>It,disconnect:()=>Ct,downloadMedia:()=>St,editChatFolder:()=>Zt,editChatPhoto:()=>jt,editMessage:()=>Mn,faveSticker:()=>gs,fetchAnimatedEmojis:()=>fs,fetchAuthorizations:()=>Js,fetchBlockedContacts:()=>Ws,fetchChat:()=>xt,fetchChatFolders:()=>Qt,fetchChats:()=>Dt,fetchContactList:()=>ss,fetchContentSettings:()=>la,fetchCurrentUser:()=>Rt,fetchEmojiKeywords:()=>Is,fetchFavoriteStickers:()=>ls,fetchFeaturedStickers:()=>us,fetchFullChat:()=>Tt,fetchFullUser:()=>es,fetchGroupsForDiscussion:()=>un,fetchInlineBot:()=>_a,fetchInlineBotResults:()=>ya,fetchLangPack:()=>sa,fetchLangStrings:()=>aa,fetchLanguages:()=>na,fetchMembers:()=>ln,fetchMessage:()=>Pn,fetchMessages:()=>Cn,fetchNearestCountry:()=>ts,fetchNotificationExceptions:()=>Zs,fetchNotificationSettings:()=>Ys,fetchPinnedMessages:()=>Jn,fetchPrivacySettings:()=>ia,fetchProfilePhotos:()=>os,fetchRecentStickers:()=>ds,fetchRecommendedChatFolders:()=>Xt,fetchSavedGifs:()=>ms,fetchScheduledHistory:()=>Wn,fetchStickerSets:()=>cs,fetchStickers:()=>ps,fetchStickersForEmoji:()=>ws,fetchTopInlineBots:()=>ma,fetchTopUsers:()=>ns,fetchUsers:()=>as,fetchWallpapers:()=>Ks,fetchWebPagePreview:()=>qn,findFirstMessageIdAfterDate:()=>zn,forwardMessages:()=>Kn,getChatByUsername:()=>tn,getPasswordInfo:()=>Us,getPaymentForm:()=>Aa,getReceipt:()=>va,importChatInvite:()=>bn,installStickerSet:()=>_s,joinChannel:()=>qt,leaveChannel:()=>Kt,loadPollOptionResults:()=>Gn,markMessageListRead:()=>Vn,markMessagesRead:()=>Fn,migrateChat:()=>pn,openChatByInvite:()=>fn,pinMessage:()=>Un,provideAuthCode:()=>nt,provideAuthPassword:()=>st,provideAuthPhoneNumber:()=>tt,provideAuthRegistration:()=>at,provideRecoveryEmailCode:()=>Vs,registerDevice:()=>ra,reportMessages:()=>xn,requestChatUpdate:()=>Vt,requestThreadInfoUpdate:()=>Nn,rescheduleMessage:()=>kn,restartAuth:()=>it,restartAuthWithQr:()=>rt,saveDraft:()=>Ft,searchChats:()=>Bt,searchGifs:()=>bs,searchMessagesGlobal:()=>Ln,searchMessagesLocal:()=>On,searchStickers:()=>hs,sendInlineBotResult:()=>ba,sendMessage:()=>vn,sendPaymentForm:()=>Pa,sendPollVote:()=>Hn,sendScheduledMessages:()=>jn,setChatUsername:()=>vs,setDiscussionGroup:()=>gn,setPrivacySettings:()=>ca,terminateAllAuthorizations:()=>Xs,terminateAuthorization:()=>Qs,toggleChatArchived:()=>Jt,toggleChatPinned:()=>$t,toggleDialogUnread:()=>en,togglePreHistoryHidden:()=>nn,toggleSignatures:()=>dn,unblockContact:()=>$s,uninstallStickerSet:()=>ys,unpinAllMessages:()=>En,unregisterDevice:()=>oa,updateChatAbout:()=>cn,updateChatAdmin:()=>rn,updateChatDefaultBannedRights:()=>sn,updateChatMemberBannedRights:()=>an,updateChatMutedState:()=>Ot,updateChatTitle:()=>on,updateContact:()=>is,updateContactSignUpNotification:()=>ea,updateContentSettings:()=>ua,updateIsOnline:()=>da,updateNotificationSettings:()=>ta,updatePassword:()=>Bs,updatePrivateLink:()=>Ss,updateProfile:()=>Os,updateProfilePhoto:()=>Hs,updateRecoveryEmail:()=>xs,updateUsername:()=>qs,uploadProfilePhoto:()=>Gs,uploadWallpaper:()=>zs,validateRequestedInfo:()=>Ca});const i=("undefined"!=typeof window&&window.innerHeight,Math.round(425)),r=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]);new Set(["image/png","image/gif","image/jpeg","video/mp4","video/avi","video/quicktime"]);var o=n(3522);function c(e,t){return e.reduce(((e,n)=>(e[n[t]]=n,e)),{})}function d(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}function l(e){return e.hasOwnProperty("userId")}function u(e){return e.hasOwnProperty("chatId")}function g(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function p(e){if(!e)return;const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:a,classType:i,...r}=e;return r}function f(e,t=!1){const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&S(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 o.Api.Channel||e instanceof o.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 o.Api.Chat||e instanceof o.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...m(e),..."creator"in e&&{isCreator:e.creator},..._(e),...y(e)}}function h(e,t,n){const{peer:s,folderId:a,unreadMark:i,unreadCount:r,unreadMentionsCount:c,notifySettings:{silent:d,muteUntil:l},readOutboxMaxId:u,readInboxMaxId:g,draft:p}=e,h=d||"number"==typeof l&&Date.now()+1e3*n<1e3*l;return{id:w(s),...a&&{folderId:a},type:C(t),title:A(s,t),lastReadOutboxMessageId:u,lastReadInboxMessageId:g,unreadCount:r,unreadMentionsCount:c,isMuted:h,...i&&{hasUnreadMark:!0},...p instanceof o.Api.DraftMessage&&{draftDate:p.date},...f(t)}}function m(e){return e instanceof o.Api.Chat||e instanceof o.Api.Channel?{adminRights:p(e.adminRights),currentUserBannedRights:e instanceof o.Api.Channel?p(e.bannedRights):void 0,defaultBannedRights:p(e.defaultBannedRights)}:{}}function _(e){if(e instanceof o.Api.ChatForbidden||e instanceof o.Api.ChannelForbidden)return{isRestricted:!0};const t={};if("restricted"in e){const n=e.restricted?function(e){if(!e)return;const t=e.find((({platform:e})=>"all"===e));return t?d(t,["reason","text"]):void 0}(e.restrictionReason):void 0;n&&Object.assign(t,{isRestricted:!0,restrictionReason:n})}return e instanceof o.Api.Chat&&Object.assign(t,{isNotJoined:e.left,isRestricted:e.kicked}),e instanceof o.Api.Channel&&Object.assign(t,{isNotJoined:e.left}),t}function y(e){return e instanceof o.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof o.Api.InputChannelEmpty)?{migratedTo:{chatId:w(e.migratedTo),...e.migratedTo instanceof o.Api.InputChannel&&{accessHash:e.migratedTo.accessHash.toString()}}}:{}}function b(e,t=!1,n=!1){if(e instanceof o.Api.Chat||e instanceof o.Api.Channel||e instanceof o.Api.User||n&&(e instanceof o.Api.ChatForbidden||e instanceof o.Api.ChannelForbidden))return{id:e instanceof o.Api.User?e.id:-e.id,type:C(e),title:e instanceof o.Api.User?v(e):e.title,...f(e,t)}}function w(e){return l(e)?e.userId:u(e)?-e.chatId:-e.channelId}function I(e){return function(e){return e.hasOwnProperty("userId")}(e)?e.userId:function(e){return e.hasOwnProperty("chatId")}(e)?-e.chatId:function(e){return e.hasOwnProperty("channelId")}(e)?-e.channelId:void 0}function C(e){return e instanceof o.Api.User||e instanceof o.Api.UserEmpty?"chatTypePrivate":e instanceof o.Api.Chat||e instanceof o.Api.ChatForbidden||e instanceof o.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function P(e){return l(e)?`user${e.userId}`:u(e)?`chat${e.chatId}`:`chat${e.channelId}`}function A(e,t){return l(e)?v(t):t.title}function v(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function S(e){if("photoId"in e)return e.photoId.toString()}function M(e){return{userId:e instanceof o.Api.ChannelParticipantBanned||e instanceof o.Api.ChannelParticipantLeft?w(e.peer):e.userId,inviterId:"inviterId"in e?e.inviterId:void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?e.kickedBy:void 0,promotedByUserId:"promotedBy"in e?e.promotedBy:void 0,bannedRights:"bannedRights"in e?p(e.bannedRights):void 0,adminRights:"adminRights"in e?p(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof o.Api.ChannelParticipantAdmin||e instanceof o.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof o.Api.ChannelParticipantCreator||e instanceof o.Api.ChatParticipantCreator)&&{isOwner:!0}}}function k(e){return e instanceof o.Api.ChatParticipants||e instanceof o.Api.channels.ChannelParticipants?e.participants.map(M).filter(Boolean):void 0}function R(e,t){let n="";if(!(e.action instanceof o.Api.SendMessageCancelAction))return e.action instanceof o.Api.SendMessageTypingAction?n="lng_user_typing":e.action instanceof o.Api.SendMessageRecordVideoAction?n="lng_send_action_record_video":e.action instanceof o.Api.SendMessageUploadVideoAction?n="lng_send_action_upload_video":e.action instanceof o.Api.SendMessageRecordAudioAction?n="lng_send_action_record_audio":e.action instanceof o.Api.SendMessageUploadAudioAction?n="lng_send_action_upload_audio":e.action instanceof o.Api.SendMessageUploadPhotoAction?n="lng_send_action_upload_photo":e.action instanceof o.Api.SendMessageUploadDocumentAction?n="lng_send_action_upload_file":e.action instanceof o.Api.SendMessageGeoLocationAction?n="selecting a location to share":e.action instanceof o.Api.SendMessageChooseContactAction?n="selecting a contact to share":e.action instanceof o.Api.SendMessageGamePlayAction?n="lng_playing_game":e.action instanceof o.Api.SendMessageRecordRoundAction?n="lng_send_action_record_round":e.action instanceof o.Api.SendMessageUploadRoundAction&&(n="lng_send_action_upload_round"),{action:n,...!(e instanceof o.Api.UpdateUserTyping)&&{userId:w(e.fromId)},timestamp:Date.now()+1e3*t}}function U(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(I).filter(Boolean),includedChatIds:e.includePeers.map(I).filter(Boolean),excludedChatIds:e.excludePeers.map(I).filter(Boolean)};var t,n}function E({filter:e,description:t}){return{...U(e),description:t}}var D=n(8960);function T(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 x(e,t){if(!e||!e.length)return;const n=e.find((e=>e instanceof o.Api.PhotoStrippedSize));if(!n)return;const s=e.filter((e=>e instanceof o.Api.PhotoSize)),{w:a,h:i}=s&&s.length?s[s.length-1]:B,{bytes:r}=n;return{dataUri:g(t&&"image/jpeg"!==t?r:(0,D.strippedPhotoToJpg)(r),void 0,t),width:a,height:i}}function V(e){const t=e.sizes.filter((e=>e instanceof o.Api.PhotoSize||e instanceof o.Api.PhotoSizeProgressive)).map(F);return{id:String(e.id),thumbnail:x(e.sizes),sizes:t}}function F(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}const N={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{},webDocuments:{}},O="application/x-tgsticker";function L(e){if(e instanceof o.Api.DocumentEmpty)return;const t=e.attributes.find((e=>e instanceof o.Api.DocumentAttributeSticker)),n=e.mimeType===O&&e.attributes.find((e=>e instanceof o.Api.DocumentAttributeFilename));if(!t&&!n)return;const s=e.attributes.find((e=>e instanceof o.Api.DocumentAttributeImageSize)),a=t&&t.stickerset instanceof o.Api.InputStickerSetID?t.stickerset:void 0,i=t?t.alt:void 0,r=e.mimeType===O,c=e.thumbs&&e.thumbs.find((e=>e instanceof o.Api.PhotoCachedSize)),d=e.thumbs&&e.thumbs.find((e=>e instanceof o.Api.PhotoPathSize)),l=c?function(e){const{w:t,h:n,bytes:s}=e;return{dataUri:g(s,void 0,"image/webp"),width:t,height:n}}(c):d&&s?function(e,t){const{w:n,h:s}=t;return{dataUri:`data:image/svg+xml;utf8,${T(e.bytes,n,s)}`,width:n,height:s}}(d,s):void 0,{w:u,h:p}=c||s||{};return{id:String(e.id),stickerSetId:a?String(a.id):"MEMOJI_STICKER",stickerSetAccessHash:a&&String(a.accessHash),emoji:i,isAnimated:r,width:u,height:p,thumbnail:l}}function q(e){const{archived:t,animated:n,installedDate:s,id:a,accessHash:i,title:r,thumbs:o,count:c,hash:d,shortName:l}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(a),accessHash:String(i),title:r,hasThumbnail:Boolean(o&&o.length),count:c,hash:d,shortName:l}}function H(e){const t=q(e.set),n=e instanceof o.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach((e=>{if(e instanceof o.Api.Document){const n=L(e);n&&(t.covers.push(n),N.documents[String(e.id)]=e)}})),t}function G(e,t){let n=0;const s=new Array(t),a=e.length/t,i=e[0],r=e[e.length-1];for(let l=0;l0?"user":e<=-1e9?"channel":"chat"}function X(e){return e>0?new o.Api.PeerUser({userId:e}):e<=-1e9?new o.Api.PeerChannel({channelId:-e}):new o.Api.PeerChat({chatId:-e})}function Z(e,t){return e>0||e<=-1e9?e>0?new o.Api.InputPeerUser({userId:e,accessHash:z()(t)}):new o.Api.InputPeerChannel({channelId:-e,accessHash:z()(t)}):new o.Api.InputPeerChat({chatId:-e})}function Y(e){if(e>0){const{accessHash:t}=N.users[e]||{};return t?new o.Api.InputPeerUser({userId:e,accessHash:t}):void 0}if(e<=-1e9){const{accessHash:t}=N.chats[-e]||{};return t?new o.Api.InputPeerChannel({channelId:-e,accessHash:t}):void 0}return new o.Api.InputPeerChat({chatId:-e})}function ee(e,t){return e>0?new o.Api.InputUser({userId:e,accessHash:z()(t)}):e<=-1e9?new o.Api.InputChannel({channelId:-e,accessHash:z()(t)}):-e}function te(e,t){return new o.Api.InputStickerSetID({id:z()(e),accessHash:z()(t)})}function ne(e){const t=N.documents[e.id];if(t)return new o.Api.InputDocument(d(t,["id","accessHash","fileReference"]))}function se(e){const t=ne(e);if(t)return new o.Api.InputMediaDocument({id:t})}function ae(){return(0,W.readBigIntFromBuffer)((0,W.generateRandomBytes)(8),!0,!0)}function ie(e,t,n){return new o.Api.Message({id:e,peerId:X(t),fromId:X(t),media:n.media})}function re(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,r=i?N.users[i]:void 0;switch(t){case j.Bold:return new o.Api.MessageEntityBold({offset:n,length:s});case j.Italic:return new o.Api.MessageEntityItalic({offset:n,length:s});case j.Underline:return new o.Api.MessageEntityUnderline({offset:n,length:s});case j.Strike:return new o.Api.MessageEntityStrike({offset:n,length:s});case j.Code:return new o.Api.MessageEntityCode({offset:n,length:s});case j.Pre:return new o.Api.MessageEntityPre({offset:n,length:s,language:""});case j.Blockquote:return new o.Api.MessageEntityBlockquote({offset:n,length:s});case j.TextUrl:return new o.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case j.Url:return new o.Api.MessageEntityUrl({offset:n,length:s});case j.Hashtag:return new o.Api.MessageEntityHashtag({offset:n,length:s});case j.MentionName:return new o.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new o.Api.InputUser({userId:i,accessHash:r.accessHash})});default:return new o.Api.MessageEntityUnknown({offset:n,length:s})}}function oe(e){let t=0;return e.forEach((e=>{t=(20261*t&2147483647)+e&2147483647})),t}function ce(e){const{media:t}=e;return!!t&&(t instanceof o.Api.MessageMediaPhoto||t instanceof o.Api.MessageMediaDocument||t instanceof o.Api.MessageMediaWebPage&&t.webpage instanceof o.Api.WebPage&&(t.webpage.photo instanceof o.Api.Photo||t.webpage.document instanceof o.Api.Document&&t.webpage.document.mimeType.startsWith("video")))}function de({phone:e,firstName:t,lastName:n}){return new o.Api.InputPhoneContact({clientId:z()(1),phone:e,firstName:t,lastName:n})}function le(e,t=0){return new o.Api.ChatBannedRights({...e,untilDate:t})}function ue(e){return new o.Api.ChatAdminRights(e)}function ge(e){const{shippingAddress:t}=e;return new o.Api.PaymentRequestedInfo({...e,shippingAddress:t?new o.Api.PostAddress(t):void 0})}function pe(e){switch(e){case"phoneNumber":return new o.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new o.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new o.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new o.Api.InputPrivacyKeyForwards;case"chatInvite":return new o.Api.InputPrivacyKeyChatInvite}}function fe(e){switch(e){case"spam":return new o.Api.InputReportReasonSpam;case"violence":return new o.Api.InputReportReasonViolence;case"childAbuse":return new o.Api.InputReportReasonChildAbuse;case"pornography":return new o.Api.InputReportReasonPornography;case"copyright":return new o.Api.InputReportReasonCopyright;case"fake":return new o.Api.InputReportReasonFake;case"geoIrrelevant":return new o.Api.InputReportReasonGeoIrrelevant;case"other":return new o.Api.InputReportReasonOther}}function he(e){if(e instanceof o.Api.Message||e instanceof o.Api.MessageService)return w(e.peerId)}function me(e){const t=`${he(e)}-${e.id}`;N.messages[t]=e,e instanceof o.Api.Message&&e.media instanceof o.Api.MessageMediaDocument&&e.media.document instanceof o.Api.Document&&(N.documents[String(e.media.document.id)]=e.media.document),e instanceof o.Api.Message&&e.media instanceof o.Api.MessageMediaWebPage&&e.media.webpage instanceof o.Api.WebPage&&e.media.webpage.document instanceof o.Api.Document&&(N.documents[String(e.media.webpage.document.id)]=e.media.webpage.document),e instanceof o.Api.MessageService&&"photo"in e.action&&_e(e.action.photo)}function _e(e){e instanceof o.Api.Photo&&(N.photos[String(e.id)]=e)}let ye,be,we=1e9;function Ie(e){const t=he(e);if(t&&(e instanceof o.Api.Message||e instanceof o.Api.MessageService))return Ce(t,e)}function Ce(e,t){const n=t.fromId?w(t.fromId):void 0,s=t.peerId?w(t.peerId):void 0,a=!n&&e===ye,i=t.out&&!t.post||a&&!t.fwdFrom;let r={};t.media&&(r={...ve(t.media)}),!t.message||r.sticker||r.poll||r.contact||(r={...r,text:Pe(t.message,t.entities)});const c=t.action&&function(e,t,n,s,a){if(e instanceof o.Api.MessageActionEmpty)return;let i,r,c;const d=[];let l,u="other";const g="users"in e?e.users&&e.users:"userId"in e&&[e.userId]||[];let p;if(e instanceof o.Api.MessageActionChatCreate)c="Notification.CreatedChatWithTitle",d.push("%action_origin%",e.title),u="chatCreate";else if(e instanceof o.Api.MessageActionChatEditTitle)s?(c="Channel.MessageTitleUpdated",d.push(e.title)):(c="Notification.ChangedGroupName",d.push("%action_origin%",e.title));else if(e instanceof o.Api.MessageActionChatEditPhoto)s?c="Channel.MessagePhotoUpdated":(c="Notification.ChangedGroupPhoto",d.push("%action_origin%"));else if(e instanceof o.Api.MessageActionChatDeletePhoto)c=s?"Channel.MessagePhotoRemoved":"Group.MessagePhotoRemoved";else if(e instanceof o.Api.MessageActionChatAddUser)!t||g.includes(t)?(c="Notification.JoinedChat",d.push("%target_user%")):(c="Notification.Invited",d.push("%action_origin%","%target_user%"));else if(e instanceof o.Api.MessageActionChatDeleteUser)!t||g.includes(t)?(c="Notification.LeftChat",d.push("%target_user%")):(c="Notification.Kicked",d.push("%action_origin%","%target_user%"));else if(e instanceof o.Api.MessageActionChatJoinedByLink)c="Notification.JoinedGroupByLink",d.push("%action_origin%");else if(e instanceof o.Api.MessageActionChannelCreate)c="Notification.CreatedChannel";else if(e instanceof o.Api.MessageActionChatMigrateTo)p=w(e),c="Migrated to %target_chat%",d.push("%target_chat%");else if(e instanceof o.Api.MessageActionChannelMigrateFrom)p=w(e),c="Migrated from %target_chat%",d.push("%target_chat%");else if(e instanceof o.Api.MessageActionPinMessage)c="Chat.Service.Group.UpdatedPinnedMessage1",d.push("%action_origin%","%message%");else if(e instanceof o.Api.MessageActionHistoryClear)c="HistoryCleared",u="historyClear";else if(e instanceof o.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 o.Api.MessageActionContactSignUp)c="Notification.Joined",d.push("%action_origin%"),u="contactSignUp";else if(e instanceof o.Api.MessageActionPaymentSent)i=Number(e.totalAmount),r=e.currency,c="PaymentSuccessfullyPaid",n&&g.push(n),d.push("%payment_amount%","%target_user%","%product%");else if(e instanceof o.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";else e instanceof o.Api.MessageActionBotAllowed?(c="Chat.Service.BotPermissionAllowed",d.push(e.domain)):c="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof o.Api.Photo&&(_e(e.photo),l=V(e.photo)),{text:c,type:u,targetUserIds:g,targetChatId:p,photo:l,amount:i,currency:r,translationValues:d}}(t.action,n,s,Boolean(t.post),i);c&&(r.action=c);const{replyToMsgId:d,replyToTopId:l}=t.replyTo||{},u=t.editDate&&!t.editHide,{inlineButtons:g,keyboardButtons:p,keyboardPlaceholder:f,isKeyboardSingleUse:h}=function(e){const{id:t,replyMarkup:n,media:s}=e;if(!n)return s instanceof o.Api.MessageMediaWebPage&&s.webpage instanceof o.Api.WebPage&&"telegram_message"===s.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:s.webpage.url}]]}:void 0;if(!(n instanceof o.Api.ReplyKeyboardMarkup||n instanceof o.Api.ReplyInlineMarkup))return;const a=n.rows.map((({buttons:e})=>e.map((e=>{let n,a,{text:i}=e;return e instanceof o.Api.KeyboardButton?(n="command",a=i):e instanceof o.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof o.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof o.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof o.Api.KeyboardButtonBuy?(s instanceof o.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 o.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a,...n instanceof o.Api.ReplyKeyboardMarkup&&{keyboardPlaceholder:n.placeholder,isKeyboardSingleUse:n.singleUse}}}(t)||{},m=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&w(e.savedFromPeer),s=e.fromId&&w(e.fromId);return{isChannelPost:Boolean(e.channelPost),isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,a),{replies:_,mediaUnread:y,postAuthor:b}=t,I=t.groupedId&&t.groupedId.toString(),C=Boolean(I)&&!(r.document||r.audio),P=t.replyMarkup instanceof o.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:i,content:r,date:t.date,senderId:n||t.out&&t.post&&ye||e,views:t.views,isFromScheduled:t.fromScheduled,...d&&{replyToMessageId:d},...l&&{replyToTopMessageId:l},...m&&{forwardInfo:m},...u&&{isEdited:u},...y&&{isMediaUnread:y},...t.mentioned&&y&&{hasUnreadMention:!0},...I&&{groupedId:I,isInAlbum:C},inlineButtons:g,...p&&{keyboardButtons:p,keyboardPlaceholder:f,isKeyboardSingleUse:h},...P&&{shouldHideKeyboardButtons:P},...t.viaBotId&&{viaBotId:t.viaBotId},..._&&_.comments&&{threadInfo:Be(_,t.id,e)},...b&&{adminTitle:b}}}function Pe(e,t){return{text:e,...t&&{entities:t.map(Te)}}}function Ae(e){if(e instanceof o.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?Pe(t,n):void 0,replyingToId:s,date:a}}function ve(e){const t=function(e){if(e instanceof o.Api.MessageMediaDocument&&e.document&&e.document instanceof o.Api.Document)return L(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(e instanceof o.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof o.Api.Photo&&!e.ttlSeconds)return V(e.photo)}(e);if(n)return{photo:n};const s=function(e){if(e instanceof o.Api.MessageMediaDocument&&e.document instanceof o.Api.Document&&e.document.mimeType.startsWith("video"))return Se(e.document)}(e);if(s)return{video:s};const a=function(e){if(!(e instanceof o.Api.MessageMediaDocument&&e.document&&e.document instanceof o.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof o.Api.DocumentAttributeAudio));return t&&!t.voice?{fileName:Ee(e.document,"audio"),...d(e.document,["size","mimeType"]),...d(t,["duration","performer","title"])}:void 0}(e);if(a)return{audio:a};const i=function(e){if(!(e instanceof o.Api.MessageMediaDocument&&e.document&&e.document instanceof o.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof o.Api.DocumentAttributeAudio));if(!t||!t.voice)return;const{duration:n,waveform:s}=t;return{duration:n,waveform:s?Array.from(s):void 0}}(e);if(i)return{voice:i};const r=function(e){if(e instanceof o.Api.MessageMediaDocument&&e.document&&!e.ttlSeconds)return Me(e.document)}(e);if(r)return{document:r};const c=function(e){if(e instanceof o.Api.MessageMediaContact)return d(e,["firstName","lastName","phoneNumber","userId"])}(e);if(c)return{contact:c};const l=function(e){if(e instanceof o.Api.MessageMediaPoll)return ke(e.poll,e.results)}(e);if(l)return{poll:l};const u=Ue(e);if(u)return{webPage:u};const g=function(e){if(e instanceof o.Api.MessageMediaInvoice)return function(e){const{description:t,title:n,photo:s,test:a,totalAmount:i,currency:r,receiptMsgId:o}=e;return{text:t,title:n,photoUrl:s&&s.url,receiptMsgId:o,amount:Number(i),currency:r,isTest:a}}(e)}(e);return g?{invoice:g}:void 0}function Se(e){if(e instanceof o.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:s,size:a,attributes:i}=e,r=i.find((e=>e instanceof o.Api.DocumentAttributeVideo));if(!r)return;const c=i.find((e=>e instanceof o.Api.DocumentAttributeAnimated)),{duration:d,w:l,h:u,supportsStreaming:g=!1,roundMessage:p=!1}=r;return{id:String(t),mimeType:n,duration:d,fileName:Ee(e,"video"),width:l,height:u,supportsStreaming:g,isRound:p,isGif:Boolean(c),thumbnail:x(s),size:a}}function Me(e){if(!(e instanceof o.Api.Document))return;const{id:t,size:n,mimeType:s,date:a,thumbs:i,attributes:r}=e,c=i&&x(i);let d,l;const u=i&&i.find((e=>e instanceof o.Api.PhotoSize));if(u)if(l={width:u.w,height:u.h},s.startsWith("image/")){d="photo";const e=r.find((e=>e instanceof o.Api.DocumentAttributeImageSize));if(e){const{w:t,h:n}=e;l={width:t,height:n}}}else s.startsWith("video/")&&(d="video");return{id:String(t),size:n,mimeType:s,timestamp:a,fileName:Ee(e),thumbnail:c,mediaType:d,mediaSize:l}}function ke(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:String.fromCharCode(...e.option)})));return{id:n.toString(),summary:{isPublic:e.publicVoters,...d(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;return{totalVoters:n,recentVoterIds:s,results:t&&t.map((({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s}))),solution:a,...i&&{solutionEntities:i.map(Te)}}}function Ue(e){if(!(e instanceof o.Api.MessageMediaWebPage&&e.webpage instanceof o.Api.WebPage))return;const{id:t,photo:n,document:s}=e.webpage;let a;return s instanceof o.Api.Document&&s.mimeType.startsWith("video/")&&(a=Se(s)),{id:Number(t),...d(e.webpage,["url","displayUrl","type","siteName","title","description","duration"]),photo:n instanceof o.Api.Photo?V(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 o.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:t.toString(),summary:d(e.summary,["question","answers"]),results:{}}}}function Te(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function Be(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:r,recentRepliers:o}=e;if(777!==s)return{threadId:t,...n!==s?{chatId:w({channelId:s}),originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:i,lastReadInboxMessageId:r,...o&&{recentReplierIds:o.map(w)}}}function xe(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i}=e;return{...Ve(e.user),fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description}}}}function Ve(e){if(!(e instanceof o.Api.User))return;const{id:t,firstName:n,lastName:s}=e,a=e.photo instanceof o.Api.UserProfilePhoto?String(e.photo.photoId):void 0,i=(r=e).bot?"userTypeBot":r.deleted?"userTypeDeleted":"userTypeRegular";var r;return{id:t,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||"",status:Fe(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a},...e.bot&&e.botInlinePlaceholder&&{botPlaceholder:e.botInlinePlaceholder}}}function Fe(e){return!e||e instanceof o.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof o.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof o.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof o.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof o.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}function Ne(e){if(e instanceof o.Api.WallPaperNoFile)return;const{slug:t}=e,n=Me(e.document);return n?{slug:t,document:n}:void 0}function Oe(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...d(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function Le(e){let t,n,s,a,i;return e.forEach((e=>{e instanceof o.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof o.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof o.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof o.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof o.Api.PrivacyValueAllowUsers?n=e.users:e instanceof o.Api.PrivacyValueDisallowUsers?a=e.users:e instanceof o.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>-e)):e instanceof o.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>-e)))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function qe(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:r}=e;return{chatId:w(t),isMuted:s||"number"==typeof a&&Date.now()+1e3*n<1e3*a,...""===r&&{isSilent:!0},...void 0!==i&&{shouldShowPreviews:Boolean(i)}}}const He=new Set;let Ge=0;function Ke(e,t){if(e instanceof o.connection.UpdateServerTimeOffset)Ge=e.timeOffset;else if(e instanceof o.connection.UpdateConnectionState){let t;switch(e.state){case o.connection.UpdateConnectionState.disconnected:t="connectionStateConnecting";break;case o.connection.UpdateConnectionState.broken:t="connectionStateBroken";break;case o.connection.UpdateConnectionState.connected:default:t="connectionStateReady"}be({"@type":"updateConnectionState",connectionState:t})}else if(e instanceof o.Api.UpdateNewMessage||e instanceof o.Api.UpdateNewScheduledMessage||e instanceof o.Api.UpdateNewChannelMessage||e instanceof o.Api.UpdateShortChatMessage||e instanceof o.Api.UpdateShortMessage||e instanceof o.Api.UpdateServiceNotification){let t;if(e instanceof o.Api.UpdateShortChatMessage)t=Ce(w({chatId:(n=e).chatId}),{...n,fromId:X(n.fromId)});else if(e instanceof o.Api.UpdateShortMessage)t=function(e){return Ce(w({userId:e.userId}),{...e,fromId:X(e.out?ye:e.userId)})}(e);else if(e instanceof o.Api.UpdateServiceNotification)t=function(e,t){const n=we++;let s={};return e.media&&(s={...ve(e.media)}),!e.message||s.sticker||s.poll||s.contact||(s={...s,text:Pe(e.message,e.entities)}),{id:n,chatId:777e3,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+Ge),ce(e)&&me(ie(t.id,t.chatId,e));else{if(e.message instanceof o.Api.MessageEmpty)return;e.message instanceof o.Api.Message&&ce(e.message)&&me(e.message),t=Ie(e.message)}const s=e._entities;if(s&&s.length&&(s.filter((e=>e instanceof o.Api.User)).map(Ve).forEach((e=>{e&&be({"@type":"updateUser",id:e.id,user:e})})),s.filter((e=>e instanceof o.Api.Chat||e instanceof o.Api.Channel)).map((e=>b(e))).forEach((e=>{e&&be({"@type":"updateChat",id:e.id,chat:e})}))),e instanceof o.Api.UpdateNewScheduledMessage?be({"@type":He.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):be({"@type":He.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t}),e.message instanceof o.Api.MessageService){const{action:n}=e.message;if(n instanceof o.Api.MessageActionChatEditTitle)be({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof o.Api.MessageActionChatEditPhoto){const s=function(e){if(e instanceof o.Api.PhotoEmpty)return new o.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new o.Api.ChatPhoto({dcId:t,photoId:n})}(n.photo),a=S(s),i=Math.abs(he(e.message));N.chats[i]&&(N.chats[i].photo=s),_e(n.photo),a&&be({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof o.Api.Photo&&{newProfilePhoto:V(n.photo)}})}else if(n instanceof o.Api.MessageActionChatDeletePhoto){const n=Math.abs(he(e.message));N.chats[n]&&(N.chats[n].photo=new o.Api.ChatPhotoEmpty),be({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof o.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some((e=>e instanceof o.Api.User&&!!e.self&&e.id===n.userId))&&(be({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),be({"@type":"updateChatLeave",id:t.chatId})):n instanceof o.Api.MessageActionChatAddUser&&e._entities&&e._entities.some((e=>e instanceof o.Api.User&&!!e.self&&n.users.includes(e.id)))&&be({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof o.Api.UpdateEditMessage||e instanceof o.Api.UpdateEditChannelMessage){if(e.message instanceof o.Api.MessageEmpty)return;e.message instanceof o.Api.Message&&ce(e.message)&&me(e.message);const t=Ie(e.message);be({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof o.Api.UpdateDeleteMessages)be({"@type":"deleteMessages",ids:e.messages});else if(e instanceof o.Api.UpdateDeleteScheduledMessages)be({"@type":"deleteScheduledMessages",ids:e.messages,chatId:I(e.peer)});else if(e instanceof o.Api.UpdateDeleteChannelMessages){const t=w({channelId:e.channelId}),n=e.messages,s=n.filter((e=>N.messages[`${t}-${e}`])),a=n.filter((e=>!N.messages[`${t}-${e}`])),i=n.map((e=>{const n=N.messages[`${t}-${e}`];return n&&n instanceof o.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0})).filter(Boolean);s.length&&be({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&be({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{be({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if((t instanceof o.Api.messages.SendMessage||t instanceof o.Api.messages.SendMedia||t instanceof o.Api.messages.SendMultiMedia||t instanceof o.Api.messages.ForwardMessages)&&(e instanceof o.Api.UpdateMessageID||e instanceof o.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const s=n&&N.localMessages[n.toString()];if(!s)throw new Error("Local message not found");let a;if(e instanceof o.Api.UpdateShortSentMessage){s.content.text&&e.entities&&(a={text:Pe(s.content.text.text,e.entities)}),e.media&&(a={...a,...ve(e.media)});const t=ie(e.id,s.chatId,e);ce(t)&&me(t)}He.add(e.id);const i="date"in e&&1e3*e.dateString.fromCharCode(...e)))});else if(e instanceof o.Api.UpdateChannelMessageViews)be({"@type":"updateMessage",chatId:w({channelId:e.channelId}),id:e.id,message:{views:e.views}});else if(e instanceof o.Api.UpdateReadHistoryInbox)be({"@type":"updateChatInbox",id:w(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof o.Api.UpdateReadHistoryOutbox)be({"@type":"updateChat",id:w(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof o.Api.UpdateReadChannelInbox)be({"@type":"updateChat",id:w({channelId:e.channelId}),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof o.Api.UpdateReadChannelOutbox)be({"@type":"updateChat",id:w({channelId:e.channelId}),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof o.Api.UpdateDialogPinned&&e.peer instanceof o.Api.DialogPeer)be({"@type":"updateChatPinned",id:w(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof o.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter((e=>e instanceof o.Api.DialogPeer)).map((e=>w(e.peer))):[];be({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof o.Api.UpdateFolderPeers)e.folderPeers.forEach((e=>{const{folderId:t,peer:n}=e;be({"@type":"updateChatListType",id:w(n),folderId:t})}));else if(e instanceof o.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?U(n):void 0;be({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof o.Api.UpdateDialogFilterOrder)be({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof o.Api.UpdateChatParticipants){const t=k(e.participants);be({"@type":"updateChatMembers",id:w({chatId:e.participants.chatId}),replacedMembers:t})}else if(e instanceof o.Api.UpdateChatParticipantAdd){const t=M(d(e,["userId","inviterId","date"]));be({"@type":"updateChatMembers",id:w({chatId:e.chatId}),addedMember:t})}else if(e instanceof o.Api.UpdateChatParticipantDelete){const{userId:t}=e;be({"@type":"updateChatMembers",id:w({chatId:e.chatId}),deletedMemberId:t})}else if(e instanceof o.Api.UpdatePinnedMessages||e instanceof o.Api.UpdatePinnedChannelMessages){const t=w(e instanceof o.Api.UpdatePinnedMessages?e.peer:{channelId:e.channelId});be({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof o.Api.UpdateNotifySettings&&e.peer instanceof o.Api.NotifyPeer)be({"@type":"updateNotifyExceptions",...qe(e.notifySettings,e.peer.peer,Ge)});else if(e instanceof o.Api.UpdateUserTyping||e instanceof o.Api.UpdateChatUserTyping){const t=e instanceof o.Api.UpdateUserTyping?e.userId:w({chatId:e.chatId});be({"@type":"updateChatTypingStatus",id:t,typingStatus:R(e,Ge)})}else if(e instanceof o.Api.UpdateChannelUserTyping){const t=w({channelId:e.channelId});be({"@type":"updateChatTypingStatus",id:t,typingStatus:R(e,Ge)})}else if(e instanceof o.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find((e=>e instanceof o.Api.Channel||e instanceof o.Api.ChannelForbidden));if(n instanceof o.Api.Channel){const t=b(n);t&&(be({"@type":"updateChat",id:t.id,chat:t}),be({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:w({channelId:e.channelId})}))}else if(n instanceof o.Api.ChannelForbidden){const t=w({channelId:e.channelId});be({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),be({"@type":"updateChatLeave",id:t})}else 0===t.length&&be({"@type":"resetMessages",id:w({chatId:e.channelId})})}else if(e instanceof o.Api.UpdateDialogUnreadMark&&e.peer instanceof o.Api.DialogPeer)be({"@type":"updateChat",id:w(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof o.Api.UpdateChatDefaultBannedRights)be({"@type":"updateChat",id:w(e.peer),chat:{defaultBannedRights:p(e.defaultBannedRights)}});else if(e instanceof o.Api.UpdateUserStatus){const{userId:t,status:n}=e;be({"@type":"updateUserStatus",userId:t,status:Fe(n)})}else if(e instanceof o.Api.UpdateUserName){const t=N.users[e.userId],n=t&&t.mutualContact&&!t.self?d(e,["username"]):d(e,["firstName","lastName","username"]);be({"@type":"updateUser",id:e.userId,user:n})}else if(e instanceof o.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=S(n);N.users[t]&&(N.users[t].photo=n),be({"@type":"updateUser",id:t,user:{avatarHash:s}})}else if(e instanceof o.Api.UpdateUserPhone){const{userId:t,phone:n}=e;be({"@type":"updateUser",id:t,user:{phoneNumber:n}})}else if(e instanceof o.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;t&&t.length&&(t.filter((e=>e instanceof o.Api.User&&!e.contact)).forEach((e=>{be({"@type":"deleteUser",id:e.id})})),t.filter((e=>e instanceof o.Api.User&&e.contact)).map(Ve).forEach((e=>{e&&be({"@type":"updateUser",id:e.id,user:e})})))}else if(e instanceof o.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;be({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*Ge<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof o.Api.UpdatePeerBlocked)be({"@type":"updatePeerBlocked",id:w(e.peerId),isBlocked:e.blocked});else if(e instanceof o.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&&be({"@type":"updatePrivacy",key:t,rules:Le(e.rules)})}else e instanceof o.Api.UpdateDraftMessage?be({"@type":"draftMessage",chatId:w(e.peer),...Ae(e.draft)}):e instanceof o.Api.UpdateContactsReset?be({"@type":"updateResetContactList"}):e instanceof o.Api.UpdateFavedStickers&&be({"@type":"updateFavoriteStickers"});var n}const ze={PHONE_NUMBER_INVALID:"PHONE_NUMBER_INVALID",PHONE_CODE_INVALID:"PHONE_CODE_INVALID",PASSWORD_HASH_INVALID:"PASSWORD_HASH_INVALID",PHONE_PASSWORD_FLOOD:"You have tried logging in too many times"},We={};let je;function $e(){return je(et("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{We.resolve=e,We.reject=t}))}function Je(e=!1){return je({...et("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{We.resolve=e,We.reject=t}))}function Qe(e){return je({...et("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{We.resolve=e}))}function Xe(){return je(et("authorizationStateWaitRegistration")),new Promise((e=>{We.resolve=e}))}function Ze(e){return je({...et("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{We.reject=t}))}function Ye(e){let t;if(e instanceof o.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=ze[e.message];t||(t="Unexpected Error"),je({"@type":"updateAuthorizationError",message:t})}function et(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function tt(e){We.resolve&&We.resolve(e)}function nt(e){We.resolve&&We.resolve(e)}function st(e){We.resolve&&We.resolve(e)}function at(e){const{firstName:t,lastName:n}=e;We.resolve&&We.resolve([t,n])}function it(){We.reject&&We.reject(new Error("RESTART_AUTH"))}function rt(){We.reject&&We.reject(new Error("RESTART_AUTH_WITH_QR"))}var ot=n(9832),ct=n(5802);function dt(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}),dt(this,"name",void 0),Object.assign(this,s)}else super(e),dt(this,"name",void 0);this.name=t}});const lt=self.caches;let ut;async function gt(e,t,n){if(lt)try{const s=new Request(t.replace(/:/g,"_")),a=await lt.open(e),i=await a.match(s);if(!i)return;switch(n){case ut.Text:return await i.text();case ut.Blob:{const e=await i.blob();if("sticker"===t.substr(0,7))return new Blob([e],{type:"image/webp"});if(!e.type){const t=i.headers.get("Content-Type");if(t)return new Blob([e],{type:t})}return e}case ut.Json:return await i.json();default:return}}catch(e){return void console.warn(e)}}async function pt(e,t,n){if(lt)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),a=new Request(t.replace(/:/g,"_")),i=new Response(s),r=await lt.open(e);return await r.put(a,i)}catch(e){return void console.warn(e)}}async function ft(e){try{if(!lt)return;return await lt.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"}(ut||(ut={}));const ht=new Set(["msg","sticker","gif","wallpaper","photo","webDocument"]);function mt(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}ot.Logger.setLevel("warn");const _t={build:e=>e};let yt,bt,wt=!1;async function It(){await vt(new o.Api.auth.LogOut),await bt.destroy()}async function Ct(){await bt.disconnect()}function Pt(e){yt({"@type":"updateSession",sessionData:e})}function At(e){e instanceof o.connection.UpdateConnectionState?wt=e.state===o.connection.UpdateConnectionState.connected:e instanceof o.Api.UpdatesTooLong?async function(){try{await vt(new o.Api.users.GetFullUser({id:new o.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&yt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof o.connection.UpdateServerTimeOffset&&yt({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function vt(e,t=!1,n=!1){if(wt)try{const n=await bt.invoke(e);if(t){let t;n instanceof o.Api.Updates||n instanceof o.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof o.Api.Updates||n.updates instanceof o.Api.UpdatesCombined)&&(t=n.updates),t?(function(e){const t=[...e.users,...e.chats];e.updates.forEach((e=>{t&&(e._entities=t)}))}(t),t.updates.forEach((t=>{Ke(t,e)}))):n instanceof o.Api.UpdatesTooLong||Ke(n,e)}return n}catch(t){if(function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof o.Api.messages.SendMessage||t instanceof o.Api.messages.SendMedia||t instanceof o.Api.messages.SendMultiMedia),{message:s}=e;yt({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}(t,e),n)throw t;return}}function St(e,t){return async function({url:e,mediaFormat:t,start:n,end:a},i,r,c){const{data:d,mimeType:l,fullSize:u}=await async function(e,t,n,s,a,i,r){const c=e.startsWith("webDocument")?e.match(/(webDocument):(.+)/):e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?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,l=c[2];const u=c[3]?c[3].replace("?size=",""):void 0;let g;switch("avatar"===c[1]||"profile"===c[1]?(d=Q(Number(l)),l=Math.abs(Number(l))):d=c[1],d){case"channel":case"chat":g=N.chats[l];break;case"user":g=N.users[l];break;case"msg":g=N.messages[l];break;case"sticker":case"gif":case"wallpaper":g=N.documents[l];break;case"photo":g=N.photos[l];break;case"stickerSet":g=N.stickerSets[l];break;case"webDocument":g=N.webDocuments[l]}if(g){if(ht.has(d)){r===$.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(g,{sizeType:u,start:a,end:i,progressCallback:s,workers:16});let n,c;return g instanceof o.Api.Message?(n=function(e,t){if(e&&e.media)return e.media instanceof o.Api.MessageMediaPhoto?"image/jpeg":e.media instanceof o.Api.MessageMediaDocument&&e.media.document instanceof o.Api.Document?t?e.media.document.attributes.some((e=>e instanceof o.Api.DocumentAttributeSticker))?"image/webp":"image/jpeg":e.media.document.mimeType:e.media instanceof o.Api.MessageMediaWebPage&&e.media.webpage instanceof o.Api.WebPage&&e.media.webpage.document instanceof o.Api.Document?e.media.webpage.document.mimeType:void 0}(g,u),g.media instanceof o.Api.MessageMediaDocument&&g.media.document instanceof o.Api.Document&&(c=g.media.document.size),g.media instanceof o.Api.MessageMediaWebPage&&g.media.webpage instanceof o.Api.WebPage&&g.media.webpage.document instanceof o.Api.Document&&(c=g.media.webpage.document.size)):g instanceof o.Api.Photo?n="image/jpeg":"sticker"===d&&u?n="image/webp":"webDocument"===d?n=g.mimeType:(n=g.mimeType,c=g.size),{mimeType:n,data:e,fullSize:c}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(g);return{mimeType:r===$.Lottie?"application/json":mt(e),data:e}}{const e=await t.downloadProfilePhoto(g,"profile"===c[1]);return{mimeType:mt(e),data:e}}}}(e,i,r,c,n,a,t)||{};if(!d)return;const g=await async function(e,t,n){switch(t){case $.DataUri:return s=new Blob([e],{type:n}),new Promise(((e,t)=>{const n=new FileReader;n.onload=n=>{const{result:s}=n.target||{};"string"==typeof s&&e(s),t(new Error("Failed to read blob"))},n.onerror=t,n.readAsDataURL(s)}));case $.BlobUrl:return new Blob([e],{type:n});case $.Lottie:{const t=(0,ct.inflate)(e,{to:"string"});return JSON.parse(t)}case $.Progressive:return e.buffer}var s}(d,t,l);if(!g)return;const p=t!==$.Progressive&&(t!==$.BlobUrl||g.size<=524288);return s&&p&&pt(e.startsWith("avatar")?"tt-media-avatars":"tt-media",e,g),{prepared:t===$.Progressive?"":(f=g,f instanceof Blob?f.type.includes("text/html")?URL.createObjectURL(function(e){const t="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==".split(","),n=t[0].match(/:(.*?);/)[1],s=atob(t[1]);let a=s.length;const i=new Uint8Array(a);for(;a--;)i[a]=s.charCodeAt(a);return new Blob([i],{type:n})}()):URL.createObjectURL(f):f),arrayBuffer:t===$.Progressive?g:void 0,mimeType:l,fullSize:u};var f}(e,bt,wt,t)}function Mt(e,t){return bt.uploadFile({file:e,onProgress:t,workers:16})}function kt(e){return bt.updateTwoFaSettings(e)}async function Rt(){const e=await vt(new o.Api.users.GetFullUser({id:new o.Api.InputUserSelf}));if(!(e&&e.user instanceof o.Api.User))return;N.users[e.user.id]=e.user;const t=xe(e);var n;n=t.id,ye=n,function(e){je({"@type":"updateCurrentUser",currentUser:e})}(t)}const Ut=2**31-1;let Et;async function Dt({limit:e,offsetDate:t,archived:n,withPinned:s,serverTimeOffset:a}){const i=await vt(new o.Api.messages.GetDialogs({offsetPeer:new o.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?1:void 0,...s&&{excludePinned:!0}})),r=s?await vt(new o.Api.messages.GetPinnedDialogs({folderId:n?1:void 0})):void 0;if(!i||i instanceof o.Api.messages.DialogsNotModified)return;r&&yn(r),yn(i);const d=c((r?r.messages:[]).concat(i.messages).map(Ie).filter(Boolean),"chatId"),l={...r&&_n(r),..._n(i)},u=[],g={},p={},f=(r?r.dialogs:[]).concat(i.dialogs),m=[];f.forEach((e=>{if(!(e instanceof o.Api.Dialog)||!n&&1===e.folderId||n&&1!==e.folderId)return;const t=h(e,l[P(e.peer)],a);if(t.lastMessage=d[t.id],t.isListed=!0,u.push(t),s&&e.pinned&&m.push(t.id),e.draft){const{formattedText:n,replyingToId:s}=Ae(e.draft)||{};n&&(g[t.id]=n),s&&(p[t.id]=s)}}));const _=(r?r.users:[]).concat(i.users).map(Ve).filter(Boolean),y=u.map((e=>e.id));let b;return b=i instanceof o.Api.messages.DialogsSlice?i.count:y.length,{chatIds:y,chats:u,users:_,draftsById:g,replyingToById:p,orderedPinnedIds:s?m:void 0,totalChatCount:b}}function Tt(e){const{id:t,accessHash:n,adminRights:s}=e;return ee(t,n)instanceof o.Api.InputChannel?async function(e,t,n){const s=await vt(new o.Api.channels.GetFullChannel({channel:ee(e,t)}));if(!(s&&s.fullChat instanceof o.Api.ChannelFull))return;const{about:a,onlineCount:i,exportedInvite:r,slowmodeSeconds:c,slowmodeNextSendDate:d,migratedFromChatId:l,migratedFromMaxId:u,canViewParticipants:g,linkedChatId:p,hiddenPrehistory:f,call:h}=s.fullChat,m=r instanceof o.Api.ChatInviteExported?r.link:void 0,{members:_,users:y}=g&&await ln(e,t)||{},{members:b,users:I}=g&&n&&await ln(e,t,"kicked")||{},{members:C,users:P}=g&&n&&await ln(e,t,"admin")||{};return{fullInfo:{about:a,onlineCount:i,inviteLink:m,slowMode:c?{seconds:c,nextSendDate:d}:void 0,migratedFrom:l?{chatId:w({chatId:l}),maxMessageId:u}:void 0,canViewMembers:g,isPreHistoryHidden:f,members:_,kickedMembers:b,adminMembers:C,groupCallId:h?h.id.toString():void 0,linkedChatId:p?w({chatId:p}):void 0},users:[...y||[],...I||[],...P||[]]}}(t,n,s):async function(e){const t=await vt(new o.Api.messages.GetFullChat({chatId:ee(e)}));if(!(t&&t.fullChat instanceof o.Api.ChatFull))return;yn(t);const{about:n,participants:s,exportedInvite:a}=t.fullChat,i=k(s),r=i?i.filter((({isAdmin:e,isOwner:t})=>e||t)):void 0;return{fullInfo:{about:n,members:i,adminMembers:r,canViewMembers:!0,...a&&{inviteLink:a.link}},users:t.users.map(Ve).filter(Boolean)}}(t)}async function Bt({query:e}){const t=await vt(new o.Api.contacts.Search({q:e}));if(!t)return;yn(t);const n=t.myResults.map(w),s=t.chats.concat(t.users).map((e=>b(e))).filter(Boolean),a=t.users.map(Ve).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 xt({type:e,user:t}){let n;if("self"===e||"user"===e){const s=await vt(new o.Api.users.GetUsers({id:["user"===e&&t?ee(t.id,t.accessHash):new o.Api.InputUserSelf]}));if(!s||!s.length)return;[n]=s}else if("support"===e){const e=await vt(new o.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const s=b(n,"support"===e);if(s)return Et({"@type":"updateChat",id:s.id,chat:s}),{chatId:s.id}}async function Vt({chat:e,serverTimeOffset:t}){const{id:n,accessHash:s}=e,a=await vt(new o.Api.messages.GetPeerDialogs({peers:[new o.Api.InputDialogPeer({peer:Z(n,s)})]}));if(!a)return;const i=a.dialogs[0];if(!(i&&i instanceof o.Api.Dialog))return;const r=_n(a)[P(i.peer)];if(!r)return;yn(a);const c=Ie(a.messages[0]);Et({"@type":"updateChat",id:n,chat:{...h(i,r,t),lastMessage:c}})}function Ft({chat:e,text:t,entities:n,replyToMsgId:s}){return vt(new o.Api.messages.SaveDraft({peer:Z(e.id,e.accessHash),message:t,...n&&{entities:n.map(re)},replyToMsgId:s}))}function Nt(e){return vt(new o.Api.messages.SaveDraft({peer:Z(e.id,e.accessHash),message:""}))}async function Ot({chat:e,isMuted:t,serverTimeOffset:n}){await vt(new o.Api.account.UpdateNotifySettings({peer:new o.Api.InputNotifyPeer({peer:Z(e.id,e.accessHash)}),settings:new o.Api.InputPeerNotifySettings({muteUntil:t?Ut:0})})),Et({"@type":"updateNotifyExceptions",chatId:e.id,isMuted:t}),Vt({chat:e,serverTimeOffset:n})}async function Lt({title:e,about:t,users:n}){const s=await vt(new o.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(s instanceof o.Api.Updates))return;const a=s.chats[0];if(!(a&&a instanceof o.Api.Channel))return;const i=b(a);return await vt(new o.Api.channels.InviteToChannel({channel:ee(i.id,i.accessHash),users:n.map((({id:e,accessHash:t})=>ee(e,t)))})),i}function qt({channelId:e,accessHash:t}){return vt(new o.Api.channels.JoinChannel({channel:ee(e,t)}),!0)}function Ht({chat:e,user:t}){if("chatTypeBasicGroup"===e.type)return vt(new o.Api.messages.DeleteChatUser({chatId:ee(e.id,e.accessHash),userId:ee(t.id,t.accessHash)}),!0)}function Gt({chatId:e}){return vt(new o.Api.messages.DeleteChat({chatId:ee(e)}),!0)}function Kt({channelId:e,accessHash:t}){return vt(new o.Api.channels.LeaveChannel({channel:ee(e,t)}),!0)}function zt({channelId:e,accessHash:t}){return vt(new o.Api.channels.DeleteChannel({channel:ee(e,t)}),!0)}async function Wt({title:e,users:t}){const n=await vt(new o.Api.messages.CreateChat({title:e,users:t.map((({id:e,accessHash:t})=>ee(e,t)))}),!0);if(!(n instanceof o.Api.Updates))return;const s=n.chats[0];return s&&s instanceof o.Api.Chat?b(s):void 0}async function jt({chatId:e,accessHash:t,photo:n}){const s=await Mt(n),a=ee(e,t);return vt(a instanceof o.Api.InputChannel?new o.Api.channels.EditPhoto({channel:a,photo:new o.Api.InputChatUploadedPhoto({file:s})}):new o.Api.messages.EditChatPhoto({chatId:a,photo:new o.Api.InputChatUploadedPhoto({file:s})}),!0)}async function $t({chat:e,shouldBePinned:t}){const{id:n,accessHash:s}=e;await vt(new o.Api.messages.ToggleDialogPin({peer:new o.Api.InputDialogPeer({peer:Z(n,s)}),pinned:t||void 0}))&&Et({"@type":"updateChatPinned",id:e.id,isPinned:t})}function Jt({chat:e,folderId:t}){const{id:n,accessHash:s}=e;return vt(new o.Api.folders.EditPeerFolders({folderPeers:[new o.Api.InputFolderPeer({peer:Z(n,s),folderId:t})]}),!0)}async function Qt(){const e=await vt(new o.Api.messages.GetDialogFilters);if(e)return{byId:c(e.map(U),"id"),orderedIds:e.map((({id:e})=>e))}}async function Xt(){const e=await vt(new o.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(E)}async function Zt({id:e,folderUpdate:t}){const n=function(e){const{emoticon:t,contacts:n,nonContacts:s,groups:a,channels:i,bots:r,excludeArchived:c,excludeMuted:d,excludeRead:l,pinnedChatIds:u,includedChatIds:g,excludedChatIds:p}=e,f=u?u.map(Y).filter(Boolean):[],h=g?g.map(Y).filter(Boolean):[],m=p?p.map(Y).filter(Boolean):[];return new o.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:r||void 0,excludeArchived:c||void 0,excludeMuted:d||void 0,excludeRead:l||void 0,broadcasts:i||void 0,pinnedPeers:f,includePeers:h,excludePeers:m})}(t);await vt(new o.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&Et({"@type":"updateChatFolder",id:e,folder:t})}async function Yt(e){const t=await vt(new o.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await Xt();t&&Et({"@type":"updateChatFolder",id:e,folder:void 0}),n&&Et({"@type":"updateRecommendedChatFolders",folders:n})}async function en({chat:e,hasUnreadMark:t}){const{id:n,accessHash:s}=e;await vt(new o.Api.messages.MarkDialogUnread({peer:new o.Api.InputDialogPeer({peer:Z(n,s)}),unread:t||void 0}))&&Et({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function tn(e){const t=await vt(new o.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:s}=t,a=s.length?b(s[0]):b(n[0]);return a?(yn(t),a):void 0}function nn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=ee(n,s);return vt(new o.Api.channels.TogglePreHistoryHidden({channel:a,enabled:t}),!0)}function sn({chat:e,bannedRights:t}){const{id:n,accessHash:s}=e,a=Z(n,s);return vt(new o.Api.messages.EditChatDefaultBannedRights({peer:a,bannedRights:le(t)}),!0)}function an({chat:e,user:t,bannedRights:n,untilDate:s}){const a=ee(e.id,e.accessHash),i=Z(t.id,t.accessHash);return vt(new o.Api.channels.EditBanned({channel:a,participant:i,bannedRights:le(n,s)}),!0)}function rn({chat:e,user:t,adminRights:n,customTitle:s=""}){const a=ee(e.id,e.accessHash),i=ee(t.id,t.accessHash);return vt(new o.Api.channels.EditAdmin({channel:a,userId:i,adminRights:ue(n),rank:s}),!0)}async function on(e,t){const n=ee(e.id,e.accessHash);await vt(n instanceof o.Api.InputChannel?new o.Api.channels.EditTitle({channel:n,title:t}):new o.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function cn(e,t){await vt(new o.Api.messages.EditChatAbout({peer:Z(e.id,e.accessHash),about:t}))&&Et({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function dn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=ee(n,s);return vt(new o.Api.channels.ToggleSignatures({channel:a,enabled:t}),!0)}async function ln(e,t,n="recent",s){let a;switch(n){case"kicked":a=new o.Api.ChannelParticipantsKicked({q:""});break;case"admin":a=new o.Api.ChannelParticipantsAdmins;break;default:a=new o.Api.ChannelParticipantsRecent}const i=await vt(new o.Api.channels.GetParticipants({channel:ee(e,t),filter:a,offset:s,limit:200}));if(i&&!(i instanceof o.Api.channels.ChannelParticipantsNotModified))return yn(i),{members:k(i),users:i.users.map(Ve).filter(Boolean)}}async function un(){const e=await vt(new o.Api.channels.GetGroupsForDiscussion);if(e)return yn(e),e.chats.map((e=>b(e)))}function gn({channel:e,chat:t}){return vt(new o.Api.channels.SetDiscussionGroup({broadcast:Z(e.id,e.accessHash),group:t?Z(t.id,t.accessHash):new o.Api.InputChannelEmpty}))}async function pn(e){const t=await vt(new o.Api.messages.MigrateChat({chatId:ee(e.id)}),!0);if(t&&t instanceof o.Api.Updates)return yn(t),b(t.chats[1])}async function fn(e){const t=await vt(new o.Api.messages.CheckChatInvite({hash:e}));if(!t)return;let n;return t instanceof o.Api.ChatInvite?Et({"@type":"showInvite",data:{title:t.title,hash:e,participantsCount:t.participantsCount,isChannel:t.channel}}):(n=b(t.chat),n&&Et({"@type":"updateChat",id:n.id,chat:n})),n?{chatId:n.id}:void 0}function hn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?vt(new o.Api.channels.InviteToChannel({channel:ee(e.id,e.accessHash),users:t.map((e=>ee(e.id,e.accessHash)))}),!0):Promise.all(t.map((t=>vt(new o.Api.messages.AddChatUser({chatId:ee(e.id),userId:ee(t.id,t.accessHash)}),!0))))}function mn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?an({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:Ut}):vt(new o.Api.messages.DeleteChatUser({chatId:ee(e.id),userId:ee(t.id,t.accessHash)}),!0)}function _n(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function yn(e){"users"in e&&e.users.forEach((e=>{e instanceof o.Api.User&&(N.users[e.id]=e)})),"chats"in e&&e.chats.forEach((e=>{(e instanceof o.Api.Chat||e instanceof o.Api.Channel)&&(N.chats[e.id]=e)})),"messages"in e&&e.messages.forEach((e=>{e instanceof o.Api.Message&&ce(e)&&me(e)}))}async function bn({hash:e}){const t=await vt(new o.Api.messages.ImportChatInvite({hash:e}),!0);if(t instanceof o.Api.Updates&&t.chats.length)return b(t.chats[0])}var wn=n(8764).Buffer;let In;async function Cn({chat:e,threadId:t,...n}){const s=-1===t?o.Api.messages.GetHistory:o.Api.messages.GetReplies;let a;try{a=await vt(new s({peer:Z(e.id,e.accessHash),...-1!==t&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&In({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!a||a instanceof o.Api.messages.MessagesNotModified||!a.messages)return;$n(a);const i=a.messages.map(Ie).filter(Boolean),r=a.users.map(Ve).filter(Boolean),c=a.chats.map((e=>b(e))).filter(Boolean),d=i.map((({threadInfo:e})=>e)).filter(Boolean);return{messages:i,users:r,chats:c,threadInfos:d}}async function Pn({chat:e,messageId:t}){const n="channel"===Q(e.id),s=await vt(n?new o.Api.channels.GetMessages({channel:ee(e.id,e.accessHash),id:[new o.Api.InputMessageID({id:t})]}):new o.Api.messages.GetMessages({id:[new o.Api.InputMessageID({id:t})]}));if(!s||s instanceof o.Api.messages.MessagesNotModified)return;const a=s.messages[0];if(!a)return;if(a instanceof o.Api.MessageEmpty)return"MESSAGE_DELETED";const i=a&&Ie(a);return i?(a instanceof o.Api.Message&&me(a),{message:i,users:s.users.map(Ve).filter(Boolean)}):void 0}let An=Promise.resolve();function vn({chat:e,text:t,entities:n,replyingTo:s,attachment:a,sticker:i,gif:r,poll:c,isSilent:d,scheduledAt:l,groupedId:u,noWebPage:g,serverTimeOffset:p},f){const h=function(e,t,n,s,a,i,r,o,c,d,l=0){const u=we++,g=a&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:a,size:i}=e;if(e.quick){const{width:r,height:o,duration:c}=e.quick;return a.startsWith("image/")?{photo:{id:"temp",sizes:[],thumbnail:{width:r,height:o,dataUri:""},blobUrl:n}}:{video:{id:"temp",mimeType:a,duration:c||0,fileName:t,width:r,height:o,blobUrl:n,...s&&{thumbnail:{width:r,height:o,dataUri:s}},size:i}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=G(n,63);return{voice:{duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}(a),p="chatTypeChannel"===e.type;return{id:u,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...g,...i&&{sticker:i},...r&&{video:r},...o&&De(o,u)},date:d||Math.round(Date.now()/1e3)+l,isOutgoing:!p,senderId:ye,...s&&{replyToMessageId:s},...c&&{groupedId:c,...g&&(g.photo||g.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}(e,t,n,s,a,i,r,c,u,l,p);In({"@type":h.isScheduled?"newScheduledMessage":"newMessage",id:h.id,chatId:e.id,message:h}),setTimeout((()=>{In({"@type":h.isScheduled?"updateScheduledMessage":"updateMessage",id:h.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const m=ae();if(N.localMessages[m.toString()]=h,u)return function({chat:e,text:t,entities:n,replyingTo:s,attachment:a,groupedId:i,isSilent:r,scheduledAt:c},d,l,u){let g=-1;Sn[i]||(Sn[i]={counter:0,singleMediaByIndex:{}}),g=Sn[i].counter++;const p=An;return An=(async()=>{let f;try{f=await Rn(l,a,u)}catch(e){return Sn[i].counter--,void await p}const h=await async function(e,t){const n=await vt(new o.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof o.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof o.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:s}}=n;return new o.Api.InputMediaPhoto({id:new o.Api.InputPhoto({id:e,accessHash:t,fileReference:s})})}if(n instanceof o.Api.MessageMediaDocument&&n.document&&n.document instanceof o.Api.Document){const{document:{id:e,accessHash:t,fileReference:s}}=n;return new o.Api.InputMediaDocument({id:new o.Api.InputDocument({id:e,accessHash:t,fileReference:s})})}}(Z(e.id,e.accessHash),f);if(await p,!h)return void Sn[i].counter--;if(Sn[i].singleMediaByIndex[g]=new o.Api.InputSingleMedia({media:h,randomId:d,message:t||"",entities:n?n.map(re):void 0}),Object.keys(Sn[i].singleMediaByIndex).length{let u;if(a)try{u=await Rn(h,a,f)}catch(e){return void await _}else i?u=se(i):r?u=se(r):c&&(u=function(e,t){const{summary:n,quiz:s}=e,a=new o.Api.Poll({id:t,publicVoters:n.isPublic,question:n.question,answers:n.answers.map((({text:e,option:t})=>new o.Api.PollAnswer({text:e,option:J.from(t)}))),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new o.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map((e=>J.from(e))),{solution:r}=s,c=s.solutionEntities?s.solutionEntities.map(re):[];return new o.Api.InputMediaPoll({poll:a,correctAnswers:i,...r&&{solution:r,solutionEntities:c}})}(c,m));await _;const p=u?o.Api.messages.SendMedia:o.Api.messages.SendMessage;await vt(new p({clearDraft:!0,message:t||"",entities:n?n.map(re):void 0,peer:Z(e.id,e.accessHash),randomId:m,...d&&{silent:d},...l&&{scheduleDate:l},...s&&{replyToMsgId:s},...u&&{media:u},...g&&{noWebpage:g}}),!0)})(),An}const Sn={};async function Mn({chat:e,message:t,text:n,entities:s,noWebPage:a,serverTimeOffset:i}){const r=1e3*t.date>Date.now()+1e3*i,c={content:{...t.content,...n&&{text:{text:n,entities:s}}}};In({"@type":r?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:c}),N.localMessages[t.id]={...t,...c};const d=s&&s.map(re);await vt(new o.Api.messages.EditMessage({message:n||"",entities:d,peer:Z(e.id,e.accessHash),id:t.id,...r&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function kn({chat:e,message:t,scheduledAt:n}){await vt(new o.Api.messages.EditMessage({peer:Z(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function Rn(e,t,n){const{filename:s,blobUrl:a,mimeType:i,quick:r,voice:c}=t,d=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),l=t=>{n.isCanceled?l.isCanceled=!0:n(t,e.id)},u=await Mt(d,l),g=[new o.Api.DocumentAttributeFilename({fileName:s})];if(r){if(i.startsWith("image/"))return new o.Api.InputMediaUploadedPhoto({file:u});{const{width:e,height:t,duration:n}=r;void 0!==n&&g.push(new o.Api.DocumentAttributeVideo({duration:n,w:e,h:t}))}}if(c){const{duration:e,waveform:t}=c,{data:n}=G(t,63);g.push(new o.Api.DocumentAttributeAudio({voice:!0,duration:e,waveform:wn.from(n)}))}return new o.Api.InputMediaUploadedDocument({file:u,mimeType:i,attributes:g})}async function Un({chat:e,messageId:t,isUnpin:n,isOneSide:s,isSilent:a}){await vt(new o.Api.messages.UpdatePinnedMessage({peer:Z(e.id,e.accessHash),id:t,...n&&{unpin:!0},...s&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function En({chat:e}){await vt(new o.Api.messages.UnpinAllMessages({peer:Z(e.id,e.accessHash)}),!0)}async function Dn({chat:e,messageIds:t,shouldDeleteForAll:n}){const s="channel"===Q(e.id);await vt(s?new o.Api.channels.DeleteMessages({channel:ee(e.id,e.accessHash),id:t}):new o.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&In({"@type":"deleteMessages",ids:t,...s&&{chatId:e.id}})}async function Tn({chat:e,messageIds:t}){await vt(new o.Api.messages.DeleteScheduledMessages({peer:Z(e.id,e.accessHash),id:t}))&&In({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function Bn({chat:e,shouldDeleteForAll:t,maxId:n}){const s="channel"===Q(e.id);await vt(s?new o.Api.channels.DeleteHistory({channel:ee(e.id,e.accessHash),maxId:n}):new o.Api.messages.DeleteHistory({peer:Z(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&In({"@type":"deleteHistory",chatId:e.id})}async function xn({peer:e,messageIds:t,reason:n,description:s}){return await vt(new o.Api.messages.Report({peer:Z(e.id,e.accessHash),id:t,reason:fe(n),message:s}))}async function Vn({chat:e,threadId:t,maxId:n,serverTimeOffset:s}){const a="channel"===Q(e.id);a&&-1===t?await vt(new o.Api.channels.ReadHistory({channel:ee(e.id,e.accessHash),maxId:n})):a?await vt(new o.Api.messages.ReadDiscussion({peer:Z(e.id,e.accessHash),msgId:t,readMaxId:n})):await vt(new o.Api.messages.ReadHistory({peer:Z(e.id,e.accessHash),maxId:n})),-1===t?Vt({chat:e,serverTimeOffset:s}):Nn({chat:e,threadId:t})}async function Fn({chat:e,messageIds:t}){const n="channel"===Q(e.id);await vt(n?new o.Api.channels.ReadMessageContents({channel:ee(e.id,e.accessHash),id:t}):new o.Api.messages.ReadMessageContents({id:t})),In({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function Nn({chat:e,threadId:t}){const[n,s]=await Promise.all([vt(new o.Api.messages.GetDiscussionMessage({peer:Z(e.id,e.accessHash),msgId:t})),vt(new o.Api.messages.GetReplies({peer:Z(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=he(n.messages[0]);a&&(In({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:s instanceof o.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=>b(e))).filter(Boolean).forEach((e=>{In({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})))}async function On({chatOrUser:e,type:t,query:n,topMessageId:s,minDate:a,maxDate:i,...r}){let c;switch(t){case"media":c=new o.Api.InputMessagesFilterPhotoVideo;break;case"documents":c=new o.Api.InputMessagesFilterDocument;break;case"links":c=new o.Api.InputMessagesFilterUrl;break;case"audio":c=new o.Api.InputMessagesFilterMusic;break;case"voice":c=new o.Api.InputMessagesFilterVoice;break;case"profilePhoto":c=new o.Api.InputMessagesFilterChatPhotos;break;case"text":default:c=new o.Api.InputMessagesFilterEmpty}const d=await vt(new o.Api.messages.Search({peer:Z(e.id,e.accessHash),filter:c,q:n||"",topMsgId:s,minDate:a,maxDate:i,...r}));if(!d||d instanceof o.Api.messages.MessagesNotModified||!d.messages)return;$n(d);const l=d.messages.map(Ie).filter(Boolean),u=d.users.map(Ve).filter(Boolean);let g,p=l.length;return(d instanceof o.Api.messages.MessagesSlice||d instanceof o.Api.messages.ChannelMessages)&&(p=d.count,l.length&&(g=l[l.length-1].id)),{messages:l,users:u,totalCount:p,nextOffsetId:g}}async function Ln({query:e,offsetRate:t=0,limit:n,type:s="text",minDate:a,maxDate:i}){let r;switch(s){case"media":r=new o.Api.InputMessagesFilterPhotoVideo;break;case"documents":r=new o.Api.InputMessagesFilterDocument;break;case"links":r=new o.Api.InputMessagesFilterUrl;break;case"audio":r=new o.Api.InputMessagesFilterMusic;break;case"voice":r=new o.Api.InputMessagesFilterVoice;break;case"text":default:if(!(e||i&&a))return;r=new o.Api.InputMessagesFilterEmpty}const c=await vt(new o.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new o.Api.InputPeerEmpty,limit:n,filter:r,folderId:0,minDate:a,maxDate:i}));if(!c||c instanceof o.Api.messages.MessagesNotModified||!c.messages)return;$n({chats:c.chats,users:c.users,messages:c.messages});const d=c.chats.map((e=>b(e))).filter(Boolean),l=c.users.map(Ve).filter(Boolean),u=c.messages.map(Ie).filter(Boolean);let g,p=u.length;return(c instanceof o.Api.messages.MessagesSlice||c instanceof o.Api.messages.ChannelMessages)&&(p=c.count,u.length&&(g=u[u.length-1].id)),{messages:u,users:l,chats:d,totalCount:p,nextRate:"nextRate"in c&&c.nextRate?c.nextRate:g}}async function qn({message:e}){const t=await vt(new o.Api.messages.GetWebPagePreview({message:e}));return t&&Ue(t)}async function Hn({chat:e,messageId:t,options:n}){const{id:s,accessHash:a}=e;await vt(new o.Api.messages.SendVote({peer:Z(s,a),msgId:t,options:n.map((e=>wn.from(e)))}),!0)}async function Gn({chat:e,messageId:t,option:n,offset:s,limit:a,shouldResetVoters:i}){const{id:r,accessHash:c}=e,d=await vt(new o.Api.messages.GetPollVotes({peer:Z(r,c),id:t,...n&&{option:wn.from(n)},...s&&{offset:s},...a&&{limit:a}}));if(!d)return;$n({chats:[],users:d.users,messages:[]});const l=d.users.map(Ve).filter(Boolean),u=d.votes.map((e=>({userId:e.userId,date:e.date})));return{count:d.count,votes:u,users:l,nextOffset:d.nextOffset,shouldResetVoters:i}}async function Kn({fromChat:e,toChat:t,messages:n,serverTimeOffset:s}){const a=n.map((({id:e})=>e)),i=n.map(ae);n.forEach(((e,n)=>{const a=function(e,t,n){const s=we++,{content:a,chatId:i,id:r,senderId:o,groupedId:c,isInAlbum:d}=t,l=a.audio,u=e.id===ye&&(i!==e.id||t.forwardInfo)&&!l;return{id:s,chatId:e.id,content:a,date:Math.round(Date.now()/1e3)+n,isOutgoing:!u&&"chatTypeChannel"!==e.type,senderId:ye,sendingState:"messageSendingStatePending",...o!==ye&&!l&&{forwardInfo:{isChannelPost:!1,fromChatId:i,fromMessageId:r,senderUserId:o}},groupedId:c,isInAlbum:d}}(t,e,s);N.localMessages[String(i[n])]=a,In({"@type":"newMessage",id:a.id,chatId:t.id,message:a})})),await vt(new o.Api.messages.ForwardMessages({fromPeer:Z(e.id,e.accessHash),toPeer:Z(t.id,t.accessHash),randomId:i,id:a}),!0)}async function zn({chat:e,timestamp:t}){const n=await vt(new o.Api.messages.GetHistory({peer:Z(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof o.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function Wn({chat:e,hash:t=0}){const{id:n,accessHash:s}=e,a=await vt(new o.Api.messages.GetScheduledHistory({peer:Z(n,s),hash:t}));if(!a||a instanceof o.Api.messages.MessagesNotModified||!a.messages)return;$n(a);const i=a.messages.map(Ie).filter(Boolean);return{messages:i,hash:oe(i.map((e=>e.id)))}}async function jn({chat:e,ids:t}){const{id:n,accessHash:s}=e;await vt(new o.Api.messages.SendScheduledMessages({peer:Z(n,s),id:t}),!0)}function $n(e){e.users.forEach((e=>{e instanceof o.Api.User&&(N.users[e.id]=e)})),e.chats.forEach((e=>{(e instanceof o.Api.Chat||e instanceof o.Api.Channel)&&(N.chats[e.id]=e)})),e.messages.forEach((e=>{(e instanceof o.Api.Message&&ce(e)||e instanceof o.Api.MessageService&&function(e){return"photo"in e.action&&e.action.photo instanceof o.Api.Photo}(e))&&me(e)}))}async function Jn({chat:e}){const t=await vt(new o.Api.messages.Search({peer:Z(e.id,e.accessHash),filter:new o.Api.InputMessagesFilterPinned,q:"",limit:50}));if(t&&!(t instanceof o.Api.messages.MessagesNotModified)&&t.messages)return $n(t),{messages:t.messages.map(Ie).filter(Boolean),users:t.users.map(Ve).filter(Boolean),chats:t.chats.map((e=>b(e))).filter(Boolean)}}let Qn,Xn,Zn,Yn;async function es({id:e,accessHash:t}){const n=ee(e,t);if(!(n instanceof o.Api.InputUser))return;const s=await vt(new o.Api.users.GetFullUser({id:n}));if(!s)return;const a=xe(s);Qn({"@type":"updateUser",id:e,user:{fullInfo:a.fullInfo}})}async function ts(){const e=await vt(new o.Api.help.GetNearestDc);return e?e.country:void 0}async function ns({hash:e=0}){const t=await vt(new o.Api.contacts.GetTopPeers({hash:e,correspondents:!0}));if(!(t instanceof o.Api.contacts.TopPeers))return;const n=t.users.map(Ve).filter((e=>!!e&&!e.isSelf)),s=n.map((({id:e})=>e));return{hash:oe(s),ids:s,users:n}}async function ss({hash:e=0}){const t=await vt(new o.Api.contacts.GetContacts({hash:e}));if(t&&!(t instanceof o.Api.contacts.ContactsNotModified))return t.users.forEach((e=>{e instanceof o.Api.User&&(N.users[e.id]=e)})),{hash:oe([t.savedCount,...t.contacts.map((({userId:e})=>e))]),users:t.users.map(Ve).filter(Boolean),chats:t.users.map((e=>b(e))).filter(Boolean)}}async function as({users:e}){const t=await vt(new o.Api.users.GetUsers({id:e.map((({id:e,accessHash:t})=>Z(e,t)))}));if(t&&t.length)return t.forEach((e=>{e instanceof o.Api.User&&(N.users[e.id]=e)})),t.map(Ve).filter(Boolean)}function is({phone:e,firstName:t,lastName:n}){return vt(new o.Api.contacts.ImportContacts({contacts:[de({phone:e||"",firstName:t||"",lastName:n||""})]}))}async function rs({id:e,accessHash:t}){const n=ee(e,t);n instanceof o.Api.InputUser&&await vt(new o.Api.contacts.DeleteContacts({id:[n]}))&&Qn({"@type":"deleteUser",id:e})}async function os(e,t){if(e){const{id:t,accessHash:n}=e,s=await vt(new o.Api.photos.GetUserPhotos({userId:ee(t,n),limit:40,offset:0,maxId:z()("0")}));if(!s)return;return function(e){e.photos.forEach(_e)}(s),{photos:s.photos.filter((e=>e instanceof o.Api.Photo)).map(V)}}const n=await On({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}}async function cs({hash:e}){const t=await vt(new o.Api.messages.GetAllStickers({hash:e}));if(t&&!(t instanceof o.Api.messages.AllStickersNotModified))return t.sets.forEach((e=>{e.thumbs&&e.thumbs.length&&(N.stickerSets[String(e.id)]=e)})),{hash:t.hash,sets:t.sets.map(q)}}async function ds({hash:e}){const t=await vt(new o.Api.messages.GetRecentStickers({hash:e}));if(t&&!(t instanceof o.Api.messages.RecentStickersNotModified))return{hash:t.hash,stickers:Cs(t.stickers.slice(0,20))}}async function ls({hash:e}){const t=await vt(new o.Api.messages.GetFavedStickers({hash:e}));if(t&&!(t instanceof o.Api.messages.FavedStickersNotModified))return{hash:t.hash,stickers:Cs(t.stickers)}}async function us({hash:e}){const t=await vt(new o.Api.messages.GetFeaturedStickers({hash:e}));if(t&&!(t instanceof o.Api.messages.FeaturedStickersNotModified))return{hash:t.hash,sets:t.sets.map(H)}}async function gs({sticker:e,unfave:t}){const n=new o.Api.messages.FaveSticker({id:ne(e),unfave:t});await vt(n)&&Xn({"@type":"updateFavoriteStickers"})}async function ps({stickerSetShortName:e,stickerSetId:t,accessHash:n}){const s=await vt(new o.Api.messages.GetStickerSet({stickerset:t?te(t,n):(a=e,new o.Api.InputStickerSetShortName({shortName:a}))}));var a,i;if(s)return{set:q(s.set),stickers:Cs(s.documents),packs:(i=s.packs,i.reduce(((e,{emoticon:t,documents:n})=>(e[t]=n.map((e=>L(N.documents[String(e)]))).filter(Boolean),e)),{}))}}async function fs(){const e=await vt(new o.Api.messages.GetStickerSet({stickerset:new o.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:q(e.set),stickers:Cs(e.documents)}}async function hs({query:e,hash:t}){const n=await vt(new o.Api.messages.SearchStickerSets({q:e,hash:t}));if(n&&!(n instanceof o.Api.messages.FoundStickerSetsNotModified))return{hash:n.hash,sets:n.sets.map(H)}}async function ms({hash:e}){const t=await vt(new o.Api.messages.GetSavedGifs({hash:e}));if(t&&!(t instanceof o.Api.messages.SavedGifsNotModified))return{hash:t.hash,gifs:Ps(t.gifs)}}async function _s({stickerSetId:e,accessHash:t}){await vt(new o.Api.messages.InstallStickerSet({stickerset:te(e,t)}))&&Xn({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function ys({stickerSetId:e,accessHash:t}){await vt(new o.Api.messages.UninstallStickerSet({stickerset:te(e,t)}))&&Xn({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function bs({query:e,offset:t=""}){if(!Zn){const e=await vt(new o.Api.help.GetConfig);if(!e)return;const t=await vt(new o.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof o.Api.User))return;Zn=new o.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await vt(new o.Api.messages.GetInlineBotResults({bot:Zn,peer:new o.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map((e=>{if(e instanceof o.Api.BotInlineMediaResult)return e.document})).filter(Boolean);return{nextOffset:n.nextOffset,gifs:Ps(s)}}async function ws({emoji:e,hash:t=0}){const n=await vt(new o.Api.messages.GetStickers({emoticon:e,hash:t}));if(n&&!(n instanceof o.Api.messages.StickersNotModified))return{stickers:Cs(n.stickers),hash:n.hash}}async function Is({language:e,fromVersion:t}){const n=await vt(new o.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 Cs(e){return e.map((e=>{if(e instanceof o.Api.Document){const t=L(e);if(t)return N.documents[String(e.id)]=e,t}})).filter(Boolean)}function Ps(e){return e.map((e=>{if(e instanceof o.Api.Document){const t=Se(e);if(t)return N.documents[String(e.id)]=e,t}})).filter(Boolean)}async function As({username:e}){try{return await vt(new o.Api.channels.CheckUsername({channel:new o.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function vs({chat:e,username:t}){await vt(new o.Api.channels.UpdateUsername({channel:ee(e.id,e.accessHash),username:t}))&&Yn({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Ss({chat:e}){const t=await vt(new o.Api.messages.ExportChatInvite({peer:Z(e.id,e.accessHash)}));t&&t instanceof o.Api.ChatInviteExported&&Yn({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const Ms={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"},ks={};let Rs;async function Us(){const e=await vt(new o.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function Es(e){return Rs({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{ks.resolve=e,ks.reject=t}))}async function Ds(e){try{return await kt({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return Fs(e),!1}}async function Ts(e){try{return await kt({currentPassword:e}),!0}catch(e){return Fs(e),!1}}async function Bs(e,t,n,s){try{return await kt({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:Es,onEmailCodeError:Fs}),!0}catch(e){return Fs(e),!1}}async function xs(e,t){try{return await kt({currentPassword:e,newPassword:e,email:t,emailCodeCallback:Es,onEmailCodeError:Fs}),!0}catch(e){return Fs(e),!1}}function Vs(e){ks.resolve(e)}function Fs(e){let t;if(e instanceof o.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=Ms[e.message];t||(t="Unexpected Error"),Rs({"@type":"updateTwoFaError",message:t})}const Ns=["ar","fa","id","ko","uz"];function Os({firstName:e,lastName:t,about:n}){return vt(new o.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function Ls(e){return vt(new o.Api.account.CheckUsername({username:e}))}function qs(e){return vt(new o.Api.account.UpdateUsername({username:e}))}async function Hs(e){const t=await Mt(e);return vt(new o.Api.photos.UploadProfilePhoto({file:t}))}async function Gs(e){const t=await Mt(e);await vt(new o.Api.photos.UploadProfilePhoto({file:t}))}async function Ks(e){const t=await vt(new o.Api.account.GetWallPapers({hash:e}));if(!t||t instanceof o.Api.account.WallPapersNotModified)return;const n=t.wallpapers.filter((e=>e instanceof o.Api.WallPaper&&e.document instanceof o.Api.Document&&!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return n.forEach((e=>{N.documents[String(e.document.id)]=e.document})),{hash:t.hash,wallpapers:n.map(Ne).filter(Boolean)}}async function zs(e){const t=await Mt(e),n=await vt(new o.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new o.Api.WallPaperSettings}));if(!(n&&n instanceof o.Api.WallPaper))return;const s=Ne(n);return s?(N.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function Ws(){const e=await vt(new o.Api.contacts.GetBlocked({limit:100}));if(e)return ga(e),{users:e.users.map(Ve).filter(Boolean),chats:e.chats.map((e=>b(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>w(e.peerId))),totalCount:e instanceof o.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function js(e,t){return vt(new o.Api.contacts.Block({id:Z(e,t)}))}function $s(e,t){return vt(new o.Api.contacts.Unblock({id:Z(e,t)}))}async function Js(){const e=await vt(new o.Api.account.GetAuthorizations);if(e)return e.authorizations.map(Oe)}function Qs(e){return vt(new o.Api.account.ResetAuthorization({hash:z()(e)}))}function Xs(){return vt(new o.Api.auth.ResetAuthorizations)}async function Zs({serverTimeOffset:e}){const t=await vt(new o.Api.account.GetNotifyExceptions({compareSound:!0}));if(t instanceof o.Api.Updates||t instanceof o.Api.UpdatesCombined)return ga(t),t.updates.reduce(((t,n)=>n instanceof o.Api.UpdateNotifySettings&&n.peer instanceof o.Api.NotifyPeer?(t.push(qe(n.notifySettings,n.peer.peer,e)),t):t),[])}async function Ys({serverTimeOffset:e}){const[t,n,s,a]=await Promise.all([vt(new o.Api.account.GetContactSignUpNotification),vt(new o.Api.account.GetNotifySettings({peer:new o.Api.InputNotifyUsers})),vt(new o.Api.account.GetNotifySettings({peer:new o.Api.InputNotifyChats})),vt(new o.Api.account.GetNotifySettings({peer:new o.Api.InputNotifyBroadcasts}))]);if(!n||!s||!a)return!1;const{silent:i,muteUntil:r,showPreviews:c}=n,{silent:d,muteUntil:l,showPreviews:u}=s,{silent:g,muteUntil:p,showPreviews:f}=a;return{hasContactJoinedNotifications:!t,hasPrivateChatsNotifications:!(i||"number"==typeof r&&Date.now()+1e3*e<1e3*r),hasPrivateChatsMessagePreview:c,hasGroupNotifications:!(d||"number"==typeof l&&Date.now()+1e3*e<1e3*l),hasGroupMessagePreview:u,hasBroadcastNotifications:!(g||"number"==typeof p&&Date.now()+1e3*e<1e3*p),hasBroadcastMessagePreview:f}}function ea(e){return vt(new o.Api.account.SetContactSignUpNotification({silent:e}))}function ta(e,{isSilent:t,shouldShowPreviews:n}){let s;s="contact"===e?new o.Api.InputNotifyUsers:"group"===e?new o.Api.InputNotifyChats:new o.Api.InputNotifyBroadcasts;const a={showPreviews:n,silent:t,muteUntil:t?2147483647:0};return vt(new o.Api.account.UpdateNotifySettings({peer:s,settings:new o.Api.InputPeerNotifySettings(a)}))}async function na(){const e=await vt(new o.Api.langpack.GetLanguages({langPack:"android"}));if(e)return e.map(p)}async function sa({sourceLangPacks:e,langCode:t}){const n=(await Promise.all(e.map((e=>vt(new o.Api.langpack.GetLangPack({langPack:e,langCode:Ns.includes(t)?`${t}-raw`:t})))))).filter(Boolean).map((e=>c(e.strings.map(p),"key")));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function aa({langPack:e,langCode:t,keys:n}){const s=await vt(new o.Api.langpack.GetStrings({langPack:e,langCode:Ns.includes(t)?`${t}-raw`:t,keys:n}));if(s)return s.map(p)}async function ia(e){const t=pe(e),n=await vt(new o.Api.account.GetPrivacy({key:t}));if(n)return ga(n),Le(n.rules)}function ra(e){const t=bt.session.getAuthKey().getKey();return vt(new o.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function oa(e){return vt(new o.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function ca(e,t){const n=pe(e),s=[];switch(t.allowedUsers&&s.push(new o.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((({id:e,accessHash:t})=>Z(e,t)))})),t.allowedChats&&s.push(new o.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((({id:e})=>-e))})),t.blockedUsers&&s.push(new o.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((({id:e,accessHash:t})=>Z(e,t)))})),t.blockedChats&&s.push(new o.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((({id:e})=>-e))})),t.visibility){case"everybody":s.push(new o.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new o.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new o.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new o.Api.InputPrivacyValueDisallowAll)}const a=await vt(new o.Api.account.SetPrivacy({key:n,rules:s}));if(a)return ga(a),Le(a.rules)}async function da(e){await vt(new o.Api.account.UpdateStatus({offline:!e}))}async function la(){const e=await vt(new o.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function ua(e){return vt(new o.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}function ga(e){e.users.forEach((e=>{e instanceof o.Api.User&&(N.users[e.id]=e)})),e.chats.forEach((e=>{(e instanceof o.Api.Chat||e instanceof o.Api.Channel)&&(N.chats[e.id]=e)}))}function pa(e){return e?d(e,["url","mimeType"]):void 0}var fa=n(8764).Buffer;function ha({chatId:e,accessHash:t,messageId:n,data:s}){return vt(new o.Api.messages.GetBotCallbackAnswer({peer:Z(e,t),msgId:n,data:fa.from(s)}))}async function ma({hash:e=0}){const t=await vt(new o.Api.contacts.GetTopPeers({hash:e,botsInline:!0}));if(!(t instanceof o.Api.contacts.TopPeers))return;const n=t.users.map(Ve).filter(Boolean),s=n.map((({id:e})=>e));return{hash:oe(s),ids:s,users:n}}async function _a({username:e}){const t=await vt(new o.Api.contacts.ResolveUsername({username:e}));if(t&&t.users[0]instanceof o.Api.User&&t.users[0].bot&&t.users[0].botInlinePlaceholder)return wa(t.users[0]),{user:Ve(t.users[0]),chat:b(t.users[0])}}async function ya({bot:e,chat:t,query:n,offset:s=""}){const a=await vt(new o.Api.messages.GetInlineBotResults({bot:Z(e.id,e.accessHash),peer:Z(t.id,t.accessHash),query:n,offset:s}));var i,r,c,l,u;if(a)return a.users.map(wa),{isGallery:Boolean(a.gallery),help:e.botPlaceholder,nextOffset:(l=e.username,u=a.nextOffset,"gif"===l&&"0"===u?"":u),switchPm:(c=a.switchPm,c?d(c,["text","startParam"]):void 0),users:a.users.map(Ve).filter(Boolean),results:(i=String(a.queryId),r=a.results,r.map((e=>{return e instanceof o.Api.BotInlineMediaResult?(e.document instanceof o.Api.Document&&(t=e.document,N.documents[String(t.id)]=t),e.photo instanceof o.Api.Photo&&(n=e.photo,N.photos[String(n.id)]=n),function(e,t){const{id:n,type:s,title:a,description:i,photo:r,document:c}=e;return{id:n,queryId:t,type:s,title:a,description:i,..."sticker"===s&&c instanceof o.Api.Document&&{sticker:L(c)},...r instanceof o.Api.Photo&&{photo:V(r)},..."gif"===s&&c instanceof o.Api.Document&&{gif:Se(c)},..."video"===s&&c instanceof o.Api.Document&&{thumbnail:x(c.thumbs)}}}(e,i)):(e.thumb&&(s=e.thumb,N.webDocuments[s.url]=s),function(e,t){const{id:n,type:s,title:a,description:i,url:r,thumb:o}=e;return{id:n,queryId:t,type:s,title:a,description:i,url:r,webThumbnail:pa(o)}}(e,i));var t,n,s})))}}async function ba({chat:e,resultId:t,queryId:n,replyingTo:s}){const a=ae();await vt(new o.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:a,queryId:z()(n),peer:Z(e.id,e.accessHash),id:t,...s&&{replyToMsgId:s}}),!0)}function wa(e){N.users[e.id]=e}function Ia(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 Ca({chat:e,messageId:t,requestInfo:n,shouldSave:s}){const a=await vt(new o.Api.payments.ValidateRequestedInfo({peer:Z(e.id,e.accessHash),msgId:t,save:s||void 0,info:ge(n)}));if(!a)return;const{id:i,shippingOptions:r}=a;return i?{id:i,shippingOptions:Ia(r)}:void 0}function Pa({chat:e,messageId:t,formId:n,requestedInfoId:s,shippingOptionId:a,credentials:i}){return vt(new o.Api.payments.SendPaymentForm({formId:z()(n),peer:Z(e.id,e.accessHash),msgId:t,requestedInfoId:s,shippingOptionId:a,credentials:new o.Api.InputPaymentCredentials({save:i.save,data:new o.Api.DataJSON({data:JSON.stringify(i.data)})})}),!0)}async function Aa({chat:e,messageId:t}){const n=await vt(new o.Api.payments.GetPaymentForm({peer:Z(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{formId:t,canSaveCredentials:n,passwordMissing:s,providerId:a,nativeProvider:i,nativeParams:r,savedInfo:o,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=r?JSON.parse(r.data):{};return{canSaveCredentials:n,passwordMissing:s,formId:String(t),providerId:a,nativeProvider:i,savedInfo:o,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 va(e,t){const n=await vt(new o.Api.payments.GetPaymentReceipt({peer:Z(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{invoice:t,info:n,shipping:s,currency:a,totalAmount:i,credentialsTitle:r}=e,{shippingAddress:o,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:o,phone:c,name:d},totalAmount:Number(i.value),credentialsTitle:r,shippingPrices:g,shippingMethod:p}}(n)}let Sa;async function Ma(e,t){Sa=e,function(e){be=e}(Da),function(e){je=e}(Da),function(e){Et=e}(Da),function(e){In=e}(Da),function(e){Qn=e}(Da),function(e){Xn=e}(Da),function(e){Yn=e}(Da),function(e){Rs=e}(Da),await async function(e,t){yt=e;const{userAgent:n,platform:s,sessionData:a}=t,i=new o.sessions.CallbackSession(a,Pt);bt=new o.TelegramClient(i,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",appVersion:"1.10.4 Z",useWSS:!0,additionalDcsDisabled:!1}),bt.addEventHandler(At,_t),bt.addEventHandler(Ke,_t);try{try{await bt.start({phoneNumber:$e,phoneCode:Je,password:Qe,firstAndLastNames:Xe,qrCode:Ze,onError:Ye,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if("Disconnect"!==e.message)return void yt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}je(et("authorizationStateReady")),Pt(i.getSessionData()),yt({"@type":"updateApiReady"}),Rt()}catch(e){throw e}}(Da,t)}const ka=function(e,t){let n,s=!1;return(...a)=>{n=a,s||(s=!0,e((()=>{s=!1,t(...n)})))}}((function(e){Promise.resolve().then(e)}),(function(e){if(!Ea||e!==Ua)return;const t=Ea;Ea=void 0,t.forEach(Sa)}));let Ra,Ua,Ea;function Da(e){Ea?Ea.push(e):Ea=[e],Ra&&!r.has(e["@type"])||(Ra=function(e,t,n=!0){let s,a,i;return(...r)=>{a=!0,i=r,s||(n&&(a=!1,e(...i)),s=self.setInterval((()=>{if(!a)return self.clearInterval(s),void(s=void 0);a=!1,e(...i)}),t))}}(ka,i,!0),Ua=Math.random()),Ra(Ua)}self.onerror=e=>{console.error(e),xa({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),xa({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const Ta=new Map;function Ba(e){xa({type:"update",update:e})}function xa(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await Ma(Ba,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];xa({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ta.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&&xa({type:"methodResponse",messageId:e,response:t},i)}catch(t){e&&xa({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ta.delete(e);break}case"cancelProgress":{const e=Ta.get(t.messageId);e&&(e.isCanceled=!0);break}}}},9618:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(6842);function r(e,t=!0,n=!1){let i=s.from(e);const r=i.length;t&&(i=i.reverse());let o=a(i.toString("hex"),16);return n&&Math.floor(o.toString("2").length/8)>=r&&(o=o.subtract(a(2).pow(a(8*r)))),o}function o(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=o(e,16),t=o(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:o,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:r,readBufferFromBigInt:o,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 o(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=r(e,!1),n=l(a(b),t,g);if(m(n,g)){const e=h(n),i=r(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(I),T=k.add(D),B=l(E,T,g),[x,V,F,N,O]=await Promise.all([c(h(B)),c(C),c(P),c(n.salt1),c(n.salt2)]),L=await c(s.concat([_(V,F),N,O,R,A,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:L})},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),r(await y(e,t),!1),r(e.p,!1)))}}},8960:(e,t,n)=>{var s=n(8764).Buffer;const{constructors:a}=n(7404),i=s.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),r=s.from("ffd9","hex");function o(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);o(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 o(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),r])},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),r=n(9674),o=n(7873),c=n.n(o),d=n(8764).Buffer;async function l(e,{isCheckPassword:t,currentPassword:n,newPassword:s,hint:o="",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,r.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,r.computeDigest)(p.newAlgo,s):d.alloc(0),hint:o,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:r}=n(9618),o=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:I}=n(243),C=131072,P=["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 r={...A.DEFAULT_OPTIONS,...s};if(this.apiId=t,this.apiHash=n,this._useIPV6=r.useIPV6,"string"==typeof r.baseLogger?this._log=new i:this._log=r.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=r.floodSleepLimit,this._eventBuilders=[],this._phoneCodeHash={},this.session=e,this.apiId=parseInt(t,10),this.apiHash=n,this._requestRetries=r.requestRetries,this._connectionRetries=r.connectionRetries,this._retryDelay=r.retryDelay||0,r.proxy&&this._log.warn("proxies are not supported"),this._proxy=r.proxy,this._timeout=r.timeout,this._autoReconnect=r.autoReconnect,this._connection=r.connection,this._floodWaitedRequests={},this._initWith=e=>new f.InvokeWithLayer({layer:g,query:new f.InitConnection({apiId:this.apiId,deviceModel:r.deviceModel||a.type().toString()||"Unknown",systemVersion:r.systemVersion||a.release().toString()||"1.0",appVersion:r.appVersion||"1.0",langCode:r.langCode,langPack:"",systemLangCode:r.systemLangCode,query:e,proxy:void 0})}),this._args=r,this._config=void 0,this.phoneCodeHashes=[],this._exportedSenderPromises={},this._exportedSenderReleaseTimeouts={},this._additionalDcsDisabled=r.additionalDcsDisabled,this._loopStarted=!1,this._reconnecting=!1,this._destroyed=!1}async connect(){await this._initSession(),void 0===this._sender&&(this._sender=new h(this.session.getAuthKey(),{logger:this._log,dcId:this.session.dcId,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),updateCallback:this._handleUpdate.bind(this),isMainSender:!0})),this._sender.userDisconnected=!1,this._sender._user_connected=!1,this._sender._reconnecting=!1,this._sender._disconnected=!0;const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log);await this._sender.connect(e)?(this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new f.help.GetConfig({}))),this._loopStarted||(this._updateLoop(),this._loopStarted=!0),this._reconnecting=!1):this._loopStarted||(this._updateLoop(),this._loopStarted=!0)}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"zws2.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;!this._destroyed;)if(await d.sleep(3e3),!this._reconnecting){try{await k((()=>{return e=this._sender.send(new f.PingDelayDisconnect({pingId:d.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),disconnectDelay:6e4})),5e3,Promise.race([e,d.sleep(5e3).then((()=>Promise.reject(new Error("TIMEOUT"))))]);var e}),3,100)}catch(e){if(console.warn(e),this._reconnecting)continue;await this.disconnect(),await this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new f.updates.GetState)}catch(e){}}await this.disconnect()}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._exportedSenderPromises).map((e=>e&&e.then((e=>{if(e)return e.disconnect()}))))),this._exportedSenderPromises={}}async destroy(){this._destroyed=!0;try{await this.disconnect()}catch(e){}this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info(`Reconnecting to new data center ${e}`);const t=l.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),this._reconnecting=!0,await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}async _cleanupExportedSender(e){this.session.dcId!==e&&this.session.setAuthKey(void 0,e);const t=await this._exportedSenderPromises[e];this._exportedSenderPromises[e]=void 0,await t.disconnect()}async _connectSender(e,t){const n=l.getDC(t,!!e.authKey.getKey());for(;;)try{if(await e.connect(new this._connection(n.ipAddress,n.port,t,this._log)),this.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=P.indexOf(t);se.type===P[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:C}),a=await this._borrowExportedSender(4),i=await a.send(s);if(n+=131072,!i.bytes.length)break;if(t.push(i.bytes),i.bytes.length{"use strict";n.r(t),n.d(t,{authFlow:()=>l,checkAuthorization:()=>u});var s=n(7150),a=n.n(s),i=n(8960),r=n.n(i),o=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:r}=n,{user:o}=await e.invoke(new(a().auth.ImportBotAuthorization)({apiId:s,apiHash:i,botAuthToken:r}));return o}(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",r().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,r,o=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return p(e,t,n);throw s}else s=n.phoneNumber;const a=await f(e,t,s,n.forceSMS);if(i=a.phoneCodeHash,o=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{r=await n.phoneCode(o)}catch(s){if("RESTART_AUTH"===s.message)return g(e,t,n)}if(!r)throw new Error("Code is empty");const l=await e.invoke(new(a().auth.SignIn)({phoneNumber:s,phoneCodeHash:i,phoneCode:r}));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,r]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:o}=await e.invoke(new(a().auth.SignUp)({phoneNumber:s,phoneCodeHash:i,firstName:t,lastName:r}));return c&&await e.invoke(new(a().help.AcceptTermsOfService)({id:c.id})),o}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,o.sleep)(3e4)])}})(),r=new Promise((t=>{e.addEventHandler((e=>{e instanceof a().UpdateLoginToken&&t()}),{build:e=>e})}));try{await Promise.race([r,i])}catch(s){if("RESTART_AUTH"===s.message)return 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:r}=t,o=await e.invoke(new(a().auth.SendCode)({phoneNumber:n,apiId:i,apiHash:r,settings:new(a().CodeSettings)}));if(!s||o.type instanceof a().auth.SentCodeTypeSms)return{phoneCodeHash:o.phoneCodeHash,isCodeViaApp:o.type instanceof a().auth.SentCodeTypeApp};const c=await e.invoke(new(a().auth.ResendCode)({phoneNumber:n,phoneCodeHash:o.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:r}=await e.invoke(new(a().auth.CheckPassword)({password:i}));return r}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),r=n(9618),o=n(7873),c=n.n(o),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,r.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:o}=n;const{fileSize:l,workers:p=1}=n,{dcId:f,progressCallback:h,start:m=0}=n;o=o&&o{for(;;){let d;try{d=await e.getSender(f);const r=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");P+=1/y,h(P)}return!o&&r.bytes.lengtho)break}const A=(await Promise.all(w)).filter(Boolean),v=o?o+1-m:void 0;return d.concat(A,v)}},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),r=n(8960),o=n(7873),c=n.n(o),d=n(8764).Buffer;async function l(e,t){const{file:n,onProgress:s}=t;let{workers:o}=t;const{name:l,size:u}=n,g=(0,i.readBigIntFromBuffer)((0,i.generateRandomBytes)(8),!0,!0),p=u>10485760,f=1024*(0,r.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),o&&u||(o=1),o>=h&&(o=h);let _=0;s&&s(_);for(let t=0;th&&(r=h);for(let o=t;o{for(;;){let r;try{r=await e.getSender(e.session.dcId),await r.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(r&&!r.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}})(o,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:r,readBigIntFromBuffer:o}=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,r(this.auxHash,8,!0)])]),d=(await a(c)).slice(4,20);return o(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)),r=s.randBetween(s(1),e.minus(1));let o,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(o=s.zero;o.lesser(d)&&c.eq(s.one);){g=t;const p=s.min(r,d.minus(o));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),o=o.add(r)}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:()=>r,isBigEndian:()=>o,i2ab:()=>c,ab2i:()=>d});const o=1===new Uint8Array(new Uint32Array([16909060]))[0],c=o?a:s,d=o?r:i},6842:(e,t,n)=>{var s=n(8764).Buffer;const a=n(8136).default,{i2ab:i,ab2i:r}=n(4121),{getWords:o}=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(o(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 r extends Error{constructor(e,t){let n=r.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=` Caused by ${e.className}`,super(n),this.message=n,this.code=t}}var o,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(o=r)?Object.defineProperty(o,c,{value:d,enumerable:!0,configurable:!0,writable:!0}):o[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:r}},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:r}=n(6952);class o 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 r{constructor(e){const t=Number(e.capture||0);super(`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`),this.message=`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`,this.codeLength=t}}const 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+)/,o],[/NETWORK_MIGRATE_(\d+)/,f],[/EMAIL_UNCONFIRMED_(\d+)/,h]];e.exports={rpcErrorRe:m,FileMigrateError:p,FloodTestPhoneWaitError:g,FloodWaitError:l,PhoneMigrateError:c,SlowModeWaitError:d,UserMigrateError:o,NetworkMigrateError:f,MsgWaitError:u,EmailUnconfirmedError:h}},7873:(e,t,n)=>{const{RPCError:s}=n(6952),{rpcErrorRe:a}=n(5651),i=n(8187),r=n(6952),o=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,...r,...o}},6316:()=>{},3903:(e,t,n)=>{const{EventBuilder:s}=n(6172);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},6172:e=>{e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},3182:(e,t,n)=>{const s=n(6316),a=n(3903);class i extends Error{}e.exports={NewMessage:s,StopPropagation:i,Raw:a}},6151:e=>{e.exports=class{constructor(){this._queue=[],this.canGet=new Promise((e=>{this.resolveGet=e})),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise((e=>{this.resolvePush=e}))}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise((e=>{this.resolveGet=e})),e}}},5544:(e,t,n)=>{const{TypeNotFoundError:s}=n(8187),{coreObjects:a}=n(2058),{tlobjects:i}=n(845),{readBigIntFromBuffer:r}=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 r(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error(`Invalid boolean code ${e.toString("16")}`)}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=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),r=n(6472),o=["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&&o.includes(e.request.className))for(let t=this._queue.length-1;t>=0;t--)if(o.includes(this._queue[t].request.className)){e.after=this._queue[t];break}this._queue.push(e),this.setReady(!0),e&&(this._pendingStates.push(e),e.promise.catch((()=>{})).finally((()=>{this._pendingStates=this._pendingStates.filter((t=>t!==e))})))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise((e=>{this.setReady=e})),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,t=new r(s.alloc(0));const n=[];let o=0;for(;this._queue.length&&n.length<=a.MAXIMUM_LENGTH;){const e=this._queue.shift();if(o+=e.data.length+i.SIZE_OVERHEAD,o<=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"),o=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 r(s.alloc(0));const o=await this._state.writeDataAsMessage(t,e,!1);for(const e of n)e.containerId=o}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,r=n(5840).w3cwebsocket,o=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 o;if(await this.canRead,this.closed)throw o;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 o;const e=this.stream;return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),e}getWebSocketLink(e,t){return 443===t?`wss://${e}:${t}/apiws`:`ws://${e}:${t}/apiws`}connect(e,t){return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),this.closed=!1,this.website=this.getWebSocketLink(t,e),this.client=new r(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 o;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}receive(){this.client.onmessage=async e=>{const t=await i.acquire();try{const n=e.data instanceof ArrayBuffer?s.from(e.data):s.from(await new Response(e.data).arrayBuffer());this.stream=s.concat([this.stream,n]),this.resolveRead(!0)}finally{t()}}}}},9832:(e,t,n)=>{const s=n(6748),a=n(6472),i=n(5544),r=n(7214),o=n(6411),c=n(6151);e.exports={BinaryWriter:a,BinaryReader:i,MessagePacker:o,AsyncQueue:c,Logger:s,PromisedWebSockets:r}},3522:(e,t,n)=>{const s=n(7150),a=n(8742),i=n(8415),r=n(7404),o=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:r,version:o,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),r=n(4736),o=n.n(r);n(9618),n(8764).Buffer;const c=[{fingerprint:o()("-3414540481677951611"),n:o()("29379598170669337022986177149456128565388431120058863768162556424047512191330847455146576344487764408661701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531316010870401287642763009136156734339538042419388722777357134487746169093539093850251243897188928735903389451772730245253062963384108812842079887538976360465290946139638691491496062099570836476454855996319192747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323"),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),r=await e.send(new(a().ReqPqMulti)({nonce:s}));if(t.debug("Starting authKey generation step 1"),!(r instanceof a().ResPQ))throw new i.SecurityError(`Step 1 answer was ${r}`);if(r.nonce.neq(s))throw new i.SecurityError("Step 1 invalid nonce from server");const o=h.readBigIntFromBuffer(r.pq,!1,!0);t.debug("Finished authKey generation step 1");const{p:c,q:_}=f.factorize(o),y=h.getByteArray(c),b=h.getByteArray(_);n=h.generateRandomBytes(32);const w=h.readBigIntFromBuffer(n,!0,!0),I=new(a().PQInnerData)({pq:h.getByteArray(o),p:y,q:b,nonce:r.nonce,serverNonce:r.serverNonce,newNonce:w}).getBytes();if(I.length>144)throw new i.SecurityError("Step 1 invalid nonce from server");let C,P;for(const e of r.serverPublicKeyFingerprints)if(P=d.get(e.toString()),void 0!==P){C=e;break}if(void 0===C||void 0===P)throw new i.SecurityError("Step 2 could not find a valid key for fingerprints");const A=h.generateRandomBytes(192-I.length),v=l.concat([I,A]),S=l.from(v).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(l.concat([e,v])),s=l.concat([S,n]),a=new g(e,l.alloc(32)).encryptIge(s),i=h.bufferXor(e,await h.sha256(a)),r=l.concat([i,a]),o=h.readBigIntFromBuffer(r,!1,!1);if(o.greaterOrEquals(P.n)){t.debug("Aes key greater than RSA. retrying");continue}const c=h.modExp(o,u(P.e),P.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:r.nonce,serverNonce:r.serverNonce,p:y,q:b,publicKeyFingerprint:C,encryptedData:M}));if(!(k instanceof a().ServerDHParamsOk||k instanceof a().ServerDHParamsFail))throw new Error(`Step 2.1 answer was ${k}`);if(k.nonce.neq(r.nonce))throw new i.SecurityError("Step 2 invalid nonce from server");if(k.serverNonce.neq(r.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(r.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(r.nonce))throw new i.SecurityError("Step 3 Invalid nonce in encrypted answer");if(B.serverNonce.neq(r.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),F=B.serverTime-Math.floor((new Date).getTime()/1e3),N=h.readBigIntFromBuffer(h.generateRandomBytes(256),!1,!1),O=h.modExp(u(B.g),N,x),L=h.modExp(V,N,x),q=new(a().ClientDHInnerData)({nonce:r.nonce,serverNonce:r.serverNonce,retryId:u.zero,gB:h.getByteArray(O,!1)}).getBytes(),H=l.concat([await h.sha1(q),q]),G=E.encryptIge(H),K=await e.send(new(a().SetClientDHParams)({nonce:r.nonce,serverNonce:r.serverNonce,encryptedData:G})),z=[a().DhGenOk,a().DhGenRetry,a().DhGenFail];if(!(K instanceof z[0]||K instanceof z[1]||K instanceof z[2]))throw new Error(`Step 3.1 answer was ${K}`);const{name:W}=K.constructor;if(K.nonce.neq(r.nonce))throw new i.SecurityError(`Step 3 invalid ${W} nonce from server`);if(K.serverNonce.neq(r.serverNonce))throw new i.SecurityError(`Step 3 invalid ${W} server nonce from server`);const j=new p;await j.setKey(h.getByteArray(L));const $=1+["DhGenOk","DhGenRetry","DhGenFail"].indexOf(K.className),J=await j.calcNewNonceHash(w,$);if(K[`newNonceHash${$}`].neq(J))throw new i.SecurityError("Step 3 invalid new nonce hash");if(!(K instanceof a().DhGenOk))throw new Error(`Step 3.2 answer was ${K}`);return t.debug("Finished authKey generation step 3"),{authKey:j,timeOffset:F}}},5585:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9109),r=n(5544),{InvalidBufferError:o}=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 o(t);const u=new r(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 s=n(5585),a=n(9109),i=n(9618),r=n(3302),{doAuthentication:o}=n(9870),c=n(2301),d=n(3254),l=n(8963),u=n(4287),{MsgsAck:g,upload:p,MsgsStateInfo:f,Pong:h}=n(7404).constructors,m=n(6411),_=n(5544),{UpdateConnectionState:y,UpdateServerTimeOffset:b}=n(8415),{BadMessageError:w}=n(8187),{BadServerSalt:I,BadMsgNotification:C,MsgDetailedInfo:P,MsgNewDetailedInfo:A,NewSessionCreated:v,FutureSalts:S,MsgsStateReq:M,MsgResendReq:k,MsgsAllInfo:R}=n(7404).constructors,{SecurityError:U}=n(8187),{InvalidBufferError:E}=n(8187),{LogOut:D}=n(7404).requests.auth,{RPCMessageToError:T}=n(7873),{TypeNotFoundError:B}=n(8187);class x{constructor(e,t){const n={...x.DEFAULT_OPTIONS,...t};this._connection=void 0,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this.userDisconnected=!1,this._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new r,this._state=new a(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[d.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[l.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[I.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[C.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[P.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[A.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[v.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[g.CONSTRUCTOR_ID]:this._handleAck.bind(this),[S.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[R.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{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);await this.connect(e,!0),this._reconnecting=!1;for(const e of Object.values(this._pending_state))e.deferred.resolve();this._pending_state={},this._autoReconnectCallback&&await this._autoReconnectCallback()}}var V,F,N;N={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(V=x)?Object.defineProperty(V,F,{value:N,enumerable:!0,configurable:!0,writable:!0}):V[F]=N,e.exports=x},9109:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9618),r=n(2608),o=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.reset()}reset(){this.id=i.generateRandomLong(!0),this._sequence=0,this._lastMsgId=a(0)}updateMessageId(e){e.msgId=this._getNewMsgId()}async _calcKey(e,t,n){const a=!0===n?0:8,[r,o]=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([r.slice(0,8),o.slice(8,24),r.slice(24,32)]),iv:s.concat([o.slice(0,8),r.slice(8,24),o.slice(24,32)])}}async writeDataAsMessage(e,t,n,a){const i=this._getNewMsgId(),r=this._getSeqNo(n);let o;o=a?await c.gzipIfSmaller(n,new g(a,{getBytes:()=>t}).getBytes()):await c.gzipIfSmaller(n,t);const d=s.alloc(4);d.writeInt32LE(r,0);const l=s.alloc(4);l.writeInt32LE(o.length,0);const u=p(i,8);return e.write(s.concat([u,d,l])),e.write(o),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),o=(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(),o,!0),l=i.readBufferFromBigInt(this.authKey.keyId,8);return s.concat([l,o,new r(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 r(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 o(e);if(g.readLong(),!g.readLong().eq(this.id))throw new l("Server replied with a wrong session ID");const p=g.readLong(),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 r{constructor(e,t,n,r){s(this,"PacketCodecClass",void 0),this._ip=e,this._port=t,this._dcId=n,this._log=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),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:r,PacketCodec:class{constructor(e){this._conn=e}encodePacket(e){throw new Error("Not Implemented")}readPacket(e){throw new Error("Not Implemented")}},ObfuscatedConnection:class extends r{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:r}=n(9618),{Connection:o,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"),r(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 o{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:r}=n(4353),{AbridgedPacketCodec:o}=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(),r=s.from(n.slice(8,40)),o=s.from(n.slice(40,56)),d=s.from(a.slice(0,32)),l=s.from(a.slice(32,48)),u=new c(r,o),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 r{constructor(...e){super(...e),a(this,"ObfuscatedIO",d),a(this,"PacketCodecClass",o)}}}},417:(e,t,n)=>{const{Connection:s}=n(4353),{ConnectionTCPFull:a}=n(5484),{ConnectionTCPAbridged:i}=n(6302),{ConnectionTCPObfuscated:r}=n(2986);e.exports={Connection:s,ConnectionTCPFull:a,ConnectionTCPAbridged:i,ConnectionTCPObfuscated:r}},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 r{constructor(e){this.state=e}}s(r,"disconnected",-1),s(r,"connected",1),s(r,"broken",0);const{Connection:o,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(417);e.exports={Connection:o,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:a,MTProtoSender:i,UpdateConnectionState:r,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),r=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:o}=r.getDC(e);this.setDC(e,a,o,!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),r=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:o,port:c}=r.getDC(t);this.setDC(t,o,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:o}=r.getDC(n);this.setDC(n,a,o);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),r=n(5544);class o extends a{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=o.decode(e),n=new r(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"+o.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=o},5886:(e,t,n)=>{const s=n(3995),a=n(2433),i=n(926),r=n(1753),o=n(5945),c=n(7);e.exports={Memory:s,StringSession:a,CacheApiSession:i,LocalStorageSession:r,IdbSession:o,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:131,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:r,serializeDate:o}=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 r(e);case"Bool":return e?s.from("b5757299","hex"):s.from("379779bc","hex");case"true":return s.alloc(0);case"bytes":return r(e);case"date":return o(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#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#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#bba51639 call:InputGroupCall time_ms:long scale:int = InputFileLocation;\npeerUser#9db1bc6d user_id:int = Peer;\npeerChat#bad0e5bb chat_id:int = Peer;\npeerChannel#bddde532 channel_id:int = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#200250ba id:int = User;\nuser#938458c1 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:int access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#9ba2d800 id:int = Chat;\nchat#3bda1bde flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true id:int title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#7328bdb id:int title:string = Chat;\nchannel#d31a961e flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true id:int access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int version:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#289da732 flags:# broadcast:flags.5?true megagroup:flags.8?true id:int access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#8a1e2983 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:int about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer = ChatFull;\nchannelFull#548c3f93 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:int about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?int migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?int location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer = ChatFull;\nchatParticipant#c8d7493e user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantCreator#da13538a user_id:int = ChatParticipant;\nchatParticipantAdmin#e2d6e436 user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3f460fed chat_id:int participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#bce383d2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#cbf24940 phone_number:string first_name:string last_name:string vcard:string user_id:int = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#a6638b9a title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#488a7337 users:Vector = MessageAction;\nmessageActionChatDeleteUser#b2ae9b0c user_id:int = MessageAction;\nmessageActionChatJoinedByLink#f89cf5e8 inviter_id:int = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#51bdb021 channel_id:int = MessageAction;\nmessageActionChannelMigrateFrom#b055eaee title:string chat_id:int = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#76b9f11a call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#df969c2d id:int bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#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#139a9a77 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector